Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda