Ranking and unranking of permutations with duplicates

前端 未结 4 1293
说谎
说谎 2020-12-06 08:14

I\'m reading about permutations and I\'m interested in ranking/unranking methods.

From the abstract of a paper:

A ranking function for the per

4条回答
  •  爱一瞬间的悲伤
    2020-12-06 09:19

    Java, from https://github.com/timtiemens/permute/blob/master/src/main/java/permute/PermuteUtil.java (my public domain code, minus the error checking):

    public class PermuteUtil {
     public  List nthPermutation(List original, final BigInteger permutationNumber)  {
            final int size = original.size();
    
            // the return list:
            List ret = new ArrayList<>();
            // local mutable copy of the original list:
            List numbers = new ArrayList<>(original);
    
            // Our input permutationNumber is [1,N!], but array indexes are [0,N!-1], so subtract one:
            BigInteger permNum = permutationNumber.subtract(BigInteger.ONE);
    
            for (int i = 1; i <= size; i++) {
                BigInteger factorialNminusI = factorial(size - i);
    
                // casting to integer is ok here, because even though permNum _could_ be big,
                //   the factorialNminusI is _always_ big
                int j = permNum.divide(factorialNminusI).intValue();
    
                permNum = permNum.mod(factorialNminusI);
    
                // remove item at index j, and put it in the return list at the end
                T item = numbers.remove(j);
                ret.add(item);
            }
    
            return ret;
      }
    }
    

提交回复
热议问题