-2

I need to check all combinations a-z, with a string length of 2. So, example output would be:

aa ab ac ad ae etc.

I've been trying to use for loop, but to no success. This is what I got:

var length = 2;
var password = [];
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

for(var l = 0; l < length; l++)
{
    for(var c = 0; c < 62; c++)
    {
        password[c] = possible.charAt(c);
        document.getElementById("code").innerHTML = password;
    }
}
sanoj00
  • 73
  • 1
  • 2
  • 6

4 Answers4

4

tCheck out this: http://jsfiddle.net/n0m4wvpq/

var passwords = function(chars, length){
    var index=[];
    chars = chars.split("");

    (function loop(base, i){
        for(var k=0; k< chars.length; k++) {
            if(i>1) loop(base+chars[k], i-1);
            else index.push(base+chars[k]);
        }
    })("", length);

    return index;
}

var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var length = 2;
passwords(possible, length);

FUN FACT:

This function can be used to generate Jorge Louis Borges "Library of Babel":

var libraryOfBabel = passwords("abcdefghijklmnopqrstuvwxyz ,.", 1312000);

PS.: Don't try it. :)

greenish
  • 1,042
  • 1
  • 8
  • 18
0

Would this work for you?

var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var x of possible){
    for(var y of possible){
        console.log(x+y);
    }
}
Grekz
  • 1,570
  • 15
  • 22
0

http://jsfiddle.net/y6qnsem4/

var length = 2;
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split('');
console.log(combine(length));

function combine(length, level, previous)
{
  var level = level || 1;
  var previous = previous || possible;
  var ret = [];

  previous.map(function(el) {
     possible.map(function(letter) {
        ret.push(el + letter);
     });
  });

  if (level < length - 1) ret = combine(length, level + 1, ret);

  return ret;
}

It returns array of combinations, but it is not difficult to join it into the string like this alert([1,2,3].join(',')). And it works for any length (but takes more and more time, of course, because number of elements in array will be equal to possible.length ^ length. For possible.length = 62 and length = 2 there are 3844 combinations. And for length = 4 you will 'kill/hang' your browser tab with 14776336 combinations).

Cheery
  • 16,063
  • 42
  • 57
0

Maybe something like this:

var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(''),
    length = 2,
    i = 0,
    j = 0,
    step,
    comb;

for (i; i < possible.length; i++) {
    step = possible[i];
    console.log("==============" + step + "==============");
    for (j; j < possible.length; j++) {
        comb  = step + '' + possible.slice(j, j + (length - 1)).join('');
        console.log(comb);
    }
    j = 0;
}