get all combinations for a string

前端 未结 8 1659
傲寒
傲寒 2020-12-01 19:34

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 wit

相关标签:
8条回答
  • 2020-12-01 20:29

    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>

    0 讨论(0)
  • 2020-12-01 20:33

    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.

                // however, we don't want duplicates so...
                if (!result.includes(next)) {
                    result.push(next);    
                }
    
    0 讨论(0)
提交回复
热议问题