Search code examples
arraysalgorithmpermutationheaps-algorithm

Permutation algorithm for n characters in x positions


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

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

...

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. 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.

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.


Solution

  • 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;
      }
    }
    

    Test:

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

    Output:

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