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

143
Views
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 answers
Answer question

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 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!