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
|
||||||
|
}
|
||||||
25
2023/gareth/day01/day01_test.go
Normal file
25
2023/gareth/day01/day01_test.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package day01
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPart1(t *testing.T) {
|
||||||
|
r := Part1(`1abc2
|
||||||
|
pqr3stu8vwx
|
||||||
|
a1b2c3d4e5f
|
||||||
|
treb7uchet`)
|
||||||
|
assert.Equal(t, 142, r)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPart2(t *testing.T) {
|
||||||
|
r := Part2(`two1nine
|
||||||
|
eightwothree
|
||||||
|
abcone2threexyz
|
||||||
|
xtwone3four
|
||||||
|
4nineeightseven2
|
||||||
|
zoneight234
|
||||||
|
7pqrstsixteen`)
|
||||||
|
assert.Equal(t, 281, r)
|
||||||
|
}
|
||||||
1000
2023/gareth/day01/input.txt
Normal file
1000
2023/gareth/day01/input.txt
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user