Reputation: 57
As title says I am trying to generate a random character that has to be either a number or an alphabetic letter and I can't come up with an efficient way to do it.
Edit: Since I am using pseudo-code (and it's handwritten) making a string/array out of all possible values may not be a very good choice.
I was thinking about generating a random integer that matches the ascii code of letters and digits but I could not find a proper way to do it since they're not consecutive.
Upvotes: 2
Views: 219
Reputation: 51756
The simplest way is to use Number.prototype.toString(36)
:
console.log(Math.floor(Math.random() * 36).toString(36));
This will produce a random number or lowercase letter.
Upvotes: 1
Reputation: 2804
Simplest way I can think of is creating an array with all possible values, then randomly choosing one.
I'm going to assume that you meant "digit" when you wrote "number".
Also, that you want a letter regardless of capital or lowercase (I've used uppercase).
Here's a javascript code for it:
var options="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log(options.charAt(Math.floor(options.length*Math.random())));
Upvotes: 2