diksha msc diksha msc - 11 months ago 47
Javascript Question

Find all the combinations of a string Javascript

I want to find all the combinations of a string in javascript. I looked up previously asked questions but there is one output missing and I don't know how to find it.

My code is:

<html>
<head></head>
<body>
<label>Enter word/sentence to generate combinations:</label>
<input type="text" name="comb"/></br>
<input type="button" value="Get Combination" name="combbtn" onclick="substrings()"/>
<script>
function substrings(){
var str=document.getElementsByTagName("input")[0].value;
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
alert(result);
}
</script>
</body>
</html>


When I try "dad" as input, the expected output is:-


d,a,da,d,dd,ad,dad


But my code somehow misses


"dd"


How can I include it. Any help/suggestion?

Answer Source

what you need to do is print all subsequences, this code would do that

function printSubsequences(str){
    let len = str.length, result = [];
    for(let i=1; i<(1<<len); i++){
        let temp = "";
        for(let j=0; j<len; j++){
            if((i&(1<<j))){
                temp = temp +str.charAt(j);
            }
        }
        result.push(temp);
    }
    console.log(result);
}
printSubsequences('dad');

Note the time complexity is exponential

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download