solutions for the Advent of Code 2023
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.0 KiB

package main
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
"unicode"
)
func linevalue(digits []rune) int {
str := fmt.Sprintf("%c%c", digits[0], digits[len(digits)-1])
value, _ := strconv.Atoi(str)
return value
}
func finddigits(line string) []rune {
d := make([]rune, 0, 7)
for len(line) > 0 {
if unicode.IsDigit(rune(line[0])) {
d = append(d, rune(line[0]))
}
line = line[1:]
}
return d
}
func findtextdigits(line string) []rune {
d := make([]rune, 0, 7)
for len(line) > 0 {
if unicode.IsDigit(rune(line[0])) {
d = append(d, rune(line[0]))
}
if strings.HasPrefix(line, "one") {
d = append(d, '1')
line = line[2:]
} else if strings.HasPrefix(line, "two") {
d = append(d, '2')
line = line[2:]
} else if strings.HasPrefix(line, "three") {
d = append(d, '3')
line = line[4:]
} else if strings.HasPrefix(line, "four") {
d = append(d, '4')
line = line[4:] // skip len("four") entirely because no digits start with 'r'
} else if strings.HasPrefix(line, "five") {
d = append(d, '5')
line = line[3:]
} else if strings.HasPrefix(line, "six") {
d = append(d, '6')
line = line[3:] // skip len("six") entirely because no digits start with 'x'
} else if strings.HasPrefix(line, "seven") {
d = append(d, '7')
line = line[4:]
} else if strings.HasPrefix(line, "eight") {
d = append(d, '8')
line = line[4:]
} else if strings.HasPrefix(line, "nine") {
d = append(d, '9')
line = line[3:]
} else {
line = line[1:]
}
}
return d
}
type day01 struct {
}
func (d day01) solve1(r io.Reader) string {
var (
total int
scanner = bufio.NewScanner(r)
)
for scanner.Scan() {
digits := finddigits(scanner.Text())
total += linevalue(digits)
}
return fmt.Sprintf("%d", total)
}
func (d day01) solve2(r io.Reader) (ans string) {
var (
total int
scanner = bufio.NewScanner(r)
)
for scanner.Scan() {
digits := findtextdigits(scanner.Text())
total += linevalue(digits)
}
return fmt.Sprintf("%d", total)
}