diksha msc diksha msc - 2 years ago 127
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:

<label>Enter word/sentence to generate combinations:</label>
<input type="text" name="comb"/></br>
<input type="button" value="Get Combination" name="combbtn" onclick="substrings()"/>
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));

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


But my code somehow misses


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++){
                temp = temp +str.charAt(j);

Note the time complexity is exponential

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