Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
How do I insert a random function inside a loop?

So... this is a bit hard to explain, but I want to print with Javascript this result:

enter image description here

  • The '*' character has to be random. SO everytime the page loads, there is a new character randomly exposed inside of my loop. Is it possible? Does anyone have an idea how to get there?

I manage to generate a random function with different characters but they are printing in all rows and always in the same place. What do I have to do to make sure that a random character is printed only once and in a random row every time?

My code:

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);

This is what my code prints:

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try something like below. I created 3 random integers outside the loop, one for character, one for row, and one for the position to insert characters. Use these integers inside the loop

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 Denunciar

0

The question doesn't specifically say that the code is restricted to a loop only, just that you want to create that particular output and that it needs to be changed on every load (at least how I read it)

So if you are free not using a loop, you could also try this option :)

  • It generates the array first with all '#' chars
  • It picks out a random row, col and character and sets it
  • and then prints it to 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda