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?

Zulu
  • 81
  • 3
  • 10
  • @Amadan Oh sorry, I will edit it, yup I did mean ["a","b","c","d"] – Zulu Aug 28 '17 at 02:05
  • Possible duplicate of [How to find all subsets of a set in JavaScript?](https://stackoverflow.com/questions/42773836/how-to-find-all-subsets-of-a-set-in-javascript) – PM 77-1 Aug 28 '17 at 02:09

3 Answers3

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));
}
Solomon Tam
  • 739
  • 3
  • 11
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);
  }
}
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
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/

Xela
  • 2,322
  • 1
  • 17
  • 32