所以我有這個數組只包含唯一的數字,其中索引0處的數字最低,數組最末尾的數字最高。遞增一個唯一的數字序列
E.g. [1,2,3,4]
現在我每增加1次後面的數字。但是當任何數字達到一定的高度時,它應該增加左邊的數字。
E.g.比方說,最大高度是8。
[1,2,3,8] - > [1,2,4,5]
現在直到我在這裏的代碼工作。但是當最後2個數字達到最大高度時,它不會再增加第三個數字。
E.G. [1,2,7,8] - > [1,3,4,5]
我寫的代碼是遞歸的。
//Position is the index in the array of which element should be incremented by 1
public int[] increaseArray(int[] index, int maxIndex, int position) {
int tmp = index[position];
if (tmp < maxIndex) {
index[position] = tmp + 1;
return index;
} else {
if (positie != 0 && index[position - 1] + 2 <= maxIndex) {
index[position] = index[position - 1] + 2;
return increaseArray(index, maxIndex, position - 1);
} else {
return null;
}
}
}
EDIT 1:
所得陣列只包含唯一的號碼,所以是INT [2]刷爆至7在這裏。
另外我編輯了代碼。我感覺,我幾乎沒有雖然最後人數仍在竊聽......
public int[] increaseIndex(int[] index, int maxIndex, int position) {
int tmp = index[position];
if (tmp < maxIndex + position - 2) {
index[position] = tmp + 1;
return index;
} else {
if (position > 0) {
//The following line of code is the problem...
index[position] = index[position - 1] + 2;
return increaseIndex(index, maxIndex, position - 1);
} else {
return null;
}
}
}
編輯2:
真的接近現在。我像說的那樣修正了maxIndex。現在有一個小錯誤,應該增加2個以上的數字。
代碼
public int[] increaseIndex(int[] index, int maxIndex, int position) {
int size = index.length;
int tmp = index[position];
if (tmp < maxIndex - (size-position-1)) {
index[position] = tmp + 1;
return index;
} else {
if (position > 0) {
//The following line is the problem i think...
index[position] = index[position - 1] + 2;
return increaseIndex(index, maxIndex, position - 1);
} else {
return null;
}
}
}
當我使用以下執行代碼這會給我下面的輸出例如與maxIndex 8
int[] index = new int[] {1,2,3,4};
index = increaseIndex(index, row.length - 1, k - 2);
while (index != null) {
printArray(index);
index = increaseIndex(index, row.length - 1, k - 2);
}
[1, 2, 3, 4]
[1, 2, 3, 5]
[1, 2, 3, 6]
[1, 2, 3, 7]
[1, 2, 3, 8]
[1, 2, 4, 5]
[1, 2, 4, 6]
[1, 2, 4, 7]
[1, 2, 4, 8]
[1, 2, 5, 6]
[1, 2, 5, 7]
[1, 2, 5, 8]
[1, 2, 6, 7]
[1, 2, 6, 8]
[1, 2, 7, 8]
[1, 3, 4, 9] //wrong
[1, 3, 5, 6]
[1, 3, 5, 7]
[1, 3, 5, 8]
[1, 3, 6, 7]
[1, 3, 6, 8]
[1, 3, 7, 8]
[1, 4, 5, 9] //wrong
[1, 4, 6, 7]
[1, 4, 6, 8]
[1, 4, 7, 8]
[1, 5, 6, 9] //wrong
[1, 5, 7, 8]
[1, 6, 7, 9] //wrong
[2, 3, 8, 9] //wrong
[2, 4, 5, 10]//wrong
[2, 4, 6, 7]
[2, 4, 6, 8]
[2, 4, 7, 8]
[2, 5, 6, 9] //wrong
[2, 5, 7, 8]
[2, 6, 7, 9] //wrong
[3, 4, 8, 9] //wrong
[3, 5, 6, 10]//wrong
[3, 5, 7, 8]
[3, 6, 7, 9] //wrong
[4, 5, 8, 9] //wrong
[4, 6, 7, 10]//wrong
[5, 6, 8, 9] //wrong
沒有結果數組需要獨特的號碼以及?還是他們都應該最大程度的發揮在8點? (在這個例子中)。 含義... if int [3] == 8,maxed out,int [2] == 7 maxed,還是應該== 8? – 2011-04-30 15:06:55
您的MaxIndex應該在每個位置都有所不同。 – 2011-04-30 15:07:20
「c#」和「算法」標籤添加了'unique'和'increment'標籤。 – 2011-04-30 15:24:57