user1575921
user1575921

Reputation: 1088

How to generate letter in all possible combinations with specific length limit?

How to generate letter in all possible combinations with specific length limit? in javascript

// return [aaaa, bbbb]

function allPossibleCombinations(inputArray, outputEachStrLength) {
  var inputArrayLength = inputArray.length;
  for (i = 0; i < inputArrayLength; i++) {

  }
}

var inputArray = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z];
var outputEachStrLength = 4;
allPossibleCombinations(inputArray, outputEachStrLength)

http://jsfiddle.net/0jqkpLmv/

Upvotes: 3

Views: 5853

Answers (1)

David Fang
David Fang

Reputation: 1787

You can use a recursive method:

function allPossibleCombinations(input, length, curstr) {
    if(curstr.length == length) return [ curstr ];
    var ret = [];
    for(var i = 0; i < input.length; i++) {
        ret.push.apply(ret, allPossibleCombinations(input, length, curstr + input[i]));
    }
    return ret;
}

var input = [ 'a', 'b', 'c', 'd' ];
console.log(allPossibleCombinations(input, 3, ''));

Upvotes: 18

Related Questions