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?

Answers


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

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)


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

Need Your Help

Apply “permutations” of a function over a list

list haskell

Creating the permutations of a list or set is simple enough. I need to apply a function to each element of all subsets of all elements in a list, in the order in which they occur. For instance:

Editing bash autocomplete to ignore automatically generated files

bash command-line autocomplete

Essentially, if I have a number of files with the same name, except for their extensions, is there a way to make the auto-complete ignore/prioritise specific extensions when I am opening them in the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.