Created
December 25, 2021 11:48
-
-
Save almendar/e34f44191a2178ab2bf7309df09a48fd to your computer and use it in GitHub Desktop.
This file contains hidden or 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 main | |
import ( | |
"io/ioutil" | |
"log" | |
"strings" | |
) | |
type Seafloor [][]rune | |
func (sf Seafloor) at(x, y int) string { | |
return string(sf[y][x]) | |
} | |
func (sf Seafloor) String() string { | |
sb := strings.Builder{} | |
for _, v := range sf { | |
sb.WriteString(string(v)) | |
sb.WriteString("\n") | |
} | |
return sb.String() | |
} | |
func readInput(input string) Seafloor { | |
bytes, err := ioutil.ReadFile(input) | |
if err != nil { | |
log.Fatal(err) | |
} | |
seaFloor := make(Seafloor, 0) | |
for _, v := range strings.Split(string(bytes), "\n") { | |
seaFloor = append(seaFloor, []rune(v)) | |
} | |
return seaFloor | |
} | |
type coords struct{ x, y int } | |
func main() { | |
in := readInput("input.txt") | |
// fmt.Printf("%v", in) | |
N := len(in) | |
M := len(in[0]) | |
it := 1 | |
for { | |
moved := false | |
to_delete := make([]coords, 0) | |
to_add := make(map[coords]rune) | |
for y := range in { | |
for x := range in[y] { | |
t := in.at(x, y) | |
if t == ">" { | |
yn := y | |
xn := x + 1 | |
if xn >= M { | |
xn = 0 | |
} | |
if in.at(xn, yn) == "." { | |
moved = true | |
to_delete = append(to_delete, coords{x, y}) | |
to_add[coords{xn, yn}] = '>' | |
} | |
} | |
} | |
} | |
for _, c := range to_delete { | |
in[c.y][c.x] = '.' | |
} | |
for c, v := range to_add { | |
in[c.y][c.x] = v | |
} | |
to_delete = make([]coords, 0) | |
to_add = make(map[coords]rune) | |
for y := range in { | |
for x := range in[y] { | |
t := in.at(x, y) | |
if t == "v" { | |
yn := y + 1 | |
xn := x | |
if yn >= N { | |
yn = 0 | |
} | |
if in.at(xn, yn) == "." { | |
moved = true | |
to_delete = append(to_delete, coords{x, y}) | |
to_add[coords{xn, yn}] = 'v' | |
} | |
} | |
} | |
} | |
for _, c := range to_delete { | |
in[c.y][c.x] = '.' | |
} | |
for c, v := range to_add { | |
in[c.y][c.x] = v | |
} | |
if !moved { | |
break | |
} | |
it += 1 | |
} | |
println(it) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment