javascript 获取字符串的所有组合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12048621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:10:25  来源:igfitidea点击:

get all combinations for a string

javascriptcombinations

提问by RedHatter

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:

我正在尝试在 JavaScript 中创建一个函数,该函数将返回一个包含所有可能字母组合的数组,每个字母最多使用一次,从最短的开始。例如,对于字符串 ABC,它将返回:

A
B
C
AB
AC
ABC

I could use loops like so:

我可以像这样使用循环:

for(i=0; i<string.length; i++) {
   //add string[i]
}
for(i=0; i<string.length; i++) {
    for(a=i; a<string.length; a++) {
            //add string[i]+string[a]
    }
}
for(i=0; i<string.length; i++) {
    for(a=i; a<string.length; a++) {
        for(b=a; b<string.length; b++) {
            //add string[i]+string[a]+string[b]
        }
    }
}

But I don't know the length of the string, so wouldn't know how many loops to use.

但我不知道字符串的长度,所以不知道要使用多少个循环。

Any ideas?

有任何想法吗?

Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.

编辑:我不是要求排列,不应同时返回 abc 和 acb。同样,数组中最短的第一个也很重要。

This is not homework. It's for a program to solve a 'lights-out' type game.

这不是家庭作业。这是一个解决“熄灯”类型游戏的程序。

采纳答案by RedHatter

This is what I ended up using.

这就是我最终使用的。

var combinations = function (string)
{
    var result = [];

    var loop = function (start,depth,prefix)
    {
        for(var i=start; i<string.length; i++)
        {
            var next = prefix+string[i];
            if (depth > 0)
                loop(i+1,depth-1,next);
            else
                result.push(next);
        }
    }

    for(var i=0; i<string.length; i++)
    {
        loop(0,i,'');
    }

    return result;
}

回答by matt3141

This is a recursive solution that I think is very easy to understand.

这是一个我认为很容易理解的递归解决方案。

var tree = function(leafs) {
  var branches = [];
  if (leafs.length == 1) return leafs;
  for (var k in leafs) {
    var leaf = leafs[k];
    tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
      branches.push([leaf].concat(subtree));
    });
  }
  return branches;
};
console.log(tree("abc".split('')).map(function(str) {
  return str.join('')
}))

回答by Jonas Wilms

You could use a nasty trick and increase a counter and use its binary representation as flags:

您可以使用一个讨厌的技巧并增加一个计数器并将其二进制表示用作标志:

 function combine(str){
   const result = [];
   for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
      result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
  return result;
}

Try it

试试看

回答by Mohammad Hassani

This is usiing loop as you expected easiest way.. good luck

这是按照您预期的最简单方法使用循环..祝你好运

        function mixString() {
            var inputy = document.getElementById("mixValue").value
            var result = document.getElementById("mix-result")
            result.innerHTML=""

            
            for (var i = 0 ; i < inputy.length; i++) {
               
                for (var b = 0 ; b < inputy.length; b++) {
                    
                    if (i == b) {
                        
                        result.innerHTML += inputy.charAt(i) + ","
                    }
                    else
                    {
                        result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
                    }
                    
                }

            }
        }
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">JavaScript string combination
</div>
            <div class="panel-body">
                <input id="mixValue" class="form-control" />
                <input type="button" onclick="mixString()" value="click" />
                <div id="mix-result"></div>
            </div>
        </div>
    </div>

回答by SAI KUMAR REDDY NOSSAM

function combinations(var1) {

    var temp;

    for (var i = 0; i < var1.length; i++) {
        var2 = "";

        temp = i;

        while (temp < var1.length) {

            var2 = var2.concat(var1.charAt(temp));
            // console.log(var2)
            if (i == var1.length - 1)
                document.getElementById('result').innerHTML += var2;

            else
                document.getElementById('result').innerHTML += var2 + ',';
            temp++;
        }
    }
}

回答by Nina Scholz

You couldm take an iterative and recursive approach by using the character at the given key or not.

您可以通过使用或不使用给定键处的字符来采用迭代和递归方法。

function combine(string) {
    function iter(i, temp) {
        if (i >= string.length) {
            result.push(temp);
            return;
        }
        iter(i + 1, temp + string[i]);
        iter(i + 1, temp);
    }

    var result = [];
    iter(0, '');
    return result;
}

console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

回答by user3232196

The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.

截至 2019 年 7 月 29 日,已接受的解决方案允许在数组中返回重复的字符串。以下调整通过向推送添加条件来解决这个小问题。

            // however, we don't want duplicates so...
            if (!result.includes(next)) {
                result.push(next);    
            }