diff --git a/day01/day01.go b/day01/day01.go index 7a6efda..9b0505f 100644 --- a/day01/day01.go +++ b/day01/day01.go @@ -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 } diff --git a/day01/day01_test.go b/day01/day01_test.go index 95e50e9..141ab87 100644 --- a/day01/day01_test.go +++ b/day01/day01_test.go @@ -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) } } } \ No newline at end of file diff --git a/day01/input2.txt b/day01/input2.txt new file mode 100644 index 0000000..4316a6b --- /dev/null +++ b/day01/input2.txt @@ -0,0 +1,7 @@ +two1nine +eightwothree +abcone2threexyz +xtwone3four +4nineeightseven2 +zoneight234 +7pqrstsixteen \ No newline at end of file