r/adventofcode • • Dec 03 '20

SOLUTION MEGATHREAD -🎄- 2020 Day 03 Solutions -🎄-

Advent of Code 2020: Gettin' Crafty With It


--- Day 03: Toboggan Trajectory ---


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 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:04:56, megathread unlocked!

88 Upvotes

1.3k comments sorted by

View all comments

1

u/or9ob Dec 03 '20

Kotlin

object Forest {

    /**
     * Forest is organized as a 2D array where, Y -> 1st dim, X -> 2nd dim.
     * Each spot can be analyzed with [isOccupied] to see if there is a tree there.
     */
    fun parse(data: String): List<List<Char>> =
        data.split("\n")
            .reversed()
            .map { it.toCharArray().toList() }

    fun walkAndCount(forest: List<List<Char>>, stepX: Int, stepY: Int) =
        walkAndCountRecursively(
            currentTreeCount = 0,
            currentX = 0,
            currentY = forest.size -1,
            stepX, stepY, forest
        )

    private fun walkAndCountRecursively(
        currentTreeCount: Int,
        currentX: Int,
        currentY: Int,
        stepX: Int,
        stepY: Int,
        forest: List<List<Char>>
    ): Int {
        val nextGenForest = expandForestIfRequired(currentX, forest)
        val currentSpot = nextGenForest[currentY][currentX]
        val nextTreeCount = currentTreeCount + if (currentSpot.isOccupied()) 1 else 0
        val nextX = currentX + stepX
        val nextY = currentY - stepY

        if (nextY < 0) {
            // we have passed through the end/bottom of the forest
            return nextTreeCount
        }

        return walkAndCountRecursively(
            currentTreeCount = nextTreeCount,
            currentX = nextX,
            currentY = nextY,
            stepX, stepY, nextGenForest
        )
    }

    private fun Char.isOccupied() = this == '#'

    /**
     * Expand the forest, by duplicating it along the X-axis (the 2nd dim) for each Y (row), if we are out of the
     * currently known bounds of the forest (along the X-axis).
     */
    private fun expandForestIfRequired(currentX: Int, forest: List<List<Char>>) =
        if (currentX < forest[0].size) {
            forest
        } else {
            forest.map { it + it }
        }
}
internal class ForestTest {

    private val testInput = """
            ..##.......
            #...#...#..
            .#....#..#.
            ..#.#...#.#
            .#...##..#.
            ..#.##.....
            .#.#.#....#
            .#........#
            #.##...#...
            #...##....#
            .#..#...#.#
        """.trimIndent()

    @Test
    fun `part 1 test`() {
        val forest = Forest.parse(testInput)
        Assertions.assertEquals(7, Forest.walkAndCount(forest, stepX = 3, stepY = 1))
    }

    @Test
    fun `part 1 real`() {
        val data = File("src/test/resources/aoc2020/day3/input.txt").readText()
        val forest = Forest.parse(data)
        Assertions.assertEquals(209, Forest.walkAndCount(forest, stepX = 3, stepY = 1))
    }

    @Test
    fun `part 2 test`() {
        val forest = Forest.parse(testInput)
        Assertions.assertEquals(336, walkMultipleSlopesAndAccumulateTreeCount(forest))
    }

    @Test
    fun `part 2 real`() {
        val data = File("src/test/resources/aoc2020/day3/input.txt").readText()

        val forest = Forest.parse(data)
        Assertions.assertEquals(1574890240, walkMultipleSlopesAndAccumulateTreeCount(forest))
    }

    private fun walkMultipleSlopesAndAccumulateTreeCount(forest: List<List<Char>>) = listOf(
        Pair(1, 1),
        Pair(3, 1),
        Pair(5, 1),
        Pair(7, 1),
        Pair(1, 2),
    ).fold(1) { acc, (stepX, stepY) ->
        acc * Forest.walkAndCount(forest, stepX, stepY)
    }
}

1

u/daggerdragon Dec 03 '20

This code is really hard to read on old.reddit. Could you please edit it using old.reddit's four-spaces formatting instead of new.reddit's triple backticks? Note that if you're using the visual editor, you may have to "Switch to Markdown" to get Reddit to understand the formatting properly.

1

u/or9ob Dec 03 '20

I have the links to GitHub right at the top too.

Sorry I didn’t realize how it renders differently in old Reddit (I use Apollo and new Reddit on web).

0

u/backtickbot Dec 03 '20

Hello, or9ob: code blocks using 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. It's a bit annoying, but then your code blocks are properly formatted for everyone.

An easy way to do this is to use the code-block button in the editor. If it's not working, try switching to the fancy-pants editor and back again.

Comment with formatting fixed for old.reddit.com users

FAQ

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