abrahamlinkedin abrahamlinkedin - 10 days ago 6
Javascript Question

javascript generating random characters

I am trying to program a password generator. However, I find that my code is unreliable. I want each run of my function to return 20 random characters. This works most times, however if I spam the function enough times then I sometimes get a result that's below my criteria (eg: 2 strings, none, etc).

var longth = 20,
allc = "!@#$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
passgen = '';
for (var i = 0; i < longth; i++) {
passgen += allc.charAt(Math.floor(Math.random() * allc.length));
}


Not sure if the problem is with logic in my code, or if there's a break in one of the characters in my
allc
variable that's causing problems. Maybe I'm not expressing the variable correctly.

Answer

I don't see any problem with your code. I have modified it slightly to take a direct index out of the array, rather than using charAt but that shouldn't matter.

This code is tested by creating 1,000,000 strings and logs how many failed the creation criteria. It doesn't seem to fail.

function makePassword(){
  var longth = 20,
  allc = "!@#$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  passgen = '';
  for (var i = 0; i < longth; i++) {
    passgen += allc[Math.floor(Math.random() * allc.length)];
  }
  return passgen;
}

// Test
var failed = [];
var result = "";
for(var x = 0; x < 1000000; ++x){
  result = makePassword();
  if(result.length !== 20){
    failed.push(result);
  }
}

console.log("Incorrect strings generated: " + failed.length, failed);