Permutations in JavaScript?

前端 未结 30 2652
不思量自难忘°
不思量自难忘° 2020-11-21 06:52

I\'m trying to write a function that does the following:

  • takes an array of integers as an argument (e.g. [1,2,3,4])
  • creates an array of all the possib
30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 07:19

    const permutations = array => {
      let permut = [];
      helperFunction(0, array, permut);
      return permut;
    };
    
    const helperFunction = (i, array, permut) => {
      if (i === array.length - 1) {
        permut.push(array.slice());
      } else {
        for (let j = i; j < array.length; j++) {
          swapElements(i, j, array);
          helperFunction(i + 1, array, permut);
          swapElements(i, j, array);
        }
      }
    };
    
    function swapElements(a, b, array) {
      let temp = array[a];
      array[a] = array[b];
      array[b] = temp;
    }
    
    console.log(permutations([1, 2, 3]));

提交回复
热议问题