嗨,我想創建一個程序,輸出所有以字母可能串(C,A,T,d,O,G)Java數組隨機字母組合(ArrayList不是)
像
c
c,a
c,a,t
c,a,d
...
.....
......
etc
我想知道是否有沒有使用arraylist做到這一點?我通過其他問題看起來和所有它們是ArrayList的不只是普通陣列
我可以這樣做:
字符串myArray的[] = {C,A,T,d,鄰,克}
然後從那裏出發?我不知道下一步該怎麼做,雖然
感謝
嗨,我想創建一個程序,輸出所有以字母可能串(C,A,T,d,O,G)Java數組隨機字母組合(ArrayList不是)
像
c
c,a
c,a,t
c,a,d
...
.....
......
etc
我想知道是否有沒有使用arraylist做到這一點?我通過其他問題看起來和所有它們是ArrayList的不只是普通陣列
我可以這樣做:
字符串myArray的[] = {C,A,T,d,鄰,克}
然後從那裏出發?我不知道下一步該怎麼做,雖然
感謝
它不建議給予完整的解決方案,而是取決於你,如果你想了解這背後的理論。
public void comb(String A[], String str, int pos, int length)
{
if (length == 0) {
System.out.println(str);
} else {
for (int i = pos; i < A.length; i++)
comb(A, str + A[i], i + 1, length - 1);
}
}
public static void main(String[] args) {
String myArray[] = {"c", "a", "t", "d","o","g"};
C c = new C();
for (int i = 0; i <= myArray.length; i++)
c.comb(myArray, "", 0, i);
}
在這another answer我簡要解釋一下類似的發電機是如何工作的。
我還建議您瞭解Backtracking和組合算法。
編輯:如果你想要的是組合存儲陣列我能想到的唯一的辦法就是有足夠的空間來初始化存儲所有這樣的組合中,例如:
private String[] combinations;
private int count;
public void comb(String A[], String str, int pos, int length)
{
if (length == 0) {
combinations[count] = str;
count++;
} else {
for (int i = pos; i < A.length; i++)
comb(A, str + A[i], i + 1, length - 1);
}
}
public void solve()
{
// 64 = C(6, 6) + C(6, 5) + C(6, 4) + C(6, 3) + C(6, 2) + C(6, 1) + C(6, 0)
// where C(n, k) = binomial coefficient function.
combinations = new String[64];
count = 0;
String myArray[] = {"c", "a", "t", "d","o","g"};
for (int i = 0; i <= myArray.length; i++)
comb(myArray, "", 0, i);
for (int i = 0; i < combinations.length; i++)
System.out.println(combinations[i]);
}
public static void main(String[] args) {
C c = new C();
c.solve();
}
我明白了。我做了不同的方式。不管怎麼說,還是要謝謝你 :) –
這是你的家庭作業? – rendon
數組是不可變的,使用arrayList似乎有一些明顯的好處。 – SeekingAlpha
@SeekingAlpha:你可能想再看一遍。 – user2357112