Kotlin Day 3

Perfectly Spherical Houses in a Vacuum

From Advent of Code 2015, Day 3

Model

We model a position object as a simple Int .

Given an instruction char and current position acc, we can figure out the next position based on the direction it takes.

We lower the dimension to use 1-D coordinates for 2-D layout, hoping it produces quicker coding and simpler understanding for the problem.

Part 1

Given a list of direction instructions, find out total number of places visited.

We scan all the instructions to get snapshots of future positions, among them we can find the distinct set and the count.

If you wonder why we are making a function accepting additional acc here, please checkout Day 1 - Part 2 for gathering the intermediate result.

Part 2

Given two persons taking turns processing same list of instructions, find out total number of places visited.

We can split the list into two lists with evens in one and odds in another.

Each list goes through exactly same process as in part1. In order to get the joint effort from two groups here, we resort to flatMap to put two streams back into one stream of data.

In the real time, flatMap is designed to join multiple streams into one stream according to element's chronological order. This behavior interestingly mimics the human collaboration pattern very closely.

Highlights

  • How sometimes lower dimension is more cost-effective?
  • How to distribute work and gather result from each unit?

Now, ready for the next day? Day 2 — I was Told There Would be No Math

Or, revisit the previous day? Day 4 — The Ideal Stocking Stuffer

For Complete source code, please visit AoC 2015 Kotlin.

Front-end Engineer