Reputation: 25
Can someone tell me me how to make word combinations in javascript. I am new to programming. I did this
var words=["word1","word2","word3","word4"];
Ex:
words: [
"word1",
"word2",
"word3",
"word4"
]
output:
"word1 word2",
"word1 word3",
"word2 word3",
"word1 word2 word3",
"word2 word3 word4",
"word1 word3 word4"
Upvotes: 1
Views: 948
Reputation: 18763
JS
// array of words
var words = ["word1", "word2", "word3", "word4"];
// array to hold results
var result = [];
// number of times we need to iterate to check over all possible combinations
var setCount = Math.pow(2, words.length) - 1;
// loop over iterations
for (var i = 0; i < setCount; i++) {
// array to hold this result
var innerList = [];
for (var j = 0; j < words.length; j++) {
// Each position in the initial list maps to a bit here
var position = 1 << j;
// if the bits when bitwise AND are position then this is unique match
if ((i & position) == position) {
// insert into inner list
innerList.push(words[j]);
}
}
// insert into results if it isn't empty or a size of 1
if(innerList.length !== 0 && innerList.length !== 1) {
result.push(innerList);
}
}
// purely for printing
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
console.log(result.length);
Taken from: http://blogs.msmvps.com/kathleen/2013/12/31/algorithm-find-all-unique-combinations-in-a-list/
["word1", "word2"]
["word1", "word3"]
["word2", "word3"]
["word1", "word2", "word3"]
["word1", "word4"]
["word2", "word4"]
["word1", "word2", "word4"]
["word3", "word4"]
["word1", "word3", "word4"]
["word2", "word3", "word4"]
Upvotes: 0
Reputation: 144679
This is one of way of doing it:
var ret = ["word1","word2","word3","word4"].reduce(function(ret, el, i, arr) {
var n = arr.slice(++i);
ret = ret.concat(n.map(function(_el) {
return el + ' ' + _el;
}));
return ret;
}, []);
update: If I have understood the (updated) question properly the following snippet should do the trick:
var ret = ["word1", "word2", "word3", "word4", "word5"].reduce(function (ret, el, i, arr) {
var n = arr.slice(++i);
[2, 3].forEach(function (c) {
ret = ret.concat(n.map(function (_, i) {
return [el].concat(n.slice(i)).slice(0, c).join(' ');
}));
});
if ( i === arr.length - 1 ) ret.pop();
return ret;
}, []);
Upvotes: 1