在javascript中进行单词组合

making combination of words in javascript

本文关键字:单词 组合 javascript      更新时间:2023-09-26

有人能告诉我如何用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"

这是一种方法:

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;
}, []);

Plunkr

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"]