查找 n 个字母表的所有排列的算法

发布于 2024-09-13 07:41:21 字数 1108 浏览 1 评论 0原文

我编写了以下算法来查找 n 个唯一字母表的所有可能排列。

Set<String> results = new HashSet<String>();
    int size = 1;
            //find the total permutations possible
    for(int i=0;i<array.length;i++){
        size*=(i+1);            
    }
    // i is the number of items remaining to be shuffled.
    while(results.size()<size){
        for (int i = array.length; i > 1; i--) {
            // Pick a random element to swap with the i-th element.
            int j = rng.nextInt(i);  // 0 <= j <= i-1 (0-based array)
            // Swap array elements.
            char tmp = array[j];
            array[j] = array[i-1];
            array[i-1] = tmp;
        }
        StringBuffer str = new StringBuffer();          
        for(int i=0;i<array.length;i++)
            str.append(array[i]);
        results.add(str.toString());
    }
    System.out.println(results);

1) 有什么办法可以改进这个算法吗?
2)该算法的时间复杂度是多少?

PS:我向那些对我的上一篇文章做出反应的人表示歉意。在寻求帮助之前我会自己尝试。

I wrote the following algorithm for finding all possible permutations of n unique alphabets.

Set<String> results = new HashSet<String>();
    int size = 1;
            //find the total permutations possible
    for(int i=0;i<array.length;i++){
        size*=(i+1);            
    }
    // i is the number of items remaining to be shuffled.
    while(results.size()<size){
        for (int i = array.length; i > 1; i--) {
            // Pick a random element to swap with the i-th element.
            int j = rng.nextInt(i);  // 0 <= j <= i-1 (0-based array)
            // Swap array elements.
            char tmp = array[j];
            array[j] = array[i-1];
            array[i-1] = tmp;
        }
        StringBuffer str = new StringBuffer();          
        for(int i=0;i<array.length;i++)
            str.append(array[i]);
        results.add(str.toString());
    }
    System.out.println(results);

1) Is there anything to be done to improve this algorithm?
2) What would be the time complexity of this algorithm?

PS: I apologize to the people who who reacted to my previous post. I'll try on my own before asking for help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迷途知返 2024-09-20 07:41:21

通过利用随机洗牌,您将进行大量次迭代,但最终不会实际将新项目放入集合中 - 您应该寻找一种方法,确保在每次迭代中新项目被放入集合中(我所说的“新”只是指以前从未见过的排列)。

我不想猜测上面提供的算法的时间复杂度 - 它会很大。

By utilizing a random shuffling, you're going to have a massive number of iterations that end up not actually putting a new item into the set - you should look for an approach that ensures that on each iteration a new item is placed into the set (by 'new' I simply mean a permutation that hasn't been seen previously).

I wouldn't like to guess at the time complexity of the algorithm supplied above - it's going to be big.

秋叶绚丽 2024-09-20 07:41:21

1)有什么办法可以改进这个算法吗?

是的。只是为了给您一些如何确定性地生成排列的提示:

  • 想象一下 N 元素上所有排列的字典顺序。想象一下,在给定前一个排列的情况下,如何按该顺序生成下一个排列

  • 想象一下,考虑到具有公共前缀的一组排列(例如,435 126、435 162 等)是什么以及如何在算法中使用它。

1) Is there anything to be done to improve this algorithm?

Yes. Just to give you some hints how you could generate the permutations deterministically:

  • imagine the lexicographic order of all permutations on N elements. Imagine, how could you generate the next permutation in that order given the previous

  • think about what would the set of permutations with a common prefix (eg. 435 126, 435 162 etc.) be and how could you use it in an algorithm.

白龙吟 2024-09-20 07:41:21

生成排列的最佳方法是迭代地执行此操作:找到一种方案从一个排列转到下一个排列,直到您看到所有排列为止。 Knuth 在 TAOCP 的组合分册之一中公开了这样的方案,并且无需深入研究他的类似汇编的伪代码,您可能需要检查 这些算法的这些漂亮的 C 实现。您正在寻找的算法是生成排列的算法。

与(我所理解的)你的算法相反,这种算法的优点是它是确定性的,并且每次都会生成不同的排列。

The best way to generate permutations is to do so iteratively: finding a scheme to go from one permutation to the next until you've seen them all. Knuth has exposed such a scheme in one of the combinatorial fascicles of TAOCP, and without going into his assembly-like pseudo code, you might want to check these nifty C implementation of those algorithms. The algorithm you are looking for is the one that generates permutations.

The advantage of such an algorithm by opposition to (what I understand of) yours, is that it is deterministic and will generate a different permutation every single time.

甜嗑 2024-09-20 07:41:21

感谢您的投入。我想我有更好的算法。请提供意见

private static List<String> allPerms(char[] array) {    
  List<String> perms = new ArrayList<String>();
  if(array.length<=1 )
      perms.add(String.valueOf(array[0]));
  else{
      char[] newarray = Arrays.copyOf(array, array.length-1);
      char lastChar = array[array.length-1];
      List<String> soFar = allPerms(newarray);
      for(int i=0; i<soFar.size(); i++) {       
          String curr = soFar.get(i);
          for(int j=0;j<array.length;j++){
              StringBuffer buff = new StringBuffer(curr);
              perms.add(buff.insert(j, lastChar).toString());                 
          }
      }       
    }
return perms; }

Thank you for your inputs. I think I have got a better algorithm. Please provide comments

private static List<String> allPerms(char[] array) {    
  List<String> perms = new ArrayList<String>();
  if(array.length<=1 )
      perms.add(String.valueOf(array[0]));
  else{
      char[] newarray = Arrays.copyOf(array, array.length-1);
      char lastChar = array[array.length-1];
      List<String> soFar = allPerms(newarray);
      for(int i=0; i<soFar.size(); i++) {       
          String curr = soFar.get(i);
          for(int j=0;j<array.length;j++){
              StringBuffer buff = new StringBuffer(curr);
              perms.add(buff.insert(j, lastChar).toString());                 
          }
      }       
    }
return perms; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文