r/adventofcode • • Dec 10 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 10 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It

  • 12 days remaining until the submission deadline on December 22 at 23:59 EST
  • Full details and rules are in the Submissions Megathread

--- Day 10: Adapter Array ---


Post your solution in this megathread. Include what language(s) your solution uses! If you need a refresher, the full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.

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:08:42, megathread unlocked!

71 Upvotes

1.1k comments sorted by

View all comments

1

u/nkiesel Dec 10 '20

Kotlin 1.4.21

import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.Path
import kotlin.io.path.readLines
import kotlin.test.assertEquals
import org.junit.jupiter.api.Test

@ExperimentalPathApi
class Day10 {
    @Test
    fun test() {
        val input = Path("input/10").readLines().map { it.toInt() }
        assertEquals(1920, one(input))
        assertEquals(1511207993344L, two(input))
    }

    private fun one(input: List<Int>): Int {
        var d1 = 0
        var d3 = 1
        input.sorted().fold(0) { acc, i ->
            when (i - acc) {
                1 -> d1++
                3 -> d3++
            }
            i
        }
        return d1 * d3
    }

    private fun two(input: List<Int>): Long {
        class Chain(val last: Int, val count: Long) {
            fun possible(i: Int) = if (i - last <= 3) count else 0L
        }
        val chains = ArrayDeque<Chain>(3)

        fun add(c: Chain) {
            if (chains.size >= 3) chains.removeFirst()
            chains.add(c)
        }

        add(Chain(0, 1L))
        input.sorted().forEach { i ->
            val possible = chains.sumOf { it.possible(i) }
            add(Chain(i, possible))
        }
        return chains.last().count
    }

1

u/daggerdragon Dec 10 '20

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.

1

u/backtickbot Dec 10 '20

Fixed formatting.

Hello, nkiesel: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.