100 lines
2.4 KiB
Go
100 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"AOC2022/helper"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
//args := os.Args[1:]
|
|
lines := helper.ReadTextFile("day5/input")
|
|
moves, index := getMoves(lines)
|
|
towers := getTowers(lines[:index])
|
|
part1(towers, moves)
|
|
fmt.Println()
|
|
towers = getTowers(lines[:index])
|
|
part2(towers, moves)
|
|
}
|
|
func part2(towers [9][]string, moves [][3]int) {
|
|
//printTowers(towers)
|
|
for i := len(moves) - 1; i > -1; i-- {
|
|
move := moves[i]
|
|
//fmt.Println(move)
|
|
movedContainer := towers[move[1]-1][len(towers[move[1]-1])-move[0]:]
|
|
towers[move[2]-1] = append(towers[move[2]-1], movedContainer...)
|
|
towers[move[1]-1] = towers[move[1]-1][:len(towers[move[1]-1])-move[0]]
|
|
}
|
|
for _, tower := range towers {
|
|
fmt.Println(tower[len(tower)-1])
|
|
}
|
|
}
|
|
|
|
func part1(towers [9][]string, moves [][3]int) {
|
|
for i := len(moves) - 1; i > -1; i-- {
|
|
move := moves[i]
|
|
for i := 0; i < move[0]; i++ {
|
|
movedContainer := towers[move[1]-1][len(towers[move[1]-1])-1:]
|
|
towers[move[2]-1] = append(towers[move[2]-1], movedContainer...)
|
|
towers[move[1]-1] = towers[move[1]-1][:len(towers[move[1]-1])-1]
|
|
}
|
|
}
|
|
for _, tower := range towers {
|
|
fmt.Println(tower[len(tower)-1])
|
|
}
|
|
}
|
|
|
|
func getTowers(lines []string) (towers [9][]string) {
|
|
replacer := strings.NewReplacer("[", "", "]", "", " ", "")
|
|
for i := len(lines) - 2; i > -1; i-- {
|
|
line := lines[i]
|
|
containers := replacer.Replace(strings.ReplaceAll(strings.ReplaceAll(line, " ", "#"), " [", ""))
|
|
for j := 0; j < len(containers); j++ {
|
|
if containers[j] != '#' {
|
|
towers[j] = append(towers[j], string(rune(containers[j])))
|
|
}
|
|
}
|
|
if line == "" {
|
|
return
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func getMoves(lines []string) ([][3]int, int) {
|
|
moves := [][3]int{}
|
|
replacer := strings.NewReplacer("move ", "", " from ", " ", " to ", " ")
|
|
for i := len(lines) - 1; i > 0; i-- {
|
|
if lines[i] == "" {
|
|
return moves, i
|
|
}
|
|
movesString := strings.Split(replacer.Replace(lines[i]), " ")
|
|
moves = append(moves, [3]int{helper.RemoveError(strconv.Atoi(movesString[0])), helper.RemoveError(strconv.Atoi(movesString[1])), helper.RemoveError(strconv.Atoi(movesString[2]))})
|
|
}
|
|
return moves, 0
|
|
}
|
|
|
|
func printTowers(towers [9][]string) {
|
|
i := 0
|
|
for true {
|
|
printString := ""
|
|
for _, tower := range towers {
|
|
if len(tower) > i {
|
|
printString += tower[i]
|
|
} else {
|
|
printString += " "
|
|
}
|
|
}
|
|
fmt.Println(printString)
|
|
if printString == " " {
|
|
return
|
|
}
|
|
i++
|
|
}
|
|
}
|
|
|
|
func towerLine(r rune) bool {
|
|
return r == '[' || r == ']'
|
|
}
|