0

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:

 var someStr = ["a","b","c","d"];

 //I want to produce this outcome

 a
 ab
 abc
 abcd
 b
 bc
 bcd
 c
 cd
 d

I know I can get the # of possibilities for "a" only by this way:

 var numCombinations = 0;
 var comboString = '';
 var outcome = [];

 for(var i = 0; i < someStr.length; i++){

    comboString += someStr[i];

    outcome[i] = comboString;

    numCombinations += i; //# of combinations from above

 }

But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?

2
  • @Amadan Oh sorry, I will edit it, yup I did mean ["a","b","c","d"] Commented Aug 28, 2017 at 2:05
  • Possible duplicate of How to find all subsets of a set in JavaScript? Commented Aug 28, 2017 at 2:09

3 Answers 3

3

Hope this help.

function getComboStringListFromIdx(arr, idx){
    var result = [];
    var comboString = '';
    for(var i=idx; i<arr.length; i++){
        comboString += arr[i];
        result.push(comboString);
    }
    return result;
}

var someStr = ['a','b','c','d'];

var outCome = [];
for(var i = 0; i<someStr.length; i++){
    outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
Sign up to request clarification or add additional context in comments.

1 Comment

You're a genius, i love you
1

I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!

var someStr = ["a","b","c","d"];

for(var i = 0;i < someStr.length;i++) {
   output(i);  
}
function output(index) {
var str = "";
  for(var j in someStr) {
    if(j < index) {
        continue;
    }
    str += someStr[j];
    console.log(str);
  }
}

Comments

1

This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.

var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
    var str = arr[i];
    for(var j=i;j<arr.length;j++){
    if(i!==j)
        str+=arr[j];
    console.log(str);
  }
}

https://jsfiddle.net/fmy539tj/

1 Comment

Wow I've never thought of it this way, brilliant!! Ty!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.