生成提供的单词的所有组合和排列 [英] Generate all combination and permutation of supplied word

查看:76
本文介绍了生成提供的单词的所有组合和排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用javascript获取所有可能的单词组合?

How can I get all possible combination of words using javascript?

例如-如果我有3个单词Apple,Banana,Orange

For example - if I have 3 word Apple , Banana , Orange

我需要这些单词的所有唯一组合,即

I need all unique combinations of those words I.e.

comb1 = Apple ;
Comb2 = Banana ;
Comb3 = Orange ;
Comb4 = Apple + Banana ;
Comb5 = Apple + Orange ;
Comb6 = Banana + Orange ;
Comb7 = Banana + Apple ;
Comb8 = Orange + Apple ;
Comb9 = Orange + Banana ;
Comb10 = Apple + Banana + Orange ;
Comb11 = Apple + Orange + Banana ;
Comb12 = Banana + Orange + Apple ;
Comb13 = Banana + Apple + Orange ;
Comb14 = Orange + Apple + Banana ;
Comb15 = Orange + Banana + Apple ;

我需要这是动态的,即将根据提供的字数生成组合.

I need this to be dynamic I.e. combination to be generated depending upon a no of words supplied.

我尝试了以下代码,但未获得预期结果

I have tried something like below code but did not get expected result

var permArr = [],result=[],aa=[],
  usedChars = [];
 var comb =['a', 'b','c'];

function permute(input) {
  var i, ch;
  for (i = 0; i < input.length; i++) {
    ch = input.splice(i, 1)[0];
    usedChars.push(ch);
    if (input.length == 0) {
      permArr.push(usedChars.slice());
    }
    permute(input);
    input.splice(i, 0, ch);
    usedChars.pop();
  }
  //return permArr
};

for(var i=0;i<comb.length;i++){
    aa=[];
    for(var j=0;j<=i;j++)

    {
        aa.push(comb[j]);
    }
    permute(aa);

}


FResult = JSON.stringify(permArr);

在未完成输出的输出下方返回代码.

Code return below output which is not completed output.

[["a"],["a","b"],["b","a"],["a","b","c"],["a","c","b"],["b","a","c"],["b","c","a"],["c","a","b"],["c","b","a"]]

我的代码缺少[b,c]和[a,c]以及[b]和[c]的排列.我的permute()函数正常工作.只需提供正确的组合即可.

My code missed to permutation with [b,c] and [a,c] and [b] and [c]. My permute() function work properly. Just need to supply correct combination.

谢谢!

推荐答案

一种生成排列的更有效方法

A more efficient way of generating the permutations

 function permutations(k, curr_perm, included_items_hash){
     if(k==0){
        perm.push(curr_perm);
        return;
     }
     
     
     for(let i=0; i<items.length; i++){

        // so that we do not repeat the item, using an array here makes it O(1) operation
        if(!included_items_hash[i]){
            included_items_hash[i] = true;
            permutations(k-1, curr_perm+items[i], included_items_hash);
            included_items_hash[i] = false;
        }
        
     }
 }

let items = ["a","b","c"];
let perm = [];

// for generating different lengths of permutations
for(let i=0; i<items.length; i++){
    permutations(items.length-i, "", []);
}

console.log(perm);

这篇关于生成提供的单词的所有组合和排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆