[英]Dividing a 2D array into boxes
像Sudoku一樣,我難以將2D數組划分為多個框。 我的板對象中有一個正方形數組,我想將它們划分為2x3或3x3盒子。盒子對象具有一維數組,用於跟蹤正方形。
k是盒子編號,在9x9數獨中,盒子的編號為0到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++;
}
這使第一個框正確,但是此后消失。 我已經考慮了好幾個小時了,似乎無法解決這個問題。 有人為此有一個巧妙的把戲嗎?
因此,我假設框的編號是這樣的:
012
345
678
(每個盒子由3x3單元組成)
如果i
和j
是x和y坐標,則需要將以上內容轉換為坐標。 就像是:
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%3
和y = k/3
。
在實際的網格中,x和y必須從0、3和6開始,而不是0、1和2,因此只需乘以3。
因此,應該執行以下操作:(根據x坐標和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數組,請使用mod /除法函數。
row = index / row_size;
col = index % col_size;
您的索引應在0到(row_size * col_size -1)的范圍內
因此,聽起來您只想獲取框行和框列。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.