有人能告诉我如何在javascript中进行单词组合。 我是编程新手。我这样做了
var words=["word1","word2","word3","word4"];
实施例
words: [
"word1",
"word2",
"word3",
"word4"
]
输出:
"word1 word2",
"word1 word3",
"word2 word3",
"word1 word2 word3",
"word2 word3 word4",
"word1 word3 word4"
答案 0 :(得分:0)
这是做到这一点的方法之一:
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;
}, []);
更新:如果我已正确理解(更新)的问题,以下代码段应该可以解决问题:
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;
}, []);
答案 1 :(得分:0)
<强> 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);
取自: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"]