Skip to content

Instantly share code, notes, and snippets.

@saidaspen
Created December 14, 2022 06:00
Show Gist options
  • Save saidaspen/b2fddd2459e00efefd382f43119c04de to your computer and use it in GitHub Desktop.
Save saidaspen/b2fddd2459e00efefd382f43119c04de to your computer and use it in GitHub Desktop.
Advent of Code 2022 14
import se.saidaspen.aoc.util.*
import kotlin.math.sign
fun main() = Dayxx.run()
object Dayxx : Day(2022, 14) {
override fun part1() : Any {
// input = "498,4 -> 498,6 -> 496,6\n" +
// "503,4 -> 502,4 -> 502,9 -> 494,9"
// println(input)
var map = mutableMapOf<P<Int, Int>, Char>()
var source = P(500,0)
var lines = input.lines().flatMap {
var splits = it.split(" -> ")
splits.windowed(2)
.map { l -> positives(l.joinToString(" ")) }
.map { i -> P(Point(i[0], i[1]), Point(i[2], i[3])) }.toList()
}
var linesPoints = lines.flatMap { it.first.lineTo(it.second) }
linesPoints.forEach { map[it] = '#' }
var maxY = linesPoints.map { it.second }.max()
var currSand = source
var cnt = 0
while(true) {
if (currSand.second >= maxY) {
break
}
if (!map.containsKey(currSand + Point(0, 1))) {
currSand += Point(0, 1)
} else if (!map.containsKey(currSand + Point(-1, 1))) {
currSand += Point(-1, 1)
} else if (!map.containsKey(currSand + Point(1, 1))) {
currSand += Point(1, 1)
} else {
cnt += 1
map[currSand] = 'o'
currSand = source
}
}
return cnt
}
override fun part2(): Any {
// input = "498,4 -> 498,6 -> 496,6\n" +
// "503,4 -> 502,4 -> 502,9 -> 494,9"
println(input)
var map = mutableMapOf<P<Int, Int>, Char>()
var source = P(500,0)
var lines = input.lines().flatMap {
var splits = it.split(" -> ")
splits.windowed(2)
.map { l -> positives(l.joinToString(" ")) }
.map { i -> P(Point(i[0], i[1]), Point(i[2], i[3])) }.toList()
}
var linesPoints = lines.flatMap { it.first.lineTo(it.second) }
linesPoints.forEach { map[it] = '#' }
var maxY = linesPoints.map { it.second }.max()
var floor = maxY + 2
var currSand = source
var moved = 0
var cnt = 0
while(true) {
if (currSand == source
&& map.containsKey(currSand + Point(0, 1))
&& map.containsKey(currSand + Point(1, 1))
&& map.containsKey(currSand + Point(-1, 1))
) {
break
}
if (!map.containsKey(currSand + Point(0, 1)) && currSand.second + 1 < floor) {
currSand += Point(0, 1)
moved += 1
} else if (!map.containsKey(currSand + Point(-1, 1)) && currSand.second + 1 < floor) {
currSand += Point(-1, 1)
moved += 1
} else if (!map.containsKey(currSand + Point(1, 1)) && currSand.second + 1 < floor) {
currSand += Point(1, 1)
moved += 1
} else {
cnt += 1
map[currSand] = 'o'
currSand = source
}
}
return cnt +1
}
}
private fun Point.lineTo(other: Point): MutableList<Point> {
var step = (other - this).sign()
var line = mutableListOf<Point>()
var curr = this
while (curr != other) {
line.add(curr)
curr += step
}
line.add(curr)
return line
}
private fun Point.sign(): Point {
return Point(this.x.sign, this.y.sign)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment