-1

I have implemented Heap's non-recursive algorithm in JavaScript. When checking permutations with console.log(arr) everything works as expected. But when I try to push each permutation to a result array, then everything breaks up. It just returns result filled with last iteration permutation.

function generate(n, arr) {
	function swap(item1, item2){
		console.log(item1, item2);
		let tmp = arr[item1];
		arr[item1] = arr[item2];
		arr[item2] = tmp;
	}
	var c = [];
	var allPermutations = [];
	
	for (let i = 0; i < n; i++) {
		c[i] = 0;
	}
	
	console.log(arr);
	allPermutations.push(arr);
	
	for (let i = 1; i < n; i) {
		if (c[i] < i) {
			if (i % 2 == 0) {
				swap(0, i);
			} else {
				swap(c[i], i);
			}
			
			console.log(arr);
			allPermutations.push(arr);
			
			c[i] += 1;
			i = 1;
		} else {
			c[i] = 0;
			i += 1;
		}
	}
	
	return allPermutations;
}

console.log('result', generate(3, ["a", "a", "b"]));

5
  • 2
    You must read How to Ask and fix your post! Commented Sep 22, 2016 at 20:29
  • You cannot be bother to cut'n'paste the code. I cannot be bothered to follow the link Commented Sep 22, 2016 at 20:29
  • @EdHeal is static output better than repl?... Commented Sep 22, 2016 at 20:30
  • 2
    @rubylifequestions Stackoverflow has snipplets that run... and if someone wants to play, they push a button and it is copied to an answer. Commented Sep 22, 2016 at 20:31
  • @epascarello wow I didn't knew that! Sorry! Commented Sep 22, 2016 at 20:34

2 Answers 2

1

The problem is that arrays are just references so when you push in the array you are just pushing a reference to it. So, on the next iteration you update the array and when you look at the final output, all the indexes will be the same since it is the same array.

So what can you do? clone it.

allPermutations.push(arr.slice(0));
Sign up to request clarification or add additional context in comments.

Comments

0

Yep - its a reference problem. Alternative to epascarello's answer:

allPermutations.push([...arr]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.