gpt4 book ai didi

java - 搜索A 'SubArray'

转载 作者:行者123 更新时间:2023-12-01 05:08:43 27 4
gpt4 key购买 nike

我正在尝试创建一个函数,该函数将从较大数组中检查 3x3 数组元素 block 中的特定元素。

9...84.6.  
..4..75.8
.3.......
3....1...
.7.5.6.4.
...4....2
.......5.
5.97..2..
.8.21...4

我想传入一个编号为 0-8 的框,并仅在选定的框内查找 x。拼图数组可能类似于上面的内容。

protected static boolean box(int box, int x){
//box is a 3x3 subset of puzzle
// 012
// 345 <--- boxes numbered as such
// 678
boolean present = false;
int coordR = 0, coordC = 0;

switch (box){
case 0:
coordR = 0;
coordC = 0;
case 1:
coordR = 0;
coordC = 3;
case 2:
coordR = 0;
coordC = 6;
case 3:
coordR = 3;
coordC = 0;
case 4:
coordR = 3;
coordC = 3;
case 5:
coordR = 3;
coordC = 6;
case 6:
coordR = 6;
coordC = 0;
case 7:
coordR = 6;
coordC = 3;
case 8:
coordR = 6;
coordC = 6;
}
System.out.print("Box " + box + " -\t");
for (int i = coordR; i < 3; i++){
for (int j = coordC; j < 3; j++){
if (puzzle[i][j] == x){
present = true;
}
System.out.print(puzzle[i][j]);
}
}
System.out.println("");
return present;
}

是否有更有效的方法来做到这一点/使这项工作发挥作用?

最佳答案

当然:

protected static boolean box(int box, int d) {
int boxY = box / 3;
int boxX = box - (boxY * 3);

int minX = boxX * 3;
int maxX = minX + 3;
int minY = boxY * 3;
int maxY = maxX + 3;

for (int y = minY; y < maxY; y++)
for (int x = minX; x < maxX; x++)
if (puzzle[x][y] == d)
return true;
return false;
}

供将来引用:您不应忘记 switch 语句中的break语句。

关于java - 搜索A 'SubArray',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344460/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com