First day

This commit is contained in:
g3po 2023-12-01 16:46:08 +01:00
parent 33b14154cf
commit aff92c4624
5 changed files with 1084 additions and 10 deletions

1000
cmd/O1/input.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,15 +2,30 @@ package main
import ( import (
"fmt" "fmt"
"log"
"os" utils "git.anthonygueguen.fr/g3po/aoc2023/internal"
day01 "git.anthonygueguen.fr/g3po/aoc2023/internal/01"
) )
func main() { func main() {
fmt.Println("Opening file...") content := utils.Init()
file, err := os.OpenFile("./input.txt", os.O_RDONLY, 0644)
if err != nil { fmt.Println("Part 1")
log.Fatal(err) digits := day01.GetDigits(content)
sum := 0
for _, v := range digits {
sum += v
} }
defer file.Close()
fmt.Printf("Result: %d\n", sum)
fmt.Println("Part 2")
content = day01.WordToNum(content)
digits = day01.GetDigits(content)
sum = 0
for _, v := range digits {
sum += v
}
fmt.Printf("Result: %d", sum)
} }

2
go.mod
View File

@ -1,3 +1,3 @@
module 01 module git.anthonygueguen.fr/g3po/aoc2023
go 1.21.4 go 1.21.4

56
internal/01/01.go Normal file
View File

@ -0,0 +1,56 @@
package day01
import (
"strconv"
"strings"
"unicode"
utils "git.anthonygueguen.fr/g3po/aoc2023/internal"
)
var wordNum = map[string]string{
"one": "o1e",
"two": "t2o",
"three": "t3e",
"four": "f4r",
"five": "f5e",
"six": "s6x",
"seven": "s7n",
"eight": "e8t",
"nine": "n9e",
}
func GetDigits(content []string) []int {
var digits []int
for _, line := range content {
d_str := ""
for _, c := range line {
if unicode.IsDigit(c) {
d_str = d_str + string(c)
break
}
}
for i := len(line) - 1; i >= 0; i-- {
if unicode.IsDigit(rune(line[i])) {
d_str = d_str + string(line[i])
break
}
}
utils.Must[int](strconv.Atoi(d_str))
digits = append(digits, utils.Must[int](strconv.Atoi(d_str)))
}
return digits
}
func WordToNum(content []string) []string {
var rContent []string
for _, line := range content {
str := line
for k, v := range wordNum {
str = strings.ReplaceAll(str, k, v)
}
rContent = append(rContent, str)
}
return rContent
}

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"strings"
) )
func Must[T any](obj T, err error) T { func Must[T any](obj T, err error) T {
@ -13,7 +14,9 @@ func Must[T any](obj T, err error) T {
return obj return obj
} }
func Init() []byte { func Init() []string {
fmt.Println("Opening file...") fmt.Println("Opening file...")
return Must(os.ReadFile("./input.txt")) bytes := Must(os.ReadFile("./input.txt"))
content := strings.Split(string(bytes), "\n")
return content[:len(content)-1]
} }