0

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.

4
  • what do you mean? Are you sure this won't work? Commented Nov 28, 2016 at 1:55
  • what are your criteria? Commented Nov 28, 2016 at 1:57
  • 1
    "I sometimes get a result that's below my criteria (eg: 2 strings, none, etc)" - Huh? The code shown produces one string, so what do you mean by "2 strings", none, etc"? Can you please edit your question to add some examples of the incorrect results? Commented Nov 28, 2016 at 3:11
  • meant to say 'characters'. Commented Nov 28, 2016 at 3:47

1 Answer 1

0

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.