DEV Community

loading...

Discussion on: Daily Challenge #5 - Ten Minute Walk

Collapse
alvaromontoro profile image
Alvaro Montoro

JS

Not a great solution, but a solution.

const createRandomPath = minutes => {
  let path = [];

  // if the minutes are even, calculate path
  if (minutes % 2 === 0) {  
    // populate the array from opposite ends with complementary values
    for (let x = 0; x < minutes/2; x++) {
      const letter = Math.floor(Math.random()*4);
      path[x] = "nsew".charAt(letter);
      path[minutes-x-1] = "snwe".charAt(letter);
    }

    // randomize path
    path.sort((a,b) => Math.floor(Math.random()*2) ? 1 : -1);
  }

  // return the generated array or an empty array if steps are odd
  return path;
}

And a one-liner but not really randomized, just going north-then-south:

const f=m=>m%2?[]:Array(m).fill("n",0,m/2).fill("s",m/2)

And the link to a demo on CodePen