Generate permutations of JavaScript array

后端 未结 4 1402
失恋的感觉
失恋的感觉 2020-11-27 06:20

I have an array of n different elements in javascript, I know there are n! possible ways to order these elements. I want to know what\'s the most effective (fastest) algorit

4条回答
  •  感情败类
    2020-11-27 06:55

    This function, perm(xs), returns all the permutations of a given array:

    function perm(xs) {
      let ret = [];
    
      for (let i = 0; i < xs.length; i = i + 1) {
        let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));
    
        if(!rest.length) {
          ret.push([xs[i]])
        } else {
          for(let j = 0; j < rest.length; j = j + 1) {
            ret.push([xs[i]].concat(rest[j]))
          }
        }
      }
      return ret;
    }
    
    console.log(perm([1,2,3]).join("\n"));

提交回复
热议问题