所以,我有一个看起来像的字符表
[[.,*,.,.,*]
[*,.,.,.,.]
[.,.,.,*,*]]
我想把每一个“。” 成一个数字,显示相邻字段中有多少 *。基本上是一个简单的扫雷艇。有没有一种优雅的方法来检查每个元素的每个相邻字段?因为我想到的是很多嵌套的 for 循环和 if 语句,但我确定有更好的方法来做到这一点?
编辑:预期的结果应该是这样的:
[[3,*,2,.]
[*,*,2,.]]
我能想到的最优雅的方式是这样的:
public static void main(String[] args) {
char[] a = {'.', '.', '*', '.', '*'};
char[] b = {'.', '*', '*', '.', '*'};
char[] c = {'.', '.', '*', '.', '*'};
char[] d = {'.', '*', '*', '.', '*'};
char[] e = {'*', '.', '*', '.', '*'};
char[][] ae = {a, b, c, d, e};
char[][] numberArray = new char[5][5];
for (int i = 0; i < ae.length; i++) {
for (int j = 0; j < ae[i].length; j++) {
numberArray[i][j] = checkAdjacentField(i, j, ae);
}
}
StringBuilder matrix = new StringBuilder();
for (char[] aNumberArray : numberArray) {
StringBuilder bld = new StringBuilder("{");
for (char character : aNumberArray) {
bld.append(character).append(",");
}
bld.deleteCharAt(bld.length() - 1);
bld.append("}");
matrix.append(bld.toString()).append("\n");
}
System.out.println(matrix.toString());
}
private static char checkAdjacentField(int i, int j, char[][] ae) {
int count = 0;
if (j <= ae[i].length - 2) { // to the right
count += ae[i][j + 1] == '*' ? 1 : 0;
}
if (j <= ae[i].length - 2 && i <= ae.length -2) { // move to top right
count += ae[i + 1][j + 1] == '*' ? 1 : 0;
}
if (j <= ae[i].length - 2 && i > 0) { // move to bottom right
count += ae[i - 1][j + 1] == '*' ? 1 : 0;
}
if (j > 0) { // to the left
count += ae[i][j - 1] == '*' ? 1 : 0;
}
if (j > 0 && i <= ae.length -2) { // to top left
count += ae[i + 1][j - 1] == '*' ? 1 : 0;
}
if (j > 0 && i > 0) { // to bottom left
count += ae[i - 1][j - 1] == '*' ? 1 : 0;
}
if (i <= ae.length -2) { // move to top
count += ae[i +1][j] == '*' ? 1 : 0;
}
if (i > 0) { // move top bottom
count += ae[i - 1][j] == '*' ? 1 : 0;
}
System.out.printf("field %s, %s has %s Adjacent fields with a * \n", i, j , count);
String stringValue = String.valueOf(count);
return stringValue.charAt(0);
}
如果你对这个例子有疑问,我想听听。
下一次,尝试提供一个示例,说明您之前已经准备好尝试的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句