Find all permutations of 2 arrays in JSJavaScript - Generating combinations from n arrays with m elementsHow do I check if an array includes an object in JavaScript?How to append something to an array?How to replace all occurrences of a string in JavaScriptLoop through an array in JavaScriptEasy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionIs Safari on iOS 6 caching $.ajax results?
A king was born in a year that was a perfect square, lived a perfect square number of years, and also died in a year that was a perfect square
How to communicate to my GM that not being allowed to use stealth isn't fun for me?
Proof that 1-P(B|C)=P(~B|C). Is everything correct?
How is John Wick 3 a 15 certificate?
Giant Steps - Coltrane and Slonimsky
is it possible for a vehicle to be manufactured witout a catalitic converter
Can Rydberg constant be in joules?
Overlapping String-Blocks
Using "subway" as name for London Underground?
Importance of Building Credit Score?
How to hide an urban landmark?
How to tell your grandparent to not come to fetch you with their car?
The use of かります in a sentence
Is it a problem if <h4>, <h5> and <h6> are smaller than regular text?
Why can't I use =default for default ctors with a member initializer list
What to do when surprise and a high initiative roll conflict with the narrative?
Is it legal for a bar bouncer to confiscate a fake ID
Why doesn't Adrian Toomes give up Spider-Man's identity?
Should I give professor gift at the beginning of my PhD?
Meaning of 'lose their grip on the groins of their followers'
Fixing obscure 8080 emulator bug?
How do I create a Sector in Stellaris?
Were Alexander the Great and Hephaestion lovers?
What is the highest possible temporary AC at level 1, without any help from others?
Find all permutations of 2 arrays in JS
JavaScript - Generating combinations from n arrays with m elementsHow do I check if an array includes an object in JavaScript?How to append something to an array?How to replace all occurrences of a string in JavaScriptLoop through an array in JavaScriptEasy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missingHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Image Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionIs Safari on iOS 6 caching $.ajax results?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm trying to find every permutations of 2 arrays like this:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords =
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
It should function with more than 3 items, both arrays will always be same length. This is my code:
const keywords =
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount)
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount)
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
result is missing some
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
javascript algorithm
add a comment |
I'm trying to find every permutations of 2 arrays like this:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords =
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
It should function with more than 3 items, both arrays will always be same length. This is my code:
const keywords =
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount)
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount)
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
result is missing some
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
javascript algorithm
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
You are not looking for permutations (which are about order), but for the cartesian product of[one, ONE],[two, TWO]and[three, THREE]. You can get those by transposing your input.
– Bergi
May 22 at 18:32
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13
add a comment |
I'm trying to find every permutations of 2 arrays like this:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords =
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
It should function with more than 3 items, both arrays will always be same length. This is my code:
const keywords =
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount)
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount)
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
result is missing some
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
javascript algorithm
I'm trying to find every permutations of 2 arrays like this:
// input
lowerWords = ['one', 'two', 'three' ]
upperWords = [ 'ONE', 'TWO', 'THREE' ]
// output
keywords =
'one two three': true,
'ONE two three': true,
'ONE TWO three': true,
'ONE TWO THREE': true,
'ONE two THREE': true,
'one TWO three': true,
'one two THREE': true,
'one TWO THREE': true,
It should function with more than 3 items, both arrays will always be same length. This is my code:
const keywords =
const lowerWords = ['one', 'two', 'three' ]
const upperWords = [ 'ONE', 'TWO', 'THREE' ]
const wordCount = lowerWords.length
let currentWord = 0
let currentWords = [...upperWords]
while (currentWord < wordCount)
currentWords[currentWord] = lowerWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
currentWord = 0
currentWords = [...lowerWords]
while (currentWord < wordCount)
currentWords[currentWord] = upperWords[currentWord]
let keyword = currentWords.join(' ')
keywords[keyword] = true
currentWord++
result is missing some
ONE TWO THREE: true
ONE TWO three: true
ONE two three: true
one TWO THREE: true
one two THREE: true
one two three: true
javascript algorithm
javascript algorithm
edited May 22 at 8:53
Dave
asked May 22 at 8:44
DaveDave
9317
9317
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
You are not looking for permutations (which are about order), but for the cartesian product of[one, ONE],[two, TWO]and[three, THREE]. You can get those by transposing your input.
– Bergi
May 22 at 18:32
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13
add a comment |
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
You are not looking for permutations (which are about order), but for the cartesian product of[one, ONE],[two, TWO]and[three, THREE]. You can get those by transposing your input.
– Bergi
May 22 at 18:32
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
You are not looking for permutations (which are about order), but for the cartesian product of
[one, ONE], [two, TWO] and [three, THREE]. You can get those by transposing your input.– Bergi
May 22 at 18:32
You are not looking for permutations (which are about order), but for the cartesian product of
[one, ONE], [two, TWO] and [three, THREE]. You can get those by transposing your input.– Bergi
May 22 at 18:32
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13
add a comment |
6 Answers
6
active
oldest
votes
You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0;
(This fails for the general version withtranspose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]])compare with mine.)
– גלעד ברקן
May 22 at 21:11
2
transposetransposes same length arrays.
– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just callcartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]])if that kind of output is desired.
– Bergi
May 23 at 6:53
|
show 1 more comment
Thought I'd give it a try. I used binary to get the possible combinations, as this problem needed a base 2 solution:
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)Explanation of loop:
1. temp = new Array(len).fill(0)
2. newCombo = i.toString(2).split("");
3. newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
- Creates temp array
[0,0,0] - Grabs loop number (i) and converts it to binary e.g:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
etc...
Then split the binary into an array 100 -> [1,0,0].
- Then for each element push it in that new array. This gave a problem with pushing the 1 and 2 element arrays (
10 -> [1,0]) into the back of the array. I usedtemp.length - newCombo.length + ito fix that.
That function then returns:
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
Then, I can map over each combination, and grab each array depending on the value, and get the words ('one' or 'ONE') via loop index.
Note this code works with more than one array, as long as the arrays are all the same length.
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
add a comment |
We can enumerate these directly. And this may be a good opportunity for you to learn more about recursion. The algorithm is very simple:
If we've reached the end of
the list, return the combination
the current recursion branch is
building.
Otherwise, create a new branch
that picks the next item from B,
while the current branch picks
the next item from A.
JavaScript code:
function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))add a comment |
You need to get a total of 2 ^ 3 combinations. If you create a 2D matrix from the 2 arrays, the below table represents the row number from which of the item should be taken.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you analyze indexes of the combinations, each of this a binary number from 0 to 2 ^ 3 with leading zeros.
So, you could
- loop from 0 to 8
- create binary number using
toString(2) - Add leading zero using
padStart spliteach digit to get an array- Get each item from
matrix[digit-from-binary][position-of-each-split] jointhe array of items with a' 'separator to get the key- Add the key to the output object
function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))You can generalize this for m x n matrix. Instead of converting each to a binary number, you need to convert it to base-m and padStart to length n
function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; add a comment |
Following Code should work for you its recursive approach:
const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)add a comment |
Here's a generalised version based on my other answer that handles a variable number of input arrays with varying lengths:
const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56252742%2ffind-all-permutations-of-2-arrays-in-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0;
(This fails for the general version withtranspose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]])compare with mine.)
– גלעד ברקן
May 22 at 21:11
2
transposetransposes same length arrays.
– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just callcartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]])if that kind of output is desired.
– Bergi
May 23 at 6:53
|
show 1 more comment
You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0;
(This fails for the general version withtranspose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]])compare with mine.)
– גלעד ברקן
May 22 at 21:11
2
transposetransposes same length arrays.
– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just callcartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]])if that kind of output is desired.
– Bergi
May 23 at 6:53
|
show 1 more comment
You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0; You could transpose the arrays for getting an array of pairs and then get all combinations of the pairs.
const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0; const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0; const
transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),
combinations = array => array.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
var lowerWords = ['one', 'two', 'three'],
upperWords = ['ONE', 'TWO', 'THREE'],
pairs = transpose([lowerWords, upperWords]),
result = combinations(pairs);
console.log(result);.as-console-wrapper max-height: 100% !important; top: 0; answered May 22 at 8:54
Nina ScholzNina Scholz
209k16117190
209k16117190
(This fails for the general version withtranspose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]])compare with mine.)
– גלעד ברקן
May 22 at 21:11
2
transposetransposes same length arrays.
– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just callcartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]])if that kind of output is desired.
– Bergi
May 23 at 6:53
|
show 1 more comment
(This fails for the general version withtranspose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]])compare with mine.)
– גלעד ברקן
May 22 at 21:11
2
transposetransposes same length arrays.
– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just callcartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]])if that kind of output is desired.
– Bergi
May 23 at 6:53
(This fails for the general version with
transpose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]]) compare with mine.)– גלעד ברקן
May 22 at 21:11
(This fails for the general version with
transpose([['ONE','TWO','THREE'],['one','two'], [1,2,3,4]]) compare with mine.)– גלעד ברקן
May 22 at 21:11
2
2
transpose transposes same length arrays.– Nina Scholz
May 22 at 21:14
transpose transposes same length arrays.– Nina Scholz
May 22 at 21:14
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@גלעדברקן It's unclear what output you'd want to get from that input anyway.
– Bergi
May 22 at 21:16
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@Bergi I implemented one such clarity.
– גלעד ברקן
May 22 at 21:31
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just call
cartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]]) if that kind of output is desired.– Bergi
May 23 at 6:53
@גלעדברקן Well, with the transposed input format this really doesn't make sense. One should just call
cartesian([['one', 'ONE', 1], ['two','TWO', 2], ['three', 3], [4]]) if that kind of output is desired.– Bergi
May 23 at 6:53
|
show 1 more comment
Thought I'd give it a try. I used binary to get the possible combinations, as this problem needed a base 2 solution:
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)Explanation of loop:
1. temp = new Array(len).fill(0)
2. newCombo = i.toString(2).split("");
3. newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
- Creates temp array
[0,0,0] - Grabs loop number (i) and converts it to binary e.g:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
etc...
Then split the binary into an array 100 -> [1,0,0].
- Then for each element push it in that new array. This gave a problem with pushing the 1 and 2 element arrays (
10 -> [1,0]) into the back of the array. I usedtemp.length - newCombo.length + ito fix that.
That function then returns:
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
Then, I can map over each combination, and grab each array depending on the value, and get the words ('one' or 'ONE') via loop index.
Note this code works with more than one array, as long as the arrays are all the same length.
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
add a comment |
Thought I'd give it a try. I used binary to get the possible combinations, as this problem needed a base 2 solution:
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)Explanation of loop:
1. temp = new Array(len).fill(0)
2. newCombo = i.toString(2).split("");
3. newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
- Creates temp array
[0,0,0] - Grabs loop number (i) and converts it to binary e.g:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
etc...
Then split the binary into an array 100 -> [1,0,0].
- Then for each element push it in that new array. This gave a problem with pushing the 1 and 2 element arrays (
10 -> [1,0]) into the back of the array. I usedtemp.length - newCombo.length + ito fix that.
That function then returns:
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
Then, I can map over each combination, and grab each array depending on the value, and get the words ('one' or 'ONE') via loop index.
Note this code works with more than one array, as long as the arrays are all the same length.
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
add a comment |
Thought I'd give it a try. I used binary to get the possible combinations, as this problem needed a base 2 solution:
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)Explanation of loop:
1. temp = new Array(len).fill(0)
2. newCombo = i.toString(2).split("");
3. newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
- Creates temp array
[0,0,0] - Grabs loop number (i) and converts it to binary e.g:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
etc...
Then split the binary into an array 100 -> [1,0,0].
- Then for each element push it in that new array. This gave a problem with pushing the 1 and 2 element arrays (
10 -> [1,0]) into the back of the array. I usedtemp.length - newCombo.length + ito fix that.
That function then returns:
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
Then, I can map over each combination, and grab each array depending on the value, and get the words ('one' or 'ONE') via loop index.
Note this code works with more than one array, as long as the arrays are all the same length.
Thought I'd give it a try. I used binary to get the possible combinations, as this problem needed a base 2 solution:
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)Explanation of loop:
1. temp = new Array(len).fill(0)
2. newCombo = i.toString(2).split("");
3. newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
- Creates temp array
[0,0,0] - Grabs loop number (i) and converts it to binary e.g:
1 -> 1
2 -> 10
3 -> 11
4 -> 100
etc...
Then split the binary into an array 100 -> [1,0,0].
- Then for each element push it in that new array. This gave a problem with pushing the 1 and 2 element arrays (
10 -> [1,0]) into the back of the array. I usedtemp.length - newCombo.length + ito fix that.
That function then returns:
[ 0, 0, 0 ]
[ 0, 0, 1 ]
[ 0, 1, 0 ]
[ 0, 1, 1 ]
[ 1, 0, 0 ]
[ 1, 0, 1 ]
[ 1, 1, 0 ]
[ 1, 1, 1 ]
Then, I can map over each combination, and grab each array depending on the value, and get the words ('one' or 'ONE') via loop index.
Note this code works with more than one array, as long as the arrays are all the same length.
const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)const low = ["one", "two", "three"];
const up = ["ONE", "TWO", "THREE"];
const words = [low, up]
const len = words[0].length
function getCombinations(noOfArrays, len)
var temp, newCombo, combos = [];
for (var i = 0; i < (noOfArrays ** len); i++)
temp = new Array(len).fill(0)
newCombo = i.toString(noOfArrays).split('');
newCombo.forEach((el, i) => temp[temp.length - newCombo.length + i] = +el);
combos.push(temp);
return combos;
function setCombinations(combos)
return combos.map(combo => combo.map((el, i) => words[el][i]))
var combos = getCombinations(words.length, len)
combos = setCombinations(combos)
console.log(combos)edited May 22 at 10:36
answered May 22 at 9:57
KobeKobe
1,06517
1,06517
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
add a comment |
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
Hi, I had favorited this question to come back later to provide an answer. My answer is very similar to yours (I independently came up, I swear :)). I have also added a generic version of it. Hope you don't mind.
– adiga
May 22 at 13:36
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
@adiga No problem, great minds think alike :p I like this approach because it's very scalable, since you can just change which base you are converting the index to for how many arrays the user provides. I didn't think about using padStart, either, so nicely done 👍
– Kobe
May 22 at 13:53
add a comment |
We can enumerate these directly. And this may be a good opportunity for you to learn more about recursion. The algorithm is very simple:
If we've reached the end of
the list, return the combination
the current recursion branch is
building.
Otherwise, create a new branch
that picks the next item from B,
while the current branch picks
the next item from A.
JavaScript code:
function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))add a comment |
We can enumerate these directly. And this may be a good opportunity for you to learn more about recursion. The algorithm is very simple:
If we've reached the end of
the list, return the combination
the current recursion branch is
building.
Otherwise, create a new branch
that picks the next item from B,
while the current branch picks
the next item from A.
JavaScript code:
function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))add a comment |
We can enumerate these directly. And this may be a good opportunity for you to learn more about recursion. The algorithm is very simple:
If we've reached the end of
the list, return the combination
the current recursion branch is
building.
Otherwise, create a new branch
that picks the next item from B,
while the current branch picks
the next item from A.
JavaScript code:
function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))We can enumerate these directly. And this may be a good opportunity for you to learn more about recursion. The algorithm is very simple:
If we've reached the end of
the list, return the combination
the current recursion branch is
building.
Otherwise, create a new branch
that picks the next item from B,
while the current branch picks
the next item from A.
JavaScript code:
function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))function f(A, B, i=0, comb=[])
return i == A.length
? [comb]
: f(A, B, i + 1, comb.concat(A[i])).concat(
f(A, B, i + 1, comb.slice().concat(B[i])))
console.log(JSON.stringify(f(['one','two','three'], ['ONE','TWO','THREE'])))edited May 22 at 11:03
answered May 22 at 10:45
גלעד ברקןגלעד ברקן
14.1k21646
14.1k21646
add a comment |
add a comment |
You need to get a total of 2 ^ 3 combinations. If you create a 2D matrix from the 2 arrays, the below table represents the row number from which of the item should be taken.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you analyze indexes of the combinations, each of this a binary number from 0 to 2 ^ 3 with leading zeros.
So, you could
- loop from 0 to 8
- create binary number using
toString(2) - Add leading zero using
padStart spliteach digit to get an array- Get each item from
matrix[digit-from-binary][position-of-each-split] jointhe array of items with a' 'separator to get the key- Add the key to the output object
function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))You can generalize this for m x n matrix. Instead of converting each to a binary number, you need to convert it to base-m and padStart to length n
function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; add a comment |
You need to get a total of 2 ^ 3 combinations. If you create a 2D matrix from the 2 arrays, the below table represents the row number from which of the item should be taken.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you analyze indexes of the combinations, each of this a binary number from 0 to 2 ^ 3 with leading zeros.
So, you could
- loop from 0 to 8
- create binary number using
toString(2) - Add leading zero using
padStart spliteach digit to get an array- Get each item from
matrix[digit-from-binary][position-of-each-split] jointhe array of items with a' 'separator to get the key- Add the key to the output object
function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))You can generalize this for m x n matrix. Instead of converting each to a binary number, you need to convert it to base-m and padStart to length n
function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; add a comment |
You need to get a total of 2 ^ 3 combinations. If you create a 2D matrix from the 2 arrays, the below table represents the row number from which of the item should be taken.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you analyze indexes of the combinations, each of this a binary number from 0 to 2 ^ 3 with leading zeros.
So, you could
- loop from 0 to 8
- create binary number using
toString(2) - Add leading zero using
padStart spliteach digit to get an array- Get each item from
matrix[digit-from-binary][position-of-each-split] jointhe array of items with a' 'separator to get the key- Add the key to the output object
function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))You can generalize this for m x n matrix. Instead of converting each to a binary number, you need to convert it to base-m and padStart to length n
function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; You need to get a total of 2 ^ 3 combinations. If you create a 2D matrix from the 2 arrays, the below table represents the row number from which of the item should be taken.
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you analyze indexes of the combinations, each of this a binary number from 0 to 2 ^ 3 with leading zeros.
So, you could
- loop from 0 to 8
- create binary number using
toString(2) - Add leading zero using
padStart spliteach digit to get an array- Get each item from
matrix[digit-from-binary][position-of-each-split] jointhe array of items with a' 'separator to get the key- Add the key to the output object
function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))You can generalize this for m x n matrix. Instead of converting each to a binary number, you need to convert it to base-m and padStart to length n
function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))function getAllCombinations(matrix)
const combinations = 2 ** 3,
output = ;
for(let i = 0; i < combinations; i++)
const key = i.toString(2)
.padStart(3, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([['one', 'two', 'three' ],[ 'ONE', 'TWO', 'THREE' ]]))function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; function getAllCombinations(matrix)
const rows = matrix.length,
columns = matrix[0].length,
combinations = rows ** columns,
output =
for(let i = 0; i < combinations; i++)
const key = i.toString(rows)
.padStart(columns, 0)
.split('')
.map((n, j) => matrix[n][j])
.join(" ")
output[key] = true;
return output
console.log(getAllCombinations([[1, 2, 3 ],[ 4, 5, 6], [ 7, 8, 9]])) // 3 x 3 matrix
console.log(getAllCombinations([[1, 2], [3, 4], [5, 6], [7, 8]])) // 4 x 2 matrix.as-console-wrapper max-height: 100% !important; top: 0; edited May 22 at 13:45
answered May 22 at 13:32
adigaadiga
15.9k62846
15.9k62846
add a comment |
add a comment |
Following Code should work for you its recursive approach:
const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)add a comment |
Following Code should work for you its recursive approach:
const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)add a comment |
Following Code should work for you its recursive approach:
const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)Following Code should work for you its recursive approach:
const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)const lowerWords = ['one', 'two', 'three']
const upperWords = ['ONE', 'TWO', 'THREE']
let result = ;
function getCombinations(index, caseType, arr)
if (index == 3)
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
result[arr.join(' ')] = true
return
arr[index] = (caseType == 'lower' ? lowerWords : upperWords)[index];
getCombinations(index + 1, 'lower', arr);
getCombinations(index + 1, 'upper', arr);
getCombinations(0, 'lower', [])
getCombinations(0, 'upper', [])
console.log('resultresult', result)edited May 22 at 11:06
Kobe
1,06517
1,06517
answered May 22 at 9:23
JackOfAshes - Mohit GawandeJackOfAshes - Mohit Gawande
14217
14217
add a comment |
add a comment |
Here's a generalised version based on my other answer that handles a variable number of input arrays with varying lengths:
const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)add a comment |
Here's a generalised version based on my other answer that handles a variable number of input arrays with varying lengths:
const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)add a comment |
Here's a generalised version based on my other answer that handles a variable number of input arrays with varying lengths:
const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)Here's a generalised version based on my other answer that handles a variable number of input arrays with varying lengths:
const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)const g = (arrs, i=0, comb=[]) =>
!arrs.some(arr => i < arr.length)
? [comb]
: arrs.reduce((acc, arr) =>
i >= arr.length ? acc :
acc.concat(g(arrs, i + 1, comb.slice().concat(arr[i])))
, [])
// Example output
let input = [['ONE','TWO','THREE'], ['one','two'], [1,2,3,4]]
let str = ''
for (let line of g(input))
str += JSON.stringify(line) + 'n'
console.log(str)edited May 24 at 10:30
answered May 22 at 20:43
גלעד ברקןגלעד ברקן
14.1k21646
14.1k21646
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56252742%2ffind-all-permutations-of-2-arrays-in-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
in your desired answer 3rd and 9th are repeating.
– JackOfAshes - Mohit Gawande
May 22 at 8:51
@Tigger no, those are combinations of 2, I need permutation of every item
– Dave
May 22 at 8:52
@JackOfAshes-MohitGawande yes that's a mistake
– Dave
May 22 at 8:52
You are not looking for permutations (which are about order), but for the cartesian product of
[one, ONE],[two, TWO]and[three, THREE]. You can get those by transposing your input.– Bergi
May 22 at 18:32
@Bergi I'm not sure if your suggestion generalises to arbitrary input (see my comment under Nina Scholz's answer).
– גלעד ברקן
May 22 at 21:13