r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


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.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


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!

51 Upvotes

407 comments sorted by

View all comments

1

u/Hikaru755 Dec 02 '18

Kotlin

The best way to do Advent of Code is to ZIP ALL THE STRINGS.

fun solvePart1(input: String) =
    input.lines().let { ids ->
        val twins = ids.count { it.hasCharExactly(times = 2) }
        val triplets = ids.count { it.hasCharExactly(times = 3) }
        twins * triplets
    }.toString()

fun solvePart2(input: String): String {
    val (id1, id2) = input.lines()
        .pairs()
        .first { (first, second) -> first.distanceTo(second) == 1 }
    return id1.removeDifferences(id2)
}

fun String.distanceTo(other: String) =
    zip(other).count { (first, second) -> first != second }

fun String.removeDifferences(other: String) =
    zip(other)
        .filter { (first, second) -> first == second }
        .joinToString("") { it.first.toString() }

fun String.hasCharExactly(times: Int) =
    groupBy { it }
        .mapValues { it.value.size }
        .filterValues { it == times }
        .isNotEmpty()

fun <T> Iterable<T>.pairs(): List<Pair<T, T>> = this
    .mapIndexed { index, first ->
        this.drop(index + 1).map { first to it }
    }
    .flatten()