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>
d,a,da,d,dd,ad,dad
"dd"
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