javaarraysalgorithmmultidimensional-arrayarray-algorithms

Return multidimensional array from given array


I have the following array: [1,2,3,4,5,6,7,8,9]

And I have to return based on a group and step parameters the following values

E.g.:

group = 3; step = 3;

[
[1,2,3],
[4,5,6],
[7,8,9],
[1,2,3]
]

group = 3; step = 2;

[
[1,2,3],
[3,4,5],
[5,6,7],
[7,8,9],
[9,1,2],
[2,3,4],
[4,5,6],
[6,7,8],
[8,9,1],
[1,2,3]
]

group = 3; step = 4;

[
[1,2,3],
[5,6,7],
[9,1,2],
[4,5,6],
[8,9,1],
[3,4,5],
[7,8,9],
[2,3,4],
[6,7,8],
[1,2,3]
]

So far I have this code snippet (in Java):

public static String[][] arrayOfArrays(String[] arr, int step, int group) {
        int size = (arr.length / step) + 1;
        String[][] list = new String[size][group];
        int start = 0;
        for (int i = 0; i < size; i++) {
            for(int j = 0; j < group; j++) {
                list[i][j] = arr[start];
                start++;
            }
            if(start == arr.length) {
                start = 0;
            }
        }
        return list;
    }

I am new to algorithms and I want to understand how should I start thinking in order to solve the problem?

Thank you


Solution

  • Not much experience here either, but I'll try and help as it seems really interesting. I used your code and changed the returned array to an array of ints to match your example.

    Edit: Thanks to the answer of @RoyceIrving I understood the logic behind how many inner-arrays are there. I now believe my solution answer your needs.


    Take a look:

    public static int[][] arrayOfArrays(int[] arr, int step, int group) {
        int size = (arr.length % step == 0) ? step + 1 : arr.length + 1;
        int[][] list = new int[size][group];
        for (int i = 0; i < size; i++) {
            int stepper = (step*i) % arr.length;
            for(int j = 0; j < group; j++) {
                list[i][j] = arr[stepper];
                stepper++;
                if (stepper == arr.length) {
                    stepper = 0;
                }
            }
        }
        return list;
    }
    

    Note the major changes: