Add back Day 1
This commit is contained in:
61
2023/gareth/day01/day01.go
Normal file
61
2023/gareth/day01/day01.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package day01
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Part1(input string) int {
|
||||
total := 0
|
||||
lines := strings.Split(input, "\r\n")
|
||||
for _, line := range lines {
|
||||
regex := regexp.MustCompile("[a-zA-Z]")
|
||||
numbers := regex.ReplaceAllString(line, "")
|
||||
number := string(numbers[0]) + string(numbers[len(numbers)-1])
|
||||
i, _ := strconv.Atoi(number)
|
||||
total += i
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
func Part2(input string) int {
|
||||
values := map[string]string{
|
||||
"one": "1",
|
||||
"two": "2",
|
||||
"three": "3",
|
||||
"four": "4",
|
||||
"five": "5",
|
||||
"six": "6",
|
||||
"seven": "7",
|
||||
"eight": "8",
|
||||
"nine": "9",
|
||||
}
|
||||
lines := strings.Split(input, "\r\n")
|
||||
s := ""
|
||||
|
||||
total := 0
|
||||
for _, line := range lines {
|
||||
numbers := []string{}
|
||||
for _, c := range line {
|
||||
s = s + string(c)
|
||||
if num, err := strconv.Atoi(string(c)); err == nil {
|
||||
numbers = append(numbers, strconv.Itoa(num))
|
||||
s = ""
|
||||
}
|
||||
for key, value := range values {
|
||||
if strings.Contains(s, key) {
|
||||
numbers = append(numbers, value)
|
||||
buffer := s[len(s)-1]
|
||||
s = "" + string(buffer)
|
||||
}
|
||||
}
|
||||
}
|
||||
number := numbers[0] + numbers[len(numbers)-1]
|
||||
i, _ := strconv.Atoi(number)
|
||||
total += i
|
||||
s = ""
|
||||
}
|
||||
return total
|
||||
}
|
||||
Reference in New Issue
Block a user