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

144
Vistas
Randomize the first element of consecutive elements in an array

I'm making the Snake Game and want to randomize the position. The snake is an array of 3 objects, each with x and y coordinates. I want to randomize only the first object, and the rest, either the x or the y coordinates, would just add 1 on it.

The code below won't work because every x and y is calling a different random number. What are the workarounds?

function randomPos() {
  let x = Math.floor(Math.random()*numOfColumns + 1)
  let y = Math.floor(Math.random()*numOfRows + 1)
  return { x, y } 
}
const snakeBody = [
  {x: randomPos().x, y: randomPos().y},
  {x: randomPos().x + 1, y: randomPos().y},
  {x: randomPos().x + 2, y: randomPos().y}
]
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are returning an x and y coordinate in your function randomPos() but you are only ever using one of them.

Additionally you only need one random position but you're calling randomPos() 6 times.

Only call it once as it calculates both an x and y coordinate and you only need one position, not 6. Then use both those values using object destructuring and use them to calculate the other two values.

const numOfColumns = 20;
const numOfRows = 20;

function randomPos() {
  let x = Math.floor(Math.random()*numOfColumns + 1)
  let y = Math.floor(Math.random()*numOfRows + 1)
  return { x, y } 
}

const { x: x1st, y: y1st } = randomPos()
const snakeBody = [
  {x: x1st, y: y1st},
  {x: x1st + 1, y: y1st},
  {x: x1st + 2, y: y1st}
]

console.log(snakeBody);

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