Last active
September 4, 2021 10:37
-
-
Save francoisromain/31002e2d5f596ff8abf0 to your computer and use it in GitHub Desktop.
permutations.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
A function that generates every possible sequences of permutations | |
of elements in a given array. | |
For example | |
with a given array ['rock', 'paper', 'scissors'] | |
and a size = 3; | |
the output should look something like: | |
[["rock", "rock", "rock"], | |
["rock", "rock", "paper"], | |
["rock", "rock", "scissors"], | |
["rock", "paper", "rock"], | |
...etc... | |
] | |
*/ | |
var permutations = function (size, array) { | |
var solutions = []; | |
var solution = []; | |
var findSolutions = function(n) { | |
// base case | |
if (n === size) { | |
solutions.push(solution.slice()); | |
return; | |
} | |
for (var i = 0; i < array.length; i++) { | |
solution.push(array[i]); | |
findSolutions(n+1); | |
solution.splice(n,1); | |
} | |
} | |
findSolutions(0); | |
return solutions; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment