I've been working on permutations within javascript so that I can colelct numbers that corrospond to letters for example a telephone keypad. What I want to do is take those letters that corrospond to keys, split them into an arrays and pass those arrays to a function to find all possible permutations or combinations.
Let's look at what I have so far. I have the numbers and their letters stored as an array
var array = [{ key: '2', value: 'a,b,c'},
{ key: '3', value: 'd,e,f'},
{ key: '4', value: 'g,h,i'}]
I then want to iterate over this array and grab the letters that corrospond to the keys.
for(var thingy of array){
var letters = thingy.value;
var splitArray = letters.split(',')
}
That gives me the letters split up as ["a", "b", "c"]
so now I want take these multiple arrays and pass them to a function that looks for all combinations. This is a function I got from this thread: Finding All Combinations of JavaScript array values
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1));
for (var c in allCasesOfRest) {
console.log("huh?" + allCasesOfRest);
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}
This function expects the format of the arrays to be something like
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
So my question is how do I pass my newly split arrays to this function in the correct format and also at what point should I do it? Should I carry this out in the iteration loop of the arrays?
Here is my complete code so far that I've yet to get working.
$(function() {
var array = [{ key: '2', value: 'a,b,c'},
{ key: '3', value: 'd,e,f'},
{ key: '4', value: 'g,h,i'}]
array.toString();
console.log(array);
//Iterate over the array and find the value label
for(var thingy of array){
var letters = thingy.value;
//Split the characters up
var splitarray = letters.split(',')
//Output all arrays via function to find permutations
//Hmm should this live here?
console.log(allPossibleCases(splitarray));
}
});
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
console.log("huh?" + allCasesOfRest);
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}