]> fbox.kageds.com Git - adventofcode.git/blob - 2023/gareth/day01/day01.go
20223 day1
[adventofcode.git] / 2023 / gareth / day01 / day01.go
1 package day01
2
3 import (
4 "regexp"
5 "strconv"
6 "strings"
7 )
8
9 func Part1(input string) int {
10 total := 0
11 lines := strings.Split(input, "\r\n")
12 for _, line := range lines {
13 regex := regexp.MustCompile("[a-zA-Z]")
14 numbers := regex.ReplaceAllString(line, "")
15 number := string(numbers[0]) + string(numbers[len(numbers)-1])
16 i, _ := strconv.Atoi(number)
17 total += i
18 }
19
20 return total
21 }
22
23 func Part2(input string) int {
24 values := map[string]string{
25 "one": "1",
26 "two": "2",
27 "three": "3",
28 "four": "4",
29 "five": "5",
30 "six": "6",
31 "seven": "7",
32 "eight": "8",
33 "nine": "9",
34 }
35 lines := strings.Split(input, "\r\n")
36 s := ""
37
38 total := 0
39 for _, line := range lines {
40 numbers := []string{}
41 for _, c := range line {
42 s = s + string(c)
43 if num, err := strconv.Atoi(string(c)); err == nil {
44 numbers = append(numbers, strconv.Itoa(num))
45 s = ""
46 }
47 for key, value := range values {
48 if strings.Contains(s, key) {
49 numbers = append(numbers, value)
50 buffer := s[len(s)-1]
51 s = "" + string(buffer)
52 }
53 }
54 }
55 number := numbers[0] + numbers[len(numbers)-1]
56 i, _ := strconv.Atoi(number)
57 total += i
58 s = ""
59 }
60 return total
61 }