Estoy haciendo un juego de palabras que elige 8 letras al azar del alfabeto y el jugador debe encontrar palabras que usen estas letras. Debo encontrar una manera de hacer que las letras seleccionadas siempre contengan 3 vocales y 5 consonantes. Apreciaría tu ayuda
Aquí está el código que estoy usando para elegir las letras aleatorias para el juego.
function makeid(length) { var result = ''; var characters = 'aaabcdeeefghiiijklmnooopqrstuuuvwxyz'; var charactersLength = characters.length; for (var i = 0; i < length; i++) { let letter = characters.charAt(Math.floor(Math.random() * charactersLength)); while (result.match(letter)) { letter = characters.charAt(Math.floor(Math.random() * charactersLength)); } result += letter; } return result; } console.log("Id of 8 characters", makeid(8))Es mucho código, pero esto funciona para mí.
La función comienza con un bucle for, que genera 8 letras diferentes. dentro de ese bucle, Math.random() hace que haya un 37,5 % de posibilidades de que se agregue una vocal a randomArray y un 62,5 % de que se agregue una consonante (8 caracteres de los cuales 3 son vocales, por lo que 3/8 = 0,375 ).
cuando se hace 8 veces (gracias al bucle for), la matriz se convertirá en una cadena y la función devolverá la cadena (que para entonces es un código de letra de 8 dígitos con 3 vocales y 5 consonantes).
Espero que esta explicación ayude(;
function getRandomString() { const vowels = 'aeiou' const consonants = 'bcdfghjklmnpqrstvwxyz' let randomArray = [] let amountOfVowels = 0 let amountOfConsonants = 0 for (let i = 0; i < 8; i++) { if (Math.random() < 0.375 && amountOfVowels < 3) addVowel() else if (amountOfConsonants < 5) addConsonant() else addVowel() } function addVowel() { randomArray.push(vowels[Math.floor(Math.random() * vowels.length)]) amountOfVowels++ } function addConsonant() { randomArray.push(consonants[Math.floor(Math.random() * consonants.length)]) amountOfConsonants++ } let finalString = '' for (let i = 0; i < 8; i++) { finalString += randomArray[i] } return finalString; } console.log('random string:', getRandomString())La respuesta de @Lars es casi perfecta, el único problema es que la cadena final no se baraja realmente.
Le sugiero que simplemente cree dos matrices: vocales aleatorias y consonantes aleatorias y luego simplemente mézclelas utilizando el algoritmo de Fisher-Yates .
function getRandomCharsFromString(str, length) { return Array.from({length}, () => { return str[Math.floor(Math.random() * str.length)] }); } function shuffle(str) { var a = str.split(""), n = a.length; for (var i = n - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); // Swap them with ES6 destructuring magic [a[i], a[j]] = [a[j], a[i]]; } return a.join(""); } function getRandomString() { const vowels = 'aeiou'; const consonants = 'bcdfghjklmnpqrstvwxyz'; const randomVowels = getRandomCharsFromString(vowels, 3); const randomConsonants = getRandomCharsFromString(consonants, 5); const randomWord = [...randomVowels, ...randomConsonants].join('') return shuffle(randomWord) } console.log('random string:', getRandomString())Mencionaste que no quieres letras repetidas; muchas palabras en inglés tienen letras duplicadas. ¿Por qué es un requisito?
Puede barajar las vowels y consonants y obtener los primeros x caracteres de esa cadena.
// This version makes sure characters are not repeated function getRandomCharsFromString(str, length) { return shuffle(str).slice(0, length); } function shuffle(str) { var a = str.split(''), n = a.length; for (var i = n - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); // Swap them with ES6 destructuring magic [a[i], a[j]] = [a[j], a[i]]; } return a; } function getRandomString() { const vowels = 'aeiou'; const consonants = 'bcdfghjklmnpqrstvwxyz'; const randomVowels = getRandomCharsFromString(vowels, 3); const randomConsonants = getRandomCharsFromString(consonants, 5); const randomWord = [...randomVowels, ...randomConsonants].join('') return shuffle(randomWord).join('') } console.log('random string:', getRandomString())Tenga una matriz de consonantes y una matriz de vocales.
Use una función de barajar, aquí hay un trazador de líneas conciso:
const shuffle = array => array.sort(() => Math.random() - 0.5); La función anterior devolverá una matriz determinada en un orden aleatorio, por lo que deberá acortar cada matriz en 5 ( consonants ) y 3 ( vowels ):
let C = shuffle(consonants); let V = shuffle(vowels); C.length = 5; V.length = 3;Fácil 😎
// Utility Function (optional) const log = data => console.log(JSON.stringify(data)); const consonants = ["B", "C", "D", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"]; const vowels = ["A", "E", "I", "O", "U"]; const shuffle = array => array.sort(() => Math.random() - 0.5); let C = shuffle(consonants); let V = shuffle(vowels); C.length = 5; V.length = 3; const result = shuffle(V.concat(C)); log(result);