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

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

在 Java 中交換數組中的三元組

在 Java 中交換數組中的三元組

泛舟湖上清波郎朗 2023-03-31 09:33:06
我正在嘗試用 Java 實現以下過程。我有一個數組,其中每個元素都是一個三元組。例如:int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };我想交換數組中的每個三元組(與右側的其他三元組)以獲得以下每個矩陣:b = { {1,2,1},{0,1,0},{1,0,0},{0,2,0} };c = { {1,0,0},{1,2,1},{0,1,0},{0,2,0} };d = { {0,2,0},{1,2,1},{1,0,0},{0,1,0} };e = { {0,1,0},{{1,0,0},{1,2,1},{0,2,0} };f = { {0,1,0},{0,2,0},{1,0,0},{1,2,1} };g = { {0,1,0},{1,2,1},{0,2,0},{1,0,0} };一般來說,對于 k 個三元組的矩陣,有 [(k*(k-1))/2] 種可能的交換。我該如何解決這個問題?
查看完整描述

1 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

雙嵌套循環應該在這里工作。請注意,您要求的輸出實際上是一個 3D 數組(2D 數組的數組):


public int[][] copy2DArray (int[][] input) {

    int[][] output = new int[input.length][];

    for (int r=0; r < input.length; ++r) {

        output[r] = new int[input[r].length];

        for (int c=0; c < input[0].length; ++c) {

            output[r][c] = input[r][c];

        }

    }


    return output;

}


public static void main(String[] args) {

    int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };

    int numSwaps = a.length*(a.length-1) / 2;

    int[][][] result = new int[numSwaps][][];


    int counter = 0;

    for (int i=0; i < a.length-1; ++i) {

        for (int j=i+1; j < a.length; ++j) {

            result[counter] = copy2DArray(a);

            int[] temp = result[counter][j];

            result[counter][j] = result[counter][i];

            result[counter][i] = temp;

            ++counter;

        }

    }


    System.out.println(Arrays.deepToString(result));

}

這打?。?/p>


[

    [[1, 2, 1], [0, 1, 0], [1, 0, 0], [0, 2, 0]],

    [[1, 0, 0], [1, 2, 1], [0, 1, 0], [0, 2, 0]],

    [[0, 2, 0], [1, 2, 1], [1, 0, 0], [0, 1, 0]],

    [[0, 1, 0], [1, 0, 0], [1, 2, 1], [0, 2, 0]],

    [[0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 2, 1]],

    [[0, 1, 0], [1, 2, 1], [0, 2, 0], [1, 0, 0]]

]

對于某些注釋,我過去使用的策略是使用兩級循環遍歷所有位置交換位置for。對于每個可能的交換,我們首先克隆您的輸入二維a數組。然后,我們在選擇的任何位置交換各個一維數組。最后,我們將該交換數組添加到 3D 結果數組。我們也可以使用類似列表的東西來存儲交換的二維數組。


查看完整回答
反對 回復 2023-03-31
  • 1 回答
  • 0 關注
  • 106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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