0

I am having trouble with dividing a 2D array into boxes, like in Sudoku. I have an array of squares in my board object, and I want to divide them into 2x3 or 3x3 boxes, The box objects have a 1D array to keep track of the squares.

k is the box number, in a 9x9 sudoku, the boxes will be numbered 0 through 8.

int l = 0;
for(int i=k*a; i<k*a+a;i++){
        for(int j=k*b;j<k*b+b;j++){
            narray[l]=brd.getSquare(i,j);
            brd.getSquare(i,j).setBox(this);
            l++;
    }

This gets the first box right, but goes off after that. I've been thinking about this for hours now, and I can't seem to wrap my head around it. Does anyone have a neat trick for this?

3 Answers3

1

So, I'll assume the boxes are numbered like this:

012
345
678

(and the boxes consist of 3x3 cells each)

If i and j are x and y coordinates, you'll need to translate the above to coordinates. Something like:

  0 1 2 3 4 5 6 7 8

x 0 1 2 0 1 2 0 1 2
y 0 0 0 1 1 1 2 2 2

So x = k%3 and y = k/3.

In the actual grid x and y has to start from 0, 3 and 6 rather than 0, 1 and 2, so just multiply by 3.

So something like this should do it: (changes depending on which coordinate is x and which is y)

int size = 3;
int l = 0;
for(int i = 0; i < size; i++){
    for(int j = 0; j < size; j++){
        int x = i + k % size * size;
        int y = j + k / size * size;
        narray[l] = brd.getSquare(x, y);
        brd.getSquare(x, y).setBox(this);
        l++;
    }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • This worked fine, except for one thing. When k is 2, the i becomes 0 again, so it grabs the same box as box 0 once more. This should also work for uneven boxes, ie. 2x3 as well, shouldn't it? – Bjørn Haugerud May 02 '13 at 18:27
  • @BjørnHaugerud It should work for uneven boxes, just change `size` into 2 variables, one for `x` and one for `y` with the appropriate dimensions. Not sure about the `i` becoming 0 issue, can't see a problem with my code. – Bernhard Barker May 02 '13 at 19:33
0

If you want to use a single number to index a 2D array, use the mod / divide functions.

row = index / row_size;
col = index % col_size;

Your index should be in the range 0 to (row_size*col_size -1)

munch1324
  • 1,148
  • 5
  • 10
0

So it sounds like you just want to get the box row and box column.

int boxsize = 3;
int h = 9; //height
inh w = 9; //width
for (int r =0;r<h;r++){
    for (int c=0;c<w;c++){
        int br = r/boxsize;
        int bc = c/boxsize;
        int index = br*h + c;
        narray[index]=brd.getSquare(br,bc);
        System.out.println("box row =" + br +"   box column =" + bc);
    }
}
greedybuddha
  • 7,488
  • 3
  • 36
  • 50