Array Arrangement Permutation

前端 未结 4 557
半阙折子戏
半阙折子戏 2021-01-26 18:09

Looking for a way to sequentially find different arrangement possibilities of an array. I only care about adding them sequentially, doesn\'t need skip or shuffle values.

4条回答
  •  一向
    一向 (楼主)
    2021-01-26 18:41

    You need a recursive function to do this.
    Since the amount of possible arrangement of your array is 6! (which is 720), I will shorten it to 3 to shorten the sample result, make the number of possible arrangement to 3! (which is 6)

    var array = ['a', 'b', 'c'];
    var counter = 0; //This is to count the number of arrangement possibilities
    
    permutation();
    console.log(counter); //Prints the number of possibilities
    
    function permutation(startWith){
        startWith = startWith || '';
        for (let i = 0; i < array.length; i++){
            //If the current character is not used in 'startWith'
            if (startWith.search(array[i]) == -1){
                console.log(startWith + array[i]); //Print the string
                    
                //If this is one of the arrangement posibilities
                if ((startWith + array[i]).length == array.length){
                    counter++;
                }
                    
                //If the console gives you "Maximum call stack size exceeded" error
                //use 'asyncPermutation' instead
                //but it might not give you the desire output
                //asyncPermutation(startWith + array[i]);
                permutation(startWith + array[i]);
            }
            else { 
                continue; //Skip every line of codes below and continue with the next iteration
            } 
        }
        function asyncPermutation(input){
            setTimeout(function(){permutation(input);},0);
        }
     }

    The first 3 output is part of your desired output. Hope this answers your question.

提交回复
热议问题