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.

99 lines
2.0 KiB

12 months ago
package main
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
12 months ago
"unicode"
)
func linevalue(digits []rune) int {
str := fmt.Sprintf("%c%c", digits[0], digits[len(digits)-1])
value, _ := strconv.Atoi(str)
return value
12 months ago
}
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
12 months ago
}
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]))
}
12 months ago
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:]
}
12 months ago
}
return d
12 months ago
}
type day01 struct {
12 months ago
}
func (d day01) solve1(r io.Reader) string {
12 months ago
var (
total int
scanner = bufio.NewScanner(r)
12 months ago
)
for scanner.Scan() {
digits := finddigits(scanner.Text())
total += linevalue(digits)
}
return fmt.Sprintf("%d", total)
}
12 months ago
func (d day01) solve2(r io.Reader) (ans string) {
var (
total int
scanner = bufio.NewScanner(r)
)
12 months ago
for scanner.Scan() {
digits := findtextdigits(scanner.Text())
total += linevalue(digits)
12 months ago
}
return fmt.Sprintf("%d", total)
12 months ago
}