Skip to content

Commit

Permalink
day 1 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
kylehoehns committed Dec 1, 2023
1 parent 7e9a78e commit fb2e53d
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 0 deletions.
70 changes: 70 additions & 0 deletions puzzles/day01/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import (
"fmt"
"github.com/kylehoehns/aoc-2023-go/pkg/files"
"github.com/kylehoehns/aoc-2023-go/pkg/ints"
"strconv"
"strings"
"unicode"
)

func main() {
fmt.Println("Part 1: ", getCalibrationValues("input.txt"))
fmt.Println("Part 2: ", getCalibrationValues("input.txt"))
}

func getCalibrationValues(name string) int {
lines := files.ReadLines(name)
totalCalibrationValue := 0
for _, line := range lines {
firstDigit := getFirstDigit(line)
lastDigit := getLastDigit(line)
combined := strconv.Itoa(firstDigit) + strconv.Itoa(lastDigit)
totalCalibrationValue += ints.FromString(combined)
}
return totalCalibrationValue
}

func getFirstDigit(s string) int {
for i := 0; i < len(s); i++ {
if found, d := containsSpelledDigit(s[:i]); found {
return d
} else if unicode.IsDigit(rune(s[i])) {
return int(s[i] - '0')
}
}
panic("No digit found in " + s)
}

func getLastDigit(s string) int {
for i := len(s) - 1; i >= 0; i-- {
if found, d := containsSpelledDigit(s[i:]); found {
return d
} else if unicode.IsDigit(rune(s[i])) {
return int(s[i] - '0')
}
}
panic("No digit found in " + s)
}

var spelledDigits = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}

func containsSpelledDigit(s string) (bool, int) {
for k, v := range spelledDigits {
if strings.Contains(s, k) {
return true, v
}
}
return false, 0
}
27 changes: 27 additions & 0 deletions puzzles/day01/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestPart1(t *testing.T) {

t.Run("Part 1", func(t *testing.T) {
expected := 142
actual := getCalibrationValues("test-input.txt")
assert.Equal(t, expected, actual)
})

}

func TestPart2(t *testing.T) {

t.Run("Part 2", func(t *testing.T) {
expected := 281
actual := getCalibrationValues("test-input-part-two.txt")
assert.Equal(t, expected, actual)
})

}
7 changes: 7 additions & 0 deletions puzzles/day01/test-input-part-two.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
4 changes: 4 additions & 0 deletions puzzles/day01/test-input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet

0 comments on commit fb2e53d

Please sign in to comment.