Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created January 23, 2020 16:35
Show Gist options
  • Save rajivnarayana/5e48aef2f82cf1d463441696683c71bf to your computer and use it in GitHub Desktop.
Save rajivnarayana/5e48aef2f82cf1d463441696683c71bf to your computer and use it in GitHub Desktop.
A routine to print all arrangements of the given numbers in an array avoiding duplicates.
const arr = [1,2,3,2];
const swap = (i, j) => {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
const print = () => {
console.log(arr);
}
const permutate = (start) => {
if (start == arr.length) {
print();
return;
}
permutate(start+1);
for (let i= start+1; i < arr.length; i++) {
if (arr.slice(start, i).indexOf(arr[i]) != -1) continue;
swap(start, i);
permutate(start+1);
swap(i, start);
}
}
permutate(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment