LONG READ: My 2023 Advent Of Code Solutions
Advent of code is a fun way to practice your problem solving skills, get some coding practice, or even picking up a new language. I am planning on solving this years problems in Go, so I can learn more about the language
Day 1
Part 1
The first part of day 1 of AoC basically consists on the following. Given a file input like this one:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
Find the first and last number of each line, in this case 12
, 38
, 15
, and 77
. Add them together to get the answer of the first part of the challenge, in this case 142
.
This was my solution written in Go
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
)
func main() {
content, err := os.ReadFile("in.txt")
if err != nil {
log.Fatal(err)
}
str_content := string(content)
split_string := strings.Split(str_content, "\n")
sum := 0
for _, s := range split_string {
nums := []int{}
for _, char := range s {
num, err := strconv.Atoi(string(char))
if err == nil {
nums = append(nums, num)
}
}
nums_len := len(nums)
sum += nums[0] * 10
sum += nums[nums_len-1]
}
f, _ := os.Create("out.txt")
f.WriteString(fmt.Sprint(sum))
f.Close()
}
This code takes in a file in.txt
, finds all the numbers in each line, and finally adds the first and last one as a single number to a global sum. It then writes this sum to an out.txt
file, which I can copy paste into AoC
Yay! First part done.
Part 2
Now for part two. We need to also parse the numbers that are written as text, one
is 1
, two
is 2
, and so on. My first thought was to do a simple search and r