Permutation Iterator in java

前端 未结 3 1730
天涯浪人
天涯浪人 2021-01-29 08:57

I want a class, that take in a possitive integer and produce a iterator that let me iterate through all possible of permutation of a list of possitive numbers under the positive

3条回答
  •  轮回少年
    2021-01-29 09:36

    This is a better solution, inspired by https://stackoverflow.com/a/10117424/312172

    To achieve, instead of getting a list of elements that are jumbled, we focus on the choices we make when deducting elements from the list. give the function a size, and a number that is smaller than factorial(size); it will return a sequence of choices we need to make to get the permutation.

    for example:
    getTheIndexOfSelection(100,5)-> for a list of 5 elements, we want the 100th permutation.

    it should output: [4, 0, 2, 0, 0]

    it means, remove the element at index 4, for the list that got removed, remove element at 0 ....

    if the list is[1,2,3,4,5]; this will be the procujure:
    [1,2,3,4,5] remove index 4 -> 5
    [1,2,3,4] remove index 0 -> 1
    [2,3,4] remove index 2 -> 4
    [2,3] rovmove index 0 -> 2
    [3] remove index 0 -> 3
    all the element we removed sequentially is the permutation.

    /**
         * Feed this function a number, it gives you a sequence of choices 
         * to make a permutation. 
         * 
    * if this return [0,0,0,0] * it means remove element at 0, and then remove again... until * reaches the end. * @return * * @param * len: the length of the list * n: the number that got match to a certain permutation. */ public static int[] getTheIndexOfSelection(int n, int size) { int[] lst = new int[size]; return getTheIndexOfSelection( n, size, 0, lst); } private static int[] getTheIndexOfSelection(int n, int size, int index, int[] lst) { if(size==1) { int[] result = {0}; // a list of one element, you can only choose the one that is in it // which is at index 0; return result; } if(n >= factorial(size))return null; // This is not possible to do. size-=1; int firstchoice = n/factorial(size); lst[index] = firstchoice; n = n-firstchoice*factorial(size); if(size>1)return getTheIndexOfSelection(n ,size, index+1, lst); return lst; }

    This is a better solution because:

    1. The speed really depends on the factorial function, assume factorial is super fast, this will be o(n).
    2. It matches numbers to permutation, making the expandable for things like map and iterator.
    3. It is not the full solution, the part that is left to solve do is pretty much trivial by now.

提交回复
热议问题