为了账号安全,请及时绑定邮箱和手机立即绑定

在java中检查数组数组中元素的相邻元素

在java中检查数组数组中元素的相邻元素

喵喔喔 2021-09-29 10:16:38
所以,我有一个看起来像的字符表[[.,*,.,.,*][*,.,.,.,.][.,.,.,*,*]]我想把每一个“。” 成一个数字,显示相邻字段中有多少 *。基本上是一个简单的扫雷艇。有没有一种优雅的方法来检查每个元素的每个相邻字段?因为我想到的是很多嵌套的 for 循环和 if 语句,但我确定有更好的方法来做到这一点?编辑:预期的结果应该是这样的:[[3,*,2,.] [*,*,2,.]]
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

我能想到的最优雅的方式是这样的:


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);

}

如果你对这个例子有疑问,我想听听。


下一次,尝试提供一个示例,说明您之前已经准备好尝试的内容。


查看完整回答
反对 回复 2021-09-29
  • 1 回答
  • 0 关注
  • 445 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信