Shuffle an array as many as possible

前端 未结 8 1359
一向
一向 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 05:39

    this one's cuter (but the output from the other example is much clearer): http://jsfiddle.net/wCnLf/

    function shuffle(list) {
        var shufflings = [];
        while(true) {
            var clone = list.slice();
            var shuffling = [];
            var period = 1;
            while(clone.length) {
                var index = Math.floor(shufflings.length / period) % clone.length;
                period *= clone.length;
                shuffling.push(clone.splice(index,1)[0]);
            }
            shufflings.push(shuffling);
            if(shufflings.length == period) return shufflings;
        }
    }
    

    and of course it still outputs all possible "shuffles"

    console.log(shuffle(['a', 'b', 'c', 'd', 'e']));
    

提交回复
热议问题