Java数组随机字母组合(不是ArrayList)

时间:2014-01-29 04:35:49

标签: arrays computer-science

嘿伙计们我想创建一个程序,用字母输出所有可能的字符串(c,a,t,d,o,g)

c
c,a
c,a,t
c,a,d
...
.....
......
etc

我想知道如果不使用arraylist就可以做到这一点?我查看了其他问题,他们只有arrayList而不仅仅是普通的数组

我可以做点什么:

  

String myArray [] = {c,a,t,d,o,g}

然后从那里开始?我不知道下一步该做什么

谢谢

1 个答案:

答案 0 :(得分:0)

不建议提供完整的解决方案,但如果您想了解其背后的理论,则由您自己决定。

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();
}