Question:
I am generating a function that randomly generates a string of characters of a length given by the num
parameter:
function generarRandom(num) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
let result = "";
for (let i = 0; i < num; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(generarRandom(6));
but I have not been able to make it not generate repeating characters.
Answer:
The best way to ensure that items are random and not repeating is to randomly shuffle the collection of possible items.
In other words, it's like dealing cards from a deck: shuffle it and then take the first N items.
function barajar(array) { let posicionActual = array.length; while (0 !== posicionActual) { const posicionAleatoria = Math.floor(Math.random() * posicionActual); posicionActual--; //"truco" para intercambiar los valores sin necesidad de una variable auxiliar [array[posicionActual], array[posicionAleatoria]] = [ array[posicionAleatoria], array[posicionActual]]; } return array; } function generarAleatorios(cantidad) { const caracteres = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""); barajar(caracteres); return caracteres.slice(0,cantidad).join("") } console.log(generarAleatorios(5)); console.log(generarAleatorios(8)); console.log(generarAleatorios(62));