Kotlin Day 1

Not Quite Lisp

Fang Jin
1 min readAug 30, 2020

From Advent of Code 2015, Day 1

()()(()()()(()()((()((()))((()((((()()((((((
)()(()()()(()()((()((()))((()((((()()((((())
)()((((())(((((((()(((((((((()(((())(()()(()
((()()(()(())(()((((()((()()()((((())(((((((
)(()(((()())(()((((()))())(())(()(()()))))))

Model

Map each character as an integer value.

In order to convert a list of string (or char) into the models, we can simply apply the map as shown in Day 0.

Part 1

Starting from position 0, find out the latest position after a series of up and down operations.

Part 2

Given a position -1, find out how many operations you need to take to get there.

Find a match from a sequence

The problem is a bit different from the previous sum, because we need to keep track of the intermediate result for each step so to know if we reach the destination.

You might already notice asSequence in the above. It's here for saving us going over the entire list. Right after we have a match via indexOf, it'll stop. Bingo! Saving us to write a while here.

You might wonder why we can not use sum after asSequence. The short answer is that sum produces Int instead of sequence , which prevents us taking advantage of sequence of deferring mechanism.

Highlights

  • How to use number to model the stream of data?
  • How to return from the loop right away?

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

Or, revisit the previous day? Day 0 — Dusk till Dawn

For Complete source code, please visit AoC 2015 Kotlin.

--

--

Fang Jin
Fang Jin

Written by Fang Jin

Front-end Engineer, book author of “Designing React Hooks the Right Way” and "Think in Recursion"

No responses yet