将2D数组划分为多个框 [英] Dividing a 2D array into boxes

查看:72
本文介绍了将2D数组划分为多个框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像数独一样,我难以将2D数组划分为多个框.我的板子对象中有一个正方形数组,我想将它们分成2x3或3x3盒子,盒子对象具有一维数组以跟踪正方形.

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是盒子编号,在9x9数独中,盒子的编号为0到8.

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?

推荐答案

所以,我假设框的编号是这样的:

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

012
345
678

(每个盒子由3x3的单元格组成)

(and the boxes consist of 3x3 cells each)

如果ij是x和y坐标,则需要将以上内容转换为坐标.像这样:

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

所以x = k%3y = k/3.

在实际的网格中,x和y必须从0、3和6开始,而不是0、1和2,因此只需乘以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.

所以应该这样:(根据哪个坐标是x和哪个y进行更改)

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

这篇关于将2D数组划分为多个框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆