Search code examples
javaarraysalgorithmjagged-arraysragged

how can i make shorter my Jagged(Ragged ) code?


How can i write a shorter code with a for loop, Is it possible? instead of writing;

    int array[][] = new int[10][];
    array[0] = new int[1];
    array[1] = new int[2];
    array[2] = new int[3];
    array[3] = new int[4];
    array[4] = new int[5];
    array[5] = new int[6];
    array[6] = new int[7];
    array[7] = new int[8];
    array[8] = new int[9];
    array[9] = new int[10];

Here is my code;

    int array[][] = new int[10][];
    array[0] = new int[1];
    array[1] = new int[2];
    array[2] = new int[3];
    array[3] = new int[4];
    array[4] = new int[5];
    array[5] = new int[6];
    array[6] = new int[7];
    array[7] = new int[8];
    array[8] = new int[9];
    array[9] = new int[10];

    for (int i = 0; i < 10; i++){
        for (int j = 0; j < i + 1; j++) {
            array[i][j] = i + j;
        }
    }
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < i + 1; j++)
            System.out.printf("%-4d",array[i][j]);
        System.out.println();
    }

}

}


Solution

  • For a generic solution, if you decide to change the length of the array

    int array[][] = new int[10][];
    
    for (int i = 0; i < array.length; i++) {
        array[i] = new int[i + 1];
    }
    

    You could also combine the two loops like

        for (int i = 0; i < array.length; i++) {
            array[i] = new int[i + 1];
            for (int j = 0; j < i + 1; j++) {
                array[i][j] = i + j;
            }
        }