[英]Adding Elements From Each Row of Jagged Array
我試圖通過每行僅使用1個元素來獲取n行,鋸齒狀2d字符串數組中元素的每個單獨組合。
一個示例數組(每行代表數組中的一行):
“ A”,“ B”,“ C”
“ D”,“ E”
“ F”,“ G”,“ H”,“ I”,“ J”
對於上述陣列,將有30種可能的組合。 歡迎使用遞歸解決方案,但由於內存使用原因,我希望使用一種迭代解決方案。
如果n
是一個變量,我想不出任何解決您問題的迭代解決方案。
遞歸解決方案:
ArrayList<String> permutations = new ArrayList<String>();
generatePermutations ("", 0);
/** Where the function generatePermutations is defined as: **/
void generatePermutations (String s, int index) {
if (index >= n) {
permutations.add(s);
return;
}
for (String a : myJaggedArray[index]) {
generatePermutations (s + a, index + 1)
}
}
這應該可以處理任何大小的鋸齒狀數組,但我僅測試了5種情況。
我們的基本策略是使用數組來跟蹤子數組中下一個元素的當前索引,一旦將序列放入permutationArray中,我們將增加最右邊的索引。 如果該索引等於最右邊的子數組的大小,則我們使最右邊的索引為0並增加第二個到最右邊的索引。 如果該索引等於該子數組的大小,則使該索引為0並增加前一個索引。 這個過程一直泡到第一個索引,直到我們沒有剩余的排列為止。
char list[][] = new char[][] { { 'a', 'b', 'c' }, { 'd', 'e' },
{ 'f', 'g', 'h', 'i', 'j' } };
int permutations = 1;
for (int i = 0; i < list.length; ++i)
permutations *= list[i].length;
char permutationArray[][] = new char[permutations][list.length];
// list of lengths of each subarray
int listlength[] = new int[list.length];
for (int i = 0; i < list.length; ++i)
listlength[i] = list[i].length;
// traverse list in a permutation, once this gets to the length then we
// increase indicies starting from the right side
int listindicies[] = new int[list.length];
for (int i = 0; i < permutations; ++i) {
for (int j = 0; j < list.length; ++j) {
permutationArray[i][j] = list[j][listindicies[j]];
if (j == (list.length - 1))
listindicies[j]++;
}
// reset indicies if they are equal to the length of the array
for (int k = list.length - 1; k >= 0; --k) {
if (listindicies[k] == (listlength[k])) {
listindicies[k] = 0;
if (k != 0)
listindicies[k - 1]++;
} else {
break;
}
}
}
for (int i = 0; i < permutationArray.length; ++i) {
for (int j = 0; j < permutationArray[i].length; ++j)
System.out.print(permutationArray[i][j] + " ");
System.out.println("");
}
這是一個使用模數的有趣的小方法:
public static void main(String args[]) {
iterate(new String[][]{{"a","b","c"},{"d","e"},{"f","g","h","i"}});
}
static void iterate(String[][] jagged) {
int count = 1;
int[] divisors = new int[jagged.length];
for (int j = 0; j < jagged.length; j++) {
divisors[j] = count;
count *= jagged[j].length;
}
for (int i = 0; i < count; i++) {
String[] combination = new String[jagged.length];
for (int j = 0; j < jagged.length; j++) {
int mod = jagged[j].length;
combination[j] = jagged[j][(i/divisors[j])%mod];
}
process(combination);
}
}
static void process(String[] combination) {
System.out.println(Arrays.toString(combination));
// Do whatever you want here. Process as you go to save memory,
// or add to a list to process later.
}
它的核心是combination[j] = jagged[j][(i/divisors[j])%mod];
divisors[j]
是較早長度的乘積,即使用較低索引數組可能的組合數。 mod
是當前數組的長度。
如果您希望最后一個元素的迭代速度更快,而第一個元素的迭代速度更慢,則在計算divisors
/ count
時,應顛倒順序,即,將j
從jagged.length
到0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.