簡體   English   中英

查找數組索引

[英]Find array indices

我確信有一個CS術語用於我想要完成的任務,但我不確定它是什么。 我有三個數組,我們稱之為abc 我正在遍歷每個可能的數組組合,這將是a*b*c迭代。

我傳遞的函數是當前迭代的int (這樣iteration0變為a*b*c-1 )和abc的長度。 我希望該函數能夠打印出索引的每個唯一排列,僅從迭代計數和abc的長度計算得出。

這就是我現在擁有的:

class Test {
    public static void printIndices(int i, int a, int b, int c) {
        System.out.println(i%a + ", " + (i+1)%b + ", " + (i+2)%c);
    }

    public static void main(String[] args) {
        int a[] = new int[2];
        int b[] = new int[2];
        int c[] = new int[3];

        int iterations = a.length * b.length * c.length;

        for (int i=0; i < iterations; i++){
            printIndices(i, a.length, b.length, c.length);
        }
    }
}

它生成此輸出:

0, 1, 2
1, 0, 0
0, 1, 1
1, 0, 2
0, 1, 0
1, 0, 1
0, 1, 2
1, 0, 0
0, 1, 1
1, 0, 2
0, 1, 0
1, 0, 1

如你所見,有重復。 我希望輸出為:

0, 0, 0
1, 0, 0
0, 1, 0
1, 1, 0
0, 0, 1
1, 0, 1
0, 1, 1
1, 1, 1
0, 0, 2
1, 0, 2
0, 1, 2
1, 1, 2

(順序並不重要,只要每個排列都沒有重復)。

顯然我的輸出線是錯誤的:

System.out.println(i%a + ", " + (i+1)%b + ", " + (i+2)%c);

獲取我正在尋找的輸出的正確操作是什么?

我知道這段代碼看起來有點傻,而且它根本不是我實際做的,但它很好地證明了這一點。

正如評論中所提到的,您正在尋找笛卡爾積

使用模塊化算法的方法幾乎可行。 您只需要進行一些修改即可獲得正確的結果:

System.out.println(i%a + ", " + (i/a)%b + ", " + (i/a/b)%c);

看到它在線工作: ideone

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM