Shuffle an array as many as possible

前端 未结 8 1358
一向
一向 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:40

    As zodiac mentioned the best solution to this problem is a recursive one:

    var permute = (function () {
        return permute;
    
        function permute(list) {
            return list.length ?
                list.reduce(permutate, []) :
                [[]];
        }
    
        function permutate(permutations, item, index, list) {
            return permutations.concat(permute(
                list.slice(0, index).concat(
                list.slice(index + 1)))
                .map(concat, [item]));
        }
    
        function concat(list) {
            return this.concat(list);
        }
    }());
    
    alert(JSON.stringify(permute([1,2,3])));

    Hope that helps.

提交回复
热议问题