This page covers all the solutions I wrote for Advent of Code 2022 problems; they are all in Go and should be self-contained, expecting the input to be in 'input'. Occasionally I do some input preprocessing; I try to note it in the file if possible.
Syntax highlighting courtesy of codehost.
2022 Day 1a
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
f, _ := os.Open("input")
s := bufio.NewScanner(f)
max := 0
cur := 0
for s.Scan() {
if s.Text() == "" {
if cur > max {
max = cur
}
cur = 0
} else {
i, _ := strconv.Atoi(s.Text())
cur += i
}
}
fmt.Println(max)
}
2022 Day 1b
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
)
func main() {
f, _ := os.Open("input")
s := bufio.NewScanner(f)
elves := []int{}
cur := 0
for s.Scan() {
if s.Text() == "" {
elves = append(elves, cur)
cur = 0
} else {
i, _ := strconv.Atoi(s.Text())
cur += i
}
}
sort.Ints(elves)
l := len(elves)
fmt.Println(elves[l-1]+elves[l-2]+elves[l-3])
}
2022 Day 2a
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type hand int64
const (
unknown hand = 0
rock hand = 1
paper hand = 2
scissors hand = 3
)
func main() {
f, _ := os.Open("input")
s := bufio.NewScanner(f)
score := int64(0)
for s.Scan() {
hands := strings.Split(s.Text(), " ")
elf := unknown
switch hands[0] {
case "A":
elf = rock
case "B":
elf = paper
case "C":
elf = scissors
}
you := unknown
switch hands[1] {
case "X":
you = rock
case "Y":
you = paper
case "Z":
you = scissors
}
score += int64(you)
if elf == you {
score += 3
} else if (elf == rock && you == paper) || (elf == paper && you == scissors) || (elf == scissors && you == rock) {
score += 6
}
}
fmt.Println(score)
}2022 Day 2b
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type hand int64
const (
unknown hand = 0
rock hand = 1
paper hand = 2
scissors hand = 3
)
type result int64
const (
noresult result = -1
lose result = 0
draw result = 3
win result = 6
)
func main() {
f, _ := os.Open("input")
s := bufio.NewScanner(f)
score := int64(0)
for s.Scan() {
hands := strings.Split(s.Text(), " ")
elf := unknown
switch hands[0] {
case "A":
elf = rock
case "B":
elf = paper
case "C":
elf = scissors
}
result := noresult
switch hands[1] {
case "X":
result = lose
case "Y":
result = draw
case "Z":
result = win
}
score += int64(result)
you := unknown
if result == draw {
you = elf
} else if result == lose {
switch elf {
case rock:
you = scissors
case paper:
you = rock
case scissors:
you = paper
}
} else {
switch elf {
case rock:
you = paper
case paper:
you = scissors
case scissors:
you = rock
}
}
score += int64(you)
}
fmt.Println(score)
}