x位置的n个字符的置换算法 [英] Permutation algorithm for n characters in x positions

查看:62
本文介绍了x位置的n个字符的置换算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如将{& ;, *,%}放置在8个位置的置换算法:

e.g. A permutation algorithm for {&, *, %} to be placed in 8 positions:

  1. &&&&&&&&
  2. &&&&&& **
  3. &&&&&& %%
  4. &&&&&& *%
  5. &&&&& **

...

我在Internet上看到的堆排列算法仅适用于字符数等于位置数的人,以及可以使用不相等的字符数和位置数的人,仅适用于整数,不适用于字符.我还必须说,到目前为止,我还没有达到任何有效的算法,因为我对算法一无所知.我尝试了一下,在看到堆的算法之后,我无法将其命名为算法!如果有帮助的话:

Heap's permutation algorithm I saw on the Internet works just for those who the number of characters are equal to the number of positions, And those who can work with unequal number of characters and number of positions, Only work with integers, Not characters. I also have to say I haven't reached any working algorithm up to now, As I don't know anything about algorithms. I had one try, Which I couldn't name it algorithm after I saw heap's algorithm! In case it helps:

  1. & 添加到输出数组.
  2. 在新索引上将添加到输出数组.
  3. 在新索引上向输出数组添加 * .
  4. 为每三个算法执行一个递归算法.
  1. Add & to the output array.
  2. Add % to the output array on a new index.
  3. Add * to the output array on a new index.
  4. Do a recursive algorithm for each three.

但是我显然不能处理数组索引.我也尝试过使用0到2之间的数字作为&,%,*;但是我没有得到一个很好的答案.

But I obviously can't handle array indexes. I have also tried using numbers from 0 to 2 for &, %, *; But I didn't reach a good answer.

推荐答案

您可以使用标准的里程表"方法( IDEOne):

You can use the standard "odometer" method (IDEOne):

static void permute(String str, int len)
{    
  char[] chars = str.toCharArray();

  int[] idx = new int[len];

  char[] perm = new char[len];    
  Arrays.fill(perm, chars[0]);

  while(true)
  {      
    System.out.println(new String(perm));

    int k=idx.length-1;
    for(; k>=0; k--)
    {
      idx[k] += 1;
      if(idx[k] < chars.length) 
      {
        perm[k] = chars[idx[k]];
        break;
      }
      idx[k] = 0;
      perm[k] = chars[idx[k]];
    }
    if(k < 0) break;
  }
}

测试:

public static void main(String[] args)
{
  permute("&*%", 8);
}

输出:

&&&&&&&&
&&&&&&&*
&&&&&&&%
&&&&&&*&
&&&&&&**
&&&&&&*%
&&&&&&%&
&&&&&&%*
&&&&&&%%
&&&&&*&&
<snip>
%%%%%%**
%%%%%%*%
%%%%%%%&
%%%%%%%*
%%%%%%%%

这篇关于x位置的n个字符的置换算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆