亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在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 關注
  • 464 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號