Skip to content

Instantly share code, notes, and snippets.

@PatrickVienne
Created December 1, 2023 07:22
Show Gist options
  • Save PatrickVienne/1cf5c45ba15e08814591a6d2c7e26a95 to your computer and use it in GitHub Desktop.
Save PatrickVienne/1cf5c45ba15e08814591a6d2c7e26a95 to your computer and use it in GitHub Desktop.
AOC2023-D1
package d1
import (
"bufio"
"io"
"regexp"
"unicode/utf8"
)
func Must(err error) {
if err != nil {
panic(err)
}
}
var intMap = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
var revIntMap = map[string]int{
"eno": 1,
"owt": 2,
"eerht": 3,
"ruof": 4,
"evif": 5,
"xis": 6,
"neves": 7,
"thgie": 8,
"enin": 9,
}
func Reverse(s string) string {
size := len(s)
buf := make([]byte, size)
for start := 0; start < size; {
r, n := utf8.DecodeRuneInString(s[start:])
start += n
utf8.EncodeRune(buf[size-start:], r)
}
return string(buf)
}
func d1_1(r io.Reader) interface{} {
reNums := regexp.MustCompile(`(\d{1})`)
fileScanner := bufio.NewScanner(r)
fileScanner.Split(bufio.ScanLines)
totalSum := 0
for fileScanner.Scan() {
databytes := fileScanner.Bytes()
foundNums := reNums.FindAll(databytes, -1)
num1 := (int(foundNums[0][0]) - 48) * 10
num2 := int(foundNums[len(foundNums)-1][0]) - 48
totalSum += (num1 + num2)
}
return totalSum
}
func d1_2(r io.Reader) int {
reNums := regexp.MustCompile(`(one|two|three|four|five|six|seven|eight|nine|\d)`)
revNums := regexp.MustCompile(`(eno|owt|eerht|ruof|evif|xis|neves|thgie|enin|\d)`)
//numbers := make([]int, 0, 1000)
fileScanner := bufio.NewScanner(r)
fileScanner.Split(bufio.ScanLines)
totalSum := 0
for fileScanner.Scan() {
databytes := fileScanner.Text()
first := reNums.FindString(databytes)
last := revNums.FindString(Reverse(databytes))
var num1 int
if len(first) == 1 {
num1 = (int(first[0]) - 48) * 10
} else {
num1 = intMap[first] * 10
}
var num2 int
if len(last) == 1 {
num2 = int(last[0]) - 48
} else {
num2 = revIntMap[last]
}
//numbers = append(numbers, num1+num2)
totalSum += (num1 + num2)
}
return totalSum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment