【问题标题】:Java Array random letter combination (not ArrayList)Java Array 随机字母组合(不是 ArrayList)
【发布时间】:2014-01-29 04:35:48
【问题描述】:

大家好,我想创建一个程序,输出所有可能的带有字母(c、a、t、d、o、g)的字符串

喜欢

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

我想知道是否有办法在不使用数组列表的情况下做到这一点?我查看了其他问题,他们所拥有的只是 arrayList 而不仅仅是普通数组

我可以这样做吗:

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

然后从那里去?我不知道下一步该怎么做

谢谢

【问题讨论】:

  • 这是你的作业吗?
  • 数组是不可变的,使用arrayList似乎有一些明显的好处。
  • @SeekingAlpha:你可能想再看一遍。
  • 你想只返回字符/字符串还是其他数组?
  • @rendon 不,这只是我自己的练习题之一

标签: arrays computer-science


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多