1
var result = [];
let count = 0;
let permutation = function (arr, ans, M) {
    if (ans.length === M) {
        result.push(ans);
    } 
    for (let i = 0; i < arr.length; i++) {
        ans.push(arr[i]);
        permutation(arr.slice(0,i).concat(arr.slice(i + 1)), ans ,M);
        ans.pop()

    }
}
permutation([1,2,3], [], 3);
return result

when I console.log inside if-statement, argument ans correct shows permutation array, but when I push it to result, it does not push it correctly.

I expected result to contain all permutated array.

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
jkco
  • 11
  • 2

1 Answers1

1

You need to get a copy from the array ans. If you push ans directly, you take the object reference and at the end this array is empty, as in all results entries.

var result = [];
let count = 0;
let permutation = function (arr, ans, M) {
    if (ans.length === M) {
        result.push(ans.slice());
        //              ^^^^^^^
    } 
    for (let i = 0; i < arr.length; i++) {
        ans.push(arr[i]);
        permutation(arr.slice(0,i).concat(arr.slice(i + 1)), ans ,M);
        ans.pop()

    }
}

permutation([1,2,3], [], 3);

console.log(result.map(a => a.join(' ')));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392