Bjørn Haugerud
Bjørn Haugerud

Reputation: 3

Dividing a 2D array into boxes

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?

Upvotes: 0

Views: 3815

Answers (3)

Bernhard Barker
Bernhard Barker

Reputation: 55619

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++;
    }
}

Upvotes: 1

greedybuddha
greedybuddha

Reputation: 7507

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);
    }
}

Upvotes: 0

munch1324
munch1324

Reputation: 1148

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)

Upvotes: 0

Related Questions