DEV Community

Cover image for Bathroom Security
Robert Mion
Robert Mion

Posted on

Bathroom Security

Advent of Code 2016 Day 2

Part 1

  1. Setting up the data structures
  2. A double-reduce()r to solve the puzzle

Setting up the data structures

My map for traversing the array based on the direction:

{
  'U': [-1,0],
  'R': [0,1],
  'D': [1,0],
  'L': [0,-1]
}
Enter fullscreen mode Exit fullscreen mode

My data structure for the keypad:

[
  [1,2,3],
  [4,5,6],
  [7,8,9]
]
Enter fullscreen mode Exit fullscreen mode

5 is at [1,1]

A double-reduce()r to solve the puzzle

The iteration portion of my algorithm in pseudocode:

For each line from the input
  Accumulate a code - starting as an empty string
  For each character in the line
    Accumulate a 2-element array of coordinates
    If the next location is a valid cell
      Return the coordinate of the next location
    Else
      Return the coordinate of the current location
  Add the value at the final cell to the string
Enter fullscreen mode Exit fullscreen mode

The iteration portion of my algorithm in JavaScript:

input.reduce(
  (code, line) => {
    key = line.reduce(
      (coords, path) => 
        keypad[coords[0] + map[path][0]] &&
        keypad[coords[0] + map[path][0]][coords[1] + map[path][1]]
        ? [ coords[0] + map[path][0],
            coords[1] + map[path][1] ]
        : coords,
        key.slice()
    )
    return code += keypad[key[0]][key[1]]
  }, ""
)
Enter fullscreen mode Exit fullscreen mode

Part 1: solved!

Part 2

Three updates and done!

Update 1: Expand the data structure

My data structure for the keypad:

[
  [0,  0,  1,  0,  0],
  [0,  2,  3,  4,  0],
  [5,  6,  7,  8,  9],
  [0, 'A','B','C', 0],
  [0,  0, 'D', 0,  0]
]
Enter fullscreen mode Exit fullscreen mode

Update 2: Adjust the starting location

5 is at [2,0] now

Update 3: Add a clause to the array-cell-checking condition - checking for a value of 0

The iteration portion of my algorithm in JavaScript:

input.reduce(
  (code, line) => {
    key = line.reduce(
      (coords, path) => 
        keypad[coords[0] + map[path][0]] &&
        keypad[coords[0] + map[path][0]][coords[1] + map[path][1]] &&
        keypad[coords[0] + map[path][0]][coords[1] + map[path][1]] !== 0
        ? [ coords[0] + map[path][0],
            coords[1] + map[path][1] ]
        : coords,
        key.slice()
    )
    return code += keypad[key[0]][key[1]]
  }, ""
)
Enter fullscreen mode Exit fullscreen mode

Part 2: solved!

I did it!!

  • I solved both parts!
  • Using nested reduce()s again!
  • And using my tried and true array traversing techniques!

Bring on Day 1...and hopefully a strong end to an overall fun and relatively fast-solved year!

Top comments (0)