Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
¿Cómo inserto una función aleatoria dentro de un bucle?

Entonces... esto es un poco difícil de explicar, pero quiero imprimir con Javascript este resultado:

ingrese la descripción de la imagen aquí

  • El carácter '*' tiene que ser aleatorio. Entonces, cada vez que se carga la página, hay un nuevo personaje expuesto aleatoriamente dentro de mi ciclo. ¿Es posible? ¿Alguien tiene una idea de cómo llegar allí?

Logro generar una función aleatoria con diferentes caracteres pero se imprimen en todas las filas y siempre en el mismo lugar. ¿Qué debo hacer para asegurarme de que un carácter aleatorio se imprima solo una vez y en una fila aleatoria cada vez?

Mi código:

 const characters = '&%$*'; function generateRandomCode() { let result = "" let charactersLength = characters.length; for (let i = 0; i < 1; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result } let string = ""; for (let i = 1; i <= 5; i++) { for (j = 1; j <= 5; j++) { string += "#"; } string += generateRandomCode(); generateRandomCode(); string += "<br>"; } document.write(string);

Esto es lo que imprime mi código:

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Prueba algo como a continuación. Creé 3 enteros aleatorios fuera del ciclo, uno para el carácter, uno para la fila y otro para la posición para insertar caracteres. Usa estos enteros dentro del ciclo

 const characters = '&%$*'; let string = ""; let rand = generateRandomCode(); // generate an array of 3 random numbers. console.log(rand); for (let i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { string += rand[1] === i && rand[2] === j ? characters[rand[0]] : "#"; } string += "<br>"; } function randomIntFromInterval(min, max) { // min and max included return Math.floor(Math.random() * (max - min + 1) + min) } function generateRandomCode() { return [randomIntFromInterval(0, 3), randomIntFromInterval(0, 4), randomIntFromInterval(0, 4)] } document.write(string);

about 4 years ago · Juan Pablo Isaza Report

0

La pregunta no dice específicamente que el código está restringido solo a un bucle, solo que desea crear esa salida en particular y que debe cambiarse en cada carga (al menos como lo leo)

Entonces, si no está usando un bucle, también puede probar esta opción :)

  • Primero genera la matriz con todos los caracteres '#'
  • Selecciona una fila, una columna y un carácter al azar y lo configura
  • y luego lo imprime en html

 const characters = '&$*'; const size = 5; // create an array with all entries const set = new Array(size).fill().map( _ => new Array(size).fill('#') ); // choose the row based on the size of the array const row = Math.floor( Math.random() * set.length ); // choose a column based on the size of the row selected const col = Math.floor( Math.random() * set[row].length ); // choose a character based on the size of the string const char = Math.floor( Math.random() * characters.length ); // overwrite the pre-existing # with the random char set[row][col] = characters[char]; // map the rows to a string and join everything with <br /> document.querySelector('#container').innerHTML = set.map( row => row.join('') ).join('<br />');
 #container { font-family: 'Courier New'; }
 <div id="container"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!