Shuffle an array as many as possible

前端 未结 8 1354
一向
一向 2020-12-07 05:21

I have an array like this

[0,2,3]

The possible shuffling of this array are

[0,2,3], [2,3,0], [3,0,2], [3,2,0], [0,3,2],         


        
相关标签:
8条回答
  • 2020-12-07 06:00

    Try a recursive approach. Here's a hint: every permutation of [0,2,3] is either

    • [0] plus a permutation of [2,3] or
    • [2] plus a permutation of [0,3] or
    • [3] plus a permutation of [0,2]
    0 讨论(0)
  • 2020-12-07 06:02

    you don't need to recurse. The demo should make the pattern pretty clear: http://jsfiddle.net/BGYk4/

    function shuffle(arr) {
            var output = [];
            var n = arr.length;
            var ways = [];
            for(var i = 0, j = 1; i < n; ways.push(j *= ++i));
            var totalWays = ways.pop();
            for(var i = 0; i < totalWays; i++) {
                    var copy = arr.slice();
                    output[i] = [];
                    for(var k = ways.length - 1; k >= 0; k--) {
                            var c = Math.floor(i/ways[k]) % (k + 2);
                            output[i].push(copy.splice(c,1)[0]);
                    }
                    output[i].push(copy[0]);
            }
            return output;
    }
    

    this should output all possible "shuffles"

    console.log(shuffle(['a', 'b', 'c', 'd', 'e']));
    
    0 讨论(0)
提交回复
热议问题