Skip to content

Instantly share code, notes, and snippets.

@SpiffGreen
Created May 2, 2022 14:59
Show Gist options
  • Save SpiffGreen/119be00c88d90feddd3431ff9e471726 to your computer and use it in GitHub Desktop.
Save SpiffGreen/119be00c88d90feddd3431ff9e471726 to your computer and use it in GitHub Desktop.
A code snippet to produce permutation of an array

Array Combinator

A library for producing all possible combinations of an array. All with the question of how many ways can elements of an array be arranged. If computationally too complex will return null.

This draws back to the idea of Permutation and Combination. E.g [AB, BA]. Here, we have 1 combination and 2 permutation. Since permutation is concerned with the arrangement, where order does matter. While in combination they are considered same since order doesn't matter.

Formula for combination:

c = n!       

;where
;n = number of elements
;c = number of combinations
const test_array = [1, 2, 3];
function get_combinations(arr) {
var permArr = [],
usedChars = [];
function permute(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr;
}
return permute(arr);
}
const names = "spiff jekey green";
console.log((get_combinations(names.split(" "))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment