Reputation: 13
I need to generate ~6 random characters using letters A-G and numbers 5-9. Can this be done using Math.random
? They don't have to be unique every time. I have found this:
Math.floor(0|Math.random()*9e6).toString(36)
and it does work really well, but can I modify this to make it use certain characters (something like replace(/[^a-z]+/g, '')
but in a more specific way) without adding arrays
etc?
Edit: where is the fifth guy's answer?
Upvotes: 1
Views: 997
Reputation: 884
You can totally use Math to pick random elements from the array (in this case the characters that will construct the random Id code) and concatenate those into the code string
steps:
Code:
const array = ["A", "B", "C", "D", "E", "F", "G", "5", "6", "7", "8", "9"];
let codeString = "";
for(i=0 ; i<6 ; i++){
const randomIndex = Math.floor(Math.random()* array.length);
codeString = codeString + array[randomIndex];
}
console.log(codeString);
Upvotes: 2
Reputation: 386634
You could use different function with different factors and offsets for letters and numbers in the wanted range.
function getRandomLetter() { // A B C D E F G
return Math.floor(Math.random() * 7 + 10).toString(36).toUpperCase();
// ^ count of wanted letters
// ^^ offset for the first letter, to get A
// with a random result of zero
}
function getRandomNumber() { // 5 6 7 8 9
return Math.floor(Math.random() * 5 + 5).toString(36);
// ^ 9 - 5 + 1 or count, as factor
// ^ offset
}
console.log(getRandomLetter());
console.log(getRandomNumber());
Upvotes: 2
Reputation: 1980
If the pattern of the random characters appearing isn't very important then I would do something like this
// This function helps us generate a random number between two numbers.
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// The characters we need
var characterArray = ["A", "B", "C", "D", "E", "F", "G", 1, 2, 3, 4, 5, 6, 7, 8, 9];
// Now run a loop six times, get a random number between 0 and the length of the characterArray and concatenate it into a new variable
var randomString = "";
for ( var i = 0; i < 6; i++) {
randomString += characterArray[ random(0, characterArray.length - 1) ];
}
console.log( randomString );
The code can be shortened even further for e.g instead of actually making an array of characters, we can assign a string characterArray = "ABCDE...7,8,9"
as a string is also an array of characters and serves the purpose similarly, but I thought it would be a good idea to write it in a way that is self-explanatory for you to understand and add or change anything in the code as you like.
With a function to give us a random number between two numbers, we can use an array that contains all the characters that our result can have. Then, since we want to get a random number with 6 different characters we use a for loop
, run it six times, each time it gets a random element from the array of characters, and does the job.
Upvotes: 0