adventofcode/2023/day01/main.go

98 lines
1.5 KiB
Go
Raw Normal View History

2023-12-01 10:18:57 +00:00
package main
import (
"fmt"
h "git.bullercodeworks.com/brian/adventofcode/helpers"
)
func main() {
inp := h.StdinToStringSlice()
part1(inp)
part2(inp)
}
func part1(input []string) {
var value int
for _, i := range input {
value = value + getValue(i, false)
}
fmt.Println("# Part 1")
fmt.Println(value)
}
var nums = []string{
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
}
func part2(input []string) {
var value int
for _, i := range input {
value = value + getValue(i, true)
}
fmt.Println("# Part 2")
fmt.Println(value)
}
func getValue(wrk string, p2 bool) int {
return (getFirstValue(wrk, p2) * 10) + getLastValue(wrk, p2)
}
func getFirstValue(wrk string, p2 bool) int {
for j := 0; j < len(wrk); j++ {
if p2 {
v := numStringAt(wrk, j)
if v > -1 {
return v
}
}
if wrk[j]-'0' >= 0 && wrk[j]-'0' <= 9 {
return int(wrk[j] - '0')
}
}
return 0
}
func getLastValue(wrk string, p2 bool) int {
for j := len(wrk) - 1; j >= 0; j-- {
if p2 {
v := numStringAt(wrk, j)
if v > -1 {
return v
}
}
if wrk[j]-'0' >= 0 && wrk[j]-'0' <= 9 {
return int(wrk[j] - '0')
}
}
return 0
}
func numStringAt(haystack string, pos int) int {
for i := range nums {
if stringAt(haystack, pos, nums[i]) {
return i
}
}
return -1
}
func stringAt(haystack string, pos int, needle string) bool {
if len(haystack) < pos+len(needle) {
return false
}
for i := range needle {
if haystack[pos+i] != needle[i] {
return false
}
}
return true
}