Day 1b
This commit is contained in:
parent
255c191dfc
commit
399e40a6f9
|
@ -8,11 +8,47 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
const digits = "0123456789"
|
||||
|
||||
func words() [10]string {
|
||||
return [10]string{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
|
||||
}
|
||||
|
||||
func firstDigit(input string) string {
|
||||
var result string
|
||||
loc := len(input)
|
||||
if index := strings.IndexAny(input, "0123456789"); index != -1 {
|
||||
loc = index
|
||||
result = string([]rune(input)[index])
|
||||
}
|
||||
for key, value := range words() {
|
||||
if index := strings.Index(input, value); index != -1 && index <= loc {
|
||||
loc = index
|
||||
result = strconv.Itoa(key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func lastDigit(input string) string {
|
||||
var result string
|
||||
loc := -1
|
||||
if index := strings.LastIndexAny(input, "0123456789"); index != -1 {
|
||||
loc = index
|
||||
result = string([]rune(input)[index])
|
||||
}
|
||||
for key, value := range words() {
|
||||
if index := strings.LastIndex(input, value); index != -1 && index >= loc {
|
||||
loc = index
|
||||
result = strconv.Itoa(key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func getCalibrationValue(input string) int {
|
||||
firstIdx := strings.IndexAny(input, "0123456789")
|
||||
lastIdx := strings.LastIndexAny(input, "0123456789")
|
||||
first := string([]rune(input)[firstIdx])
|
||||
last := string([]rune(input)[lastIdx])
|
||||
first := firstDigit(input)
|
||||
last := lastDigit(input)
|
||||
output, _ := strconv.Atoi(first + last)
|
||||
return output
|
||||
}
|
||||
|
|
|
@ -11,6 +11,7 @@ func TestScanFile(t *testing.T) {
|
|||
want int;
|
||||
}{
|
||||
{"input1.txt", 142},
|
||||
{"input2.txt", 281},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
|
@ -25,7 +26,7 @@ func TestScanFile(t *testing.T) {
|
|||
}
|
||||
|
||||
if got != c.want {
|
||||
t.Errorf("ScanFile(%q) == %q, want %q", c.inFile, got, c.want)
|
||||
t.Errorf("ScanFile(%q) == %d, want %d", c.inFile, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
7
day01/input2.txt
Normal file
7
day01/input2.txt
Normal file
|
@ -0,0 +1,7 @@
|
|||
two1nine
|
||||
eightwothree
|
||||
abcone2threexyz
|
||||
xtwone3four
|
||||
4nineeightseven2
|
||||
zoneight234
|
||||
7pqrstsixteen
|
Loading…
Reference in a new issue