Search code examples
javasortingmatrixmodulodivide

Why is the modulo and division used in the matrix function?


 Actor[][] toMatrix(Actor[] arr) {
    int size = (int) round(sqrt(arr.length));
    Actor[][] matrix = new Actor[size][size];
    for (int i = 0; i < arr.length; i++) {
       *** matrix[i / size][i % size] = arr[i]; ***
    }
    return matrix;
}

I'm unable to understand what that particular line of code does.


Solution

  • Let's try an example here:

    String[] test = {"John Doe","Actor","Jane Doe","Actress"};
    
    int size = (int) Math.round(Math.sqrt(arr.length)); -> 2
    

    So we're creating a [2][2] array.

    Iterating over the size of arr (=4):

    0 -> [0/2 -> 0][0%2 -> 0] = arr[0]
    1 -> [1/2 -> 0][1%2 -> 1] = arr[1]
    2 -> [2/2 -> 1][2%2 -> 0] = arr[2]
    3 -> [3/2 -> 1][3%2 -> 1] = arr[3] 
    

    So the rest of the division is used to determine the index in the second dimension of the array.

    The output will look like:

    [[John Doe, Actor], [Jane Doe, Actress]]