Last active
August 20, 2021 11:24
-
-
Save StylianosGakis/d57ada1e7bb6766430a1c237b6d5e43a to your computer and use it in GitHub Desktop.
Kotlin solution for day 3 of advent of code 2020. https://adventofcode.com/2020/day/3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package day03 | |
import java.io.File | |
@JvmInline | |
private value class Map(val map: List<List<Square>>) { | |
fun countNumberOfTreesForStep(step: Coordinate): Int { | |
return generateSequence( | |
seed = Coordinate(0, 0), | |
nextFunction = { coordinate: Coordinate -> | |
val nextCoordinate = coordinate + step | |
if (nextCoordinate.y > map.size) return@generateSequence null | |
nextCoordinate | |
} | |
).count { coordinate -> | |
this.getSquareAtCoordinateOrNull(coordinate) == Square.Tree | |
} | |
} | |
private fun getSquareAtCoordinateOrNull(coordinate: Coordinate): Square? { | |
return map.getOrNull(coordinate.y)?.let { row -> | |
row.getOrNull((coordinate.x % row.size)) | |
} | |
} | |
} | |
private data class Coordinate(val x: Int, val y: Int) { | |
operator fun plus(other: Coordinate): Coordinate { | |
return Coordinate(x + other.x, y + other.y) | |
} | |
} | |
private enum class Square { | |
Empty, | |
Tree; | |
companion object { | |
fun fromChar(char: Char): Square { | |
return when (char) { | |
'#' -> Tree | |
'.' -> Empty | |
else -> throw IllegalArgumentException() | |
} | |
} | |
} | |
} | |
fun main() { | |
val inputMap = File("src/main/kotlin/day03/input.txt") | |
.readLines() | |
.filter(String::isNotEmpty) | |
.map { line: String -> | |
line.map(Square::fromChar) | |
} | |
.let(::Map) | |
// Part 1 | |
inputMap.countNumberOfTreesForStep(Coordinate(3, 1)).also(::println) | |
// Part 2 | |
listOf( | |
Coordinate(1, 1), | |
Coordinate(3, 1), | |
Coordinate(5, 1), | |
Coordinate(7, 1), | |
Coordinate(1, 2), | |
).map { coordinate: Coordinate -> | |
inputMap.countNumberOfTreesForStep(coordinate) | |
}.fold(1L) { accumulatedScore: Long, score: Int -> | |
accumulatedScore * score | |
}.also(::println) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment