2013-04-11 74 views
4

如何迭代n維數組(n未知)?在n維陣列上迭代

我已經找到了C++的結果,其中一個可以簡單地貫穿數組的內存區域,但我不知道我是否可以在JAVA中做到這一點。

+0

什麼是「可變維數組」? – Andremoniy 2013-04-11 11:58:09

+0

我不認爲我理解你的問題,但在這裏:我在N^n中有一個向量,其中每個條目從0到xn。但是,我不知道n是多少,我需要一種方法來遍歷所有這些可能的向量。 – user2270119 2013-04-11 14:52:04

+0

Hi @ user2270119習慣於選擇適合您的問題的答案。 – 2013-09-13 12:38:31

回答

1

在C/C++多維陣列(int[][])在所述存儲器中的平坦的方式被表示和索引操作符被翻譯成指針運算。這就是爲什麼在這些語言中做到這一點很容易和直接。

但是,這不是Java中的情況,多維數組是數組的數組。在嚴格檢查類型時,數組數組中的索引產生一個數組類型,而不是內部數組包含的類型。

所以壽回答這個問題:不,你不能這樣做,在Java的簡單,如在C/C++

要做到這一點看其他答案.. :-)

2

我在其他地方發現了這個。這是一個相當不錯的遞歸解決問題的方法:

interface Callback { 
     void visit(int[] p); // n-dimensional point 
    } 

void visit(int[] bounds, int currentDimension, int[] p, Callback c) { 
    for (int i = 0; i < bounds[currentDimension]; i++) { 
     p[currentDimension] = i; 
     if (currentDimension == p.length - 1) c.visit(p); 
     else visit(bounds, currentDimension + 1, p, c); 
    } 
} 

visit(new int[] {10, 10, 10}, 0, new int[3], new Callback() { 
    public void visit(int[] p) { 
     System.out.println(Arrays.toString(p)); 
    } 
}); 
2

這可能適合你需求:

public interface ElementProcessor {  
    void process(Object e);  
} 

public static void iterate(Object o, ElementProcessor p) { 
    int n = Array.getLength(o); 
    for (int i = 0; i < n; i++) { 
     Object e = Array.get(o, i); 
     if (e != null && e.getClass().isArray()) { 
      iterate(e, p); 
     } else { 
      p.process(e); 
     } 
    } 
} 

然後,打電話時:

// the process method will be called on each element of the n-dimensional 
ElementProcessor p = new ElementProcessor() { 
    @Override 
    public void process(Object e) { 
     // simply log for example 
     System.out.println(e); 
    } 
}; 

int[] a1 = new int[] { 1, 2 }; 
int[][] a2 = new int[][] { new int[] { 3, 4 }, new int[] { 5, 6 } }; 

iterate(a1, p); 
iterate(a2, p); 

This print:

1 
2 
3 
4 
5 
6 
+0

這看起來不錯,似乎是一個很好的解決方案,但我對效率感興趣,一般來說遞歸不是要走的路。 真的沒有其他辦法嗎? (我無能爲力) – user2270119 2013-04-11 14:48:01

+0

@ user2270119在嘗試了幾件事之後,我一直無法找到任何不使用遞歸的其他解決方案......恐怕你別無選擇。請讓我知道,如果你發現另一個雖然:) – sp00m 2013-04-11 15:16:17