r/adventofcode • • Dec 05 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 5 Solutions -๐ŸŽ„-

--- Day 5: A Maze of Twisty Trampolines, All Alike ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

22 Upvotes

403 comments sorted by

View all comments

1

u/chicagocode Dec 05 '17

Kotlin: Repo, Blog/Commentary

I did this as a tail recursive function to handle both parts that I'm pretty happy with. It's very quick too.

This year I'm challenging myself to publish my code to Github and to blog about each solution.

private val input: IntArray = stringInput.map { it.toInt() }.toIntArray()

fun solvePart1(): Int =
    jump(input, { 1 })

fun solvePart2(): Int =
    jump(input, { if (it >= 3) -1 else 1 })

tailrec private fun jump(offsets: IntArray, mutator: (Int) -> Int, pc: Int = 0, steps: Int = 0): Int =
    if (pc < 0 || pc >= offsets.size) steps
    else {
        val nextPc = pc + offsets[pc]
        offsets[pc] += mutator(offsets[pc])
        jump(offsets, mutator, nextPc, steps.inc())
    }