0

I need to output a grid array that gives me an output of:

1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24

This is the code I have at this moment:

    public static void printGrid(){
    int x = 0, y = 0;
    int[][] grid = new int[4][6];
    for(int i=1; i<=(4*6); i++){
        x++;
        if(i%4 == 0){
            y++;
            x = 0;
        }
    }

}

Any and all help is greatly appreciated.

DPabst
  • 35
  • 1
  • 7
  • 2
    what is your output now, Are you stuck in printing grid data? – RamPrakash Feb 23 '17 at 19:01
  • I don't get any output yet, I'm still trying to figure out how to output the result. on the plus side it will compile now, which it did not do before. – DPabst Feb 23 '17 at 19:10

3 Answers3

0

The easiest way to go about this is probably with a two dimensional array. This is an array that contains arrays inside of it. These are native to java, and can be declared like so:

int[][] nameOfArray = new int[numOfArrays][lengthOfEachArray]

Using these, you can fill this array such that the array contains 1-4, the second contains 5-8, and so on. Then, you can print out the first value of each array on the same line, go to the next line, print out the second value of each array on that line, and so on. If you do that, you should be able to print out what you want to. If you need help with the syntax of 2D arrays, refer here for a good answer explaining how they work. Good luck with the implementation!

Community
  • 1
  • 1
Lavaman65
  • 863
  • 1
  • 12
  • 22
0

You could do something like this:

int x = 0, y = 0, sizeX = 5, sizeY = 5;
int[][] name = new int[sizeX][sizeY]
for(int i = 1; i <= (sizeX*sizeY); i++) {        
    x++;
    if(i%sizeX == 0) {
        y++;
        x = 0;
    }
    name[x][y] = numberAtThisPoint;
}

This is also a fairly efficient way because it uses only one for loop, however you have to use modulus.

With modulus you can make the next row of the grid by taking how many columns you want "sizeX" and checking to see if the current column that the loop is on "i" is equal to 0.

You may have to change it a little to produce the output that you are looking for.

0

If you don't want to use modulus, this is one way you can do it. It has a nested for loop, so in you will have a ~O(n^2) time complexity. (Not counting the method which prints the array, but you could easily put the print calls into the getGrid method)

public static int[][] getGrid(int height, int length) {
    int[][] grid = new int[height][length];
    int k;
    for (int i = 0; i < height; i++) {
        k = i;
        for (int j = 0; j < length; j++) {
            grid[i][j] = k+1;
            k += height;
        }
    }
    return grid;
}

public static void printGrid(int[][] grid) {
    for(int i = 0; i < grid.length; i++) {
        for(int j = 0; j < grid[i].length; j++) {
            System.out.print(grid[i][j] + " ");
        }
        System.out.println();
    }
}
Linxy
  • 2,525
  • 3
  • 22
  • 37