unify addSand implementations

This commit is contained in:
David 2022-12-18 21:18:45 -05:00
parent 30cb6c5cd6
commit a97522988a

View File

@ -87,11 +87,16 @@ func printCave(cave map[coord]int, xmin, xmax, depth int, floor bool) {
}
// return value is false if sand reached max depth
func addSandVoid(cave map[coord]int, depth int) bool {
func addSand(cave map[coord]int, depth int, floor bool) bool {
x := 500
y := 0
for {
if y > depth {
if floor {
// made it to the floor, come to rest
cave[coord{x: x, y: y}] = 2
return true
}
return false
}
if _, blocked := cave[coord{x: x, y: y + 1}]; !blocked {
@ -108,37 +113,6 @@ func addSandVoid(cave map[coord]int, depth int) bool {
x += 1
continue
}
// blocked in all directions, come to rest
cave[coord{x: x, y: y}] = 2
return true
}
}
// return value is false if sand reached max depth
func addSandFloor(cave map[coord]int, depth int) bool {
x := 500
y := 0
for {
if y > depth {
// made it to the floor, come to rest
cave[coord{x: x, y: y}] = 2
return true
}
if _, blocked := cave[coord{x: x, y: y + 1}]; !blocked {
y += 1
continue
}
if _, blocked := cave[coord{x: x - 1, y: y + 1}]; !blocked {
y += 1
x -= 1
continue
}
if _, blocked := cave[coord{x: x + 1, y: y + 1}]; !blocked {
y += 1
x += 1
continue
}
// filled the cavern, return false
if y == 0 {
cave[coord{x: x, y: y}] = 2
@ -187,7 +161,7 @@ func partOne() {
}
}
}
for addSandVoid(cave, depth) {
for addSand(cave, depth, false) {
}
printCave(cave, minx-1, maxx+1, depth+1, false)
score := 0
@ -236,7 +210,7 @@ func partTwo() {
}
}
}
for addSandFloor(cave, depth) {
for addSand(cave, depth, true) {
}
printCave(cave, minx-1, maxx+1, depth+1, true)
score := 0