DEV Community

Discussion on: Daily Challenge #5 - Ten Minute Walk

Collapse
 
ryansmith profile image
Ryan Smith • Edited

Here is my JavaScript solution.

My approach was to depart in some random direction, duplicate that initial set of directions, reverse each individual direction within that copy (north goes to south, etc.), then reverse that entire copy to return to the starting point.

/**
 * Generate directions for a walk on a grid that returns to its origin point where one block takes one minute.
 */
function generateWalk (timeInMinutes) {
  const midpoint = Math.trunc(timeInMinutes / 2)
  const compass = ['n', 'e', 's', 'w']
  let departureDirections = []
  let returnDirections = []

  for (let i = 0; i < midpoint; i++) {
    // For the first half of the walk, generate random directions.
    departureDirections[i] = compass[Math.floor(Math.random() * Math.floor(compass.length))]

    // If the direction's index is less than 2 (north, east), shift forward two directions to its reverse direction. Otherwise if it is greater than 2 (south, west), shift it backward two directions to its reverse direction.
    if (compass.indexOf(departureDirections[i]) < 2) {
      returnDirections[i] = compass[compass.indexOf(departureDirections[i]) + 2]
    } else {
      returnDirections[i] = compass[compass.indexOf(departureDirections[i]) - 2]
    }
  }

  // Reverse the return directions in order to return to the starting point.
  returnDirections.reverse()

  // Concatenate the departure array with the return array to get the full directions.
  return departureDirections.concat(returnDirections)
}

The part I had trouble with was swapping each individual direction. I stored my directions in an array that follows a compass because I figured that the reverse direction is always two away: north's array position + 2 = south, east + 2 = west. I ran into some trouble shifting the directions because I could not add two in all cases because it would go outside of the array bounds, so I put in the if-statement. I'm not sure if there is a way to "wrap" an array in JavaScript without going out of the array bounds. I believe in Python this can be done with the slice notation (double colon syntax). If anyone has a tip for JavaScript, feel free to share.

Collapse
 
johncip profile image
jmc

For wrapping some sum x + y inside of a range n, you can use (x + y) % n (and of course bounds-checking with if works too).

N.B. different languages treat negative mod differently. For JS, in the negative case you'd want something like ((x % n) + n) % n instead of plain %.