jlelse
/
aoc21
Archived
1
Fork 0
This repository has been archived on 2024-01-02. You can view files and clone it, but cannot push or open issues or pull requests.
aoc21/10/main.go

89 lines
2.5 KiB
Go

package main
import (
"log"
"os"
"sort"
"strings"
"github.com/thoas/go-funk"
)
func main() {
inputBytes, _ := os.ReadFile("input.txt")
input := strings.Split(string(inputBytes), "\n")
log.Println("Puzzle 1:", puzzle1(input))
log.Println("Puzzle 2:", puzzle2(input))
}
func puzzle1(input []string) int {
correctClosingChar := map[rune]rune{'(': ')', '[': ']', '{': '}', '<': '>'}
points := map[rune]int{')': 3, ']': 57, '}': 1197, '>': 25137}
count := 0
for _, line := range input {
stack := []rune{}
// Check every character in the line
for _, char := range line {
// If the character is a opening bracket, push it to the stack
if char == '(' || char == '[' || char == '{' || char == '<' {
stack = append(stack, char)
continue
}
// If the character is a closing bracket, pop the stack
if char == ')' || char == ']' || char == '}' || char == '>' {
// Check if the char is the correct one
topOnStack := stack[len(stack)-1]
if char != correctClosingChar[topOnStack] {
// It isn't, so add the points of the closing char to the count
count += points[char]
break
}
// It is, so pop the stack
stack = stack[:len(stack)-1]
}
}
}
return count
}
func puzzle2(input []string) int {
correctClosingChar := map[rune]rune{'(': ')', '[': ']', '{': '}', '<': '>'}
points := map[rune]int{')': 1, ']': 2, '}': 3, '>': 4}
scores := []int{}
forlines:
for _, line := range input {
stack := []rune{}
score := 0
// Check every character in the line
for _, char := range line {
// If the character is a opening bracket, push it to the stack
if char == '(' || char == '[' || char == '{' || char == '<' {
stack = append(stack, char)
continue
}
// If the character is a closing bracket, pop the stack
if char == ')' || char == ']' || char == '}' || char == '>' {
// Check if the char is the correct one
topOnStack := stack[len(stack)-1]
if char != correctClosingChar[topOnStack] {
// It isn't, discard the line and continue with the next one
continue forlines
}
// It is, so pop the stack
stack = stack[:len(stack)-1]
}
}
// Find correct closing brackets and add their points to the score
reversedStack := funk.Reverse(stack).([]rune)
for _, char := range reversedStack {
score = score*5 + points[correctClosingChar[char]]
}
// Add the score of the line to the scores
scores = append(scores, score)
}
// Return the middle one from the scores
sort.Ints(scores)
return scores[len(scores)/2]
}