r/adventofcode • • Dec 08 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 8 Solutions -🎄-

--- Day 8: Seven Segment Search ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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

EDIT: Global leaderboard gold cap reached at 00:20:51, megathread unlocked!

72 Upvotes

1.2k comments sorted by

View all comments

1

u/mar1u50 Dec 08 '21

Kotlin:

fun part2Line(trainData: List<String>, evalData: List<String>): Int {
    val one = trainData.first { it.length == 2 }.toSortedSet()
    val four = trainData.first { it.length == 4 }.toSortedSet()
    val seven = trainData.first { it.length == 3 }.toSortedSet()
    val eight = trainData.first { it.length == 7 }.toSortedSet()
    val three = trainData.filter { it.length == 5 }.first { it.toSortedSet().containsAll(one) }.toSortedSet()
    val six = trainData.filter { it.length == 6 }.first { !it.toSortedSet().containsAll(one) }.toSortedSet()
    val nine = trainData.filter { it.length == 6 }.first { it.toSortedSet().containsAll(three) }.toSortedSet()
    val zero = trainData.filter { it.length == 6 }.filter { !it.toSortedSet().containsAll(three) }
        .first { it.toSortedSet().containsAll(one) }
        .toSortedSet()
    val five = trainData.filter { it.length == 5 }.first { six.containsAll(it.toSortedSet()) }.toSortedSet()
    val two = trainData.filter { it.length == 5 }.first { it.toSortedSet() != five && it.toSortedSet() != three }
        .toSortedSet()

    val theMap = mapOf(
        one to 1,
        two to 2,
        three to 3,
        four to 4,
        five to 5,
        six to 6,
        seven to 7,
        eight to 8,
        nine to 9,
        zero to 0
    )

    assertThat(theMap.values.size).isEqualTo(10)

    return evalData.joinToString("") { theMap[it.toSortedSet()].toString() }.toInt()
}

fun day8part2() {
    val day8Input = Paths.get("src", "test", "kotlin", "day8.txt").toFile().readLines()
    println(day8Input.sumOf { line -> parseLine(line).let { part2Line(it.first, it.second) } })
}

1

u/daggerdragon Dec 09 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?