Skip to content

Instantly share code, notes, and snippets.

@bartoszm
Created December 13, 2021 08:06
Show Gist options
  • Save bartoszm/c26b66461b4eba4f7e39c924e0ea68bd to your computer and use it in GitHub Desktop.
Save bartoszm/c26b66461b4eba4f7e39c924e0ea68bd to your computer and use it in GitHub Desktop.
Day 13 part 1+2 (main solves 2)
abstract class Fold(val line: Int) {
abstract fun transform(p: Pair<Int, Int>): Pair<Int, Int>
}
class FoldX(line: Int) : Fold(line) {
override fun transform(p: Pair<Int, Int>): Pair<Int, Int> {
val x = p.first
val d = line - x
return if(x > line) Pair(x + d*2, p.second) else p
}
override fun toString() = "Y ${line}"
}
class FoldY(line: Int) : Fold(line) {
override fun transform(p: Pair<Int, Int>): Pair<Int, Int> {
val y = p.second
val d = line - y
return if(y > line) Pair(p.first, y + d*2) else p
}
override fun toString() = "X ${line}"
}
data class Input(val points: List<Pair<Int,Int>>, val folds: List<Fold>)
fun parse(lines: List<String>) : Input {
fun point(s: String): Pair<Int, Int> = s.split(",").map { it.toInt() }.toPair()
fun fold(s: String): Fold {
val f = s.split("\\s+".toRegex()).last()
val parts = f.split("=")
return if(parts[0] == "y") {
FoldY(parts[1].toInt())
} else {
FoldX(parts[1].toInt())
}
}
val points = lines.takeWhile { it.isNotBlank() }
.map { point(it) }
val folds = lines.dropWhile { it.isNotBlank() }.drop(1)
.map { fold(it) }
return Input(points, folds)
}
object Day13_Part1 {
fun solve(input: Input) : Int {
val s = input.points
val fold = input.folds[0]
val t = s.map { fold.transform(it) }.distinct()
println(t)
return t.size
}
}
object Day13_Part2 {
fun solve(input: Input): List<String> {
var data = input.points
input.folds.forEach { f ->
data = data.map { f.transform(it) }.distinct()
}
val x = data.groupBy { it.first }.toSortedMap().values
val result = x.map { l ->
val s = l.map { it.second }.toSet()
(0..5).map { if(it in s) '#' else '.' }.toTypedArray()
}.toTypedArray()
return result.transpose().map {
it.toList().chunked(4).map { c -> c.joinToString("") }.joinToString(" " )
}
}
}
private inline fun <reified T> Array<Array<T>>.transpose(): Array<Array<T>> {
val rows = this.size
val cols = this[0].size
val result = (0 until cols).map { c ->
(0 until rows).map { r -> this[r][c] }.toTypedArray()
}.toTypedArray()
return result
}
fun main(args: Array<String>) {
val input = parse(Files.readAllLines(Path.of(args[0])))
println(input)
Day13_Part2.solve(input).forEach {
println(it)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment