advent-of-code/aoc2023/day01/main.go

103 lines
1.7 KiB
Go
Raw Normal View History

2023-12-02 18:28:38 -07:00
package main
import (
"bufio"
_ "embed"
"fmt"
"strings"
2023-12-15 15:13:24 -07:00
aoc "go.sour.is/advent-of-code"
2023-12-08 19:09:00 -07:00
)
2023-12-02 18:28:38 -07:00
2023-12-13 08:32:37 -07:00
func main() { aoc.MustResult(aoc.Runner(run)) }
2023-12-08 19:09:00 -07:00
type result struct {
sum int
sum2 int
}
func (r result) String() string {
return fmt.Sprintln("result pt1:", r.sum, "\nresult pt2:", r.sum2)
}
var numbers = []string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
func run(scan *bufio.Scanner) (*result, error) {
result := &result{}
2023-12-02 18:28:38 -07:00
for scan.Scan() {
var first, last int
2023-12-08 19:09:00 -07:00
var first2, last2 int
2023-12-02 18:28:38 -07:00
text := scan.Text()
slice := make([]rune, 5)
for i := range text {
copy(slice, []rune(text[i:]))
switch {
case slice[0] >= '0' && slice[0] <= '9':
2023-12-08 19:09:00 -07:00
if first == 0 {
first = int(slice[0] - '0')
}
if first2 == 0 {
first2 = int(slice[0] - '0')
}
default:
if first2 != 0 {
continue
}
for i, s := range numbers {
if strings.HasPrefix(string(slice), s) {
first2 = i
break
}
}
2023-12-02 18:28:38 -07:00
}
2023-12-08 19:09:00 -07:00
if first != 0 && first2 != 0 {
2023-12-02 18:28:38 -07:00
break
}
}
2023-12-08 19:09:00 -07:00
text = string(aoc.Reverse([]rune(text)))
2023-12-02 18:28:38 -07:00
for i := range text {
copy(slice, []rune(text[i:]))
2023-12-08 19:09:00 -07:00
slice = aoc.Reverse(slice)
2023-12-02 18:28:38 -07:00
switch {
case slice[4] >= '0' && slice[4] <= '9':
2023-12-08 19:09:00 -07:00
if last == 0 {
last = int(slice[4] - '0')
}
if last2 == 0 {
last2 = int(slice[4] - '0')
}
default:
if last2 != 0 {
continue
}
for i, s := range numbers {
if strings.HasSuffix(string(slice), s) {
last2 = i
break
}
}
2023-12-02 18:28:38 -07:00
}
2023-12-08 19:09:00 -07:00
if last != 0 && last2 != 0 {
2023-12-02 18:28:38 -07:00
break
}
}
2023-12-08 19:09:00 -07:00
result.sum += first*10 + last
result.sum2 += first2*10 + last2
2023-12-02 18:28:38 -07:00
}
if err := scan.Err(); err != nil {
2023-12-08 19:09:00 -07:00
return nil, err
2023-12-02 18:28:38 -07:00
}
2023-12-08 19:09:00 -07:00
return result, nil
2023-12-02 18:28:38 -07:00
}