需要帮助找出一种不同的写count((的方法,它将添加到我的代码中:
public class Grid
{
private int [][] array;
private int max;
public Grid(int max)
{
array = new int[10][10];
this.max = max;
setRandom();
}
public void setRandom()
{
int i = 0;
while(i < max)
{
int r = (int)(Math.random() * 9) + 0;
int c = (int)(Math.random() * 9) + 0;
if(array[r][c] != -1)
{
array[r][c] = -1;
i++;
}
}
}
public void print()
{
for(int r = 0; r < array.length; r++)
{
for(int c = 0; c < array[r].length; c++)
{
System.out.print(array[r][c] + " ");
}
System.out.println();
}
}
public int count(int row, int col)
{
// method here
}
public static void main(String[] args)
{
Grid a = new Grid(20);
a.count(5, 5);
a.print();
}
}
我希望count()
返回在输入位置周围的2d数组中找到的-1的数量,并且它也不能检查位置";在边界之外";(更具体地说,对于给定的行/列,不相邻的位置(。本质上,从某种意义上说,它就像扫雷器:假设我通过count(5, 5)
(5
分别是行和列(,它将检查(5, 5)
周围的所有相邻位置。
在这种情况下,高亮显示的蓝色是要检查的位置,黄色是相邻位置。白色区域超出范围,不会进行检查。位置(5, 5)
的值为3,因为该位置周围有3-1。此处可见:https://i.stack.imgur.com/8DXVb.jpg
我想出了这个代码:
public int count(int row, int col)
{
int value = 0;
for(int r = -1; r < 2; r++)
{
for(int c = -1; c < 2; c++)
{
if(c == 0 & r == 0)
continue;
if(array[row + r][col + c] == -1)
{
value++;
}
}
}
return value;
}
但当我在main()
中通过a.count(4, 7)
时,网格没有发生任何变化,并且保持不变。我还想在不使用continue
的情况下找到一种不同的方法这是输出:
0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 0 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
我希望我的预期输出看起来像这样(如果我传入a.count(4, 7)
-4
是行,7
是列(
0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 **4** 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
(4是我经过的位置的值,因为它周围有4-1s,(3, 7)
的值为4(
您应该检查尝试访问的行和列的索引是否有效只需添加一个检查即可防止ArrayIndexOutOfBoundsException。
public int count(int row, int col) {
int value = 0;
for(int r = -1; r < 2; r++) {
for(int c = -1; c < 2; c++) {
if(c == 0 & r == 0)
continue;
int newR = row + r;
int newC = col + c;
if(newR < 0 || newR >= array.length || newC < 0 || newC >= array[0].length)
continue;
if(array[newR][newC] == -1)
value++;
}
}
return value;
}
这是我可以想出的办法来避免继续
public int count(int row, int col) {
int value = 0;
value += isValidIndex(row - 1, col - 1)? array[row - 1][col - 1]: 0;
value += isValidIndex(row - 1, col)? array[row - 1][col]: 0;
value += isValidIndex(row - 1, col + 1)? array[row - 1][col + 1]: 0;
value += isValidIndex(row, col - 1)? array[row][col - 1]: 0;
value += isValidIndex(row, col + 1)? array[row][col + 1]: 0;
value += isValidIndex(row + 1, col - 1)? array[row + 1][col - 1]: 0;
value += isValidIndex(row + 1, col)? array[row + 1][col]: 0;
value += isValidIndex(row + 1, col + 1)? array[row + 1][col + 1]: 0;
return -value;
}
public boolean isValidIndex(int row, int col) {
return !(row < 0 || col < 0 || row >= array.length || col >= array[0].length);
}