【问题标题】:Code for Variations with repetition (combinatorics)?重复变化的代码(组合)?
【发布时间】:2010-03-02 19:30:25
【问题描述】:

有没有人有 Java 代码来生成所有重复的变化?

有很多可用的排列和组合示例,而变体必须是最简单的一种... 浪费时间重新发明轮子感觉很愚蠢(必须为此编写大量代码)。

有重复的变化的例子可能是这样的:

(tupletSize=3, input= A, B)
AAA, AAB, ABA, BAA, ABB, BAB, BBA, BBB

谢谢!

【问题讨论】:

    标签: java algorithm recursion combinatorics


    【解决方案1】:

    这是按原样工作的,它对你来说是最容易学习的。

    public class Main {
        public static void main(String args[]) {
            brute("AB", 3, new StringBuffer());
        }
        static void brute(String input, int depth, StringBuffer output) {
            if (depth == 0) {
                System.out.println(output);
            } else {
                for (int i = 0; i < input.length(); i++) {
                    output.append(input.charAt(i));
                    brute(input, depth - 1, output);
                    output.deleteCharAt(output.length() - 1);
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:
      public class Main {
      
          public static void main(String[] args) throws IOException {
              LinkedList<char[]> items = new LinkedList<char[]>();
              char[] item = new char[3];
              char[] input = {'A', 'B'};
              rep(items, input, item, 0);
      
      
              for (char[] rep : items) {
                  System.out.println(rep);
              }
          }
      
          private static void rep(LinkedList<char[]> reps, char[] input, char[] item, int count){
              if (count < item.length){
                  for (int i = 0; i < input.length; i++) {
                      item[count] = input[i];
                      rep(reps, input, item, count+1);
                  }
              }else{
                  reps.add(item.clone());
              }
          }
      
      }
      

      产生以下输出: AAA AAB ABA ABB BAA BAB 工商管理学士 BBB

      注意大 tupleSize 的堆栈溢出。 递归算法(比如这个)通常比迭代版本慢,但它们对编码非常方便。

      【讨论】:

      • 非常感谢!我在编译时遇到了一些错误,但代码肯定会有所帮助!
      • 只要输入有两个或更多元素,您就会在堆栈溢出之前很久就耗尽内存。
      • 是的,你是对的——我猜“天哪——小心递归”比想象的要快;-)。所以在发布代码中我想我们不会囤积 char[]s :-)
      【解决方案3】:

      How to write a brute-force password cracker

      虽然这不是 Java 实现,但进行排列的部分应该很容易在 Java 中移植。

      我在没有 Python 知识的情况下将它移植到 C 中,它的工作就像一个魅力。

      【讨论】:

      • 它就像一个魅力?你真的有破解密码吗? ;)
      • 是的,但仅限于家庭作业(3-4 个字符长):-)
      【解决方案4】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        • 1970-01-01
        相关资源
        最近更新 更多