This commit is contained in:
Katherina Walshe-Grey 2024-10-28 18:12:20 +00:00
parent c3c1fe8b3a
commit 255c191dfc
3 changed files with 74 additions and 0 deletions

39
day01/day01.go Normal file
View file

@ -0,0 +1,39 @@
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
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])
output, _ := strconv.Atoi(first + last)
return output
}
func ScanFile(file *os.File) (int, error) {
scanner := bufio.NewScanner(file);
sum := 0;
for scanner.Scan() {
sum += getCalibrationValue(scanner.Text());
}
if err := scanner.Err(); err != nil {
return 0, err
}
return sum, nil
}
func main() {
sum, err := ScanFile(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid input: %s\n", err)
return
}
fmt.Println(sum)
}

31
day01/day01_test.go Normal file
View file

@ -0,0 +1,31 @@
package main
import (
"os"
"testing"
)
func TestScanFile(t *testing.T) {
cases := []struct {
inFile string;
want int;
}{
{"input1.txt", 142},
}
for _, c := range cases {
f, err := os.Open(c.inFile)
if err != nil {
t.Fatal(err)
}
got, err := ScanFile(f)
if err != nil {
t.Fatal(err)
}
if got != c.want {
t.Errorf("ScanFile(%q) == %q, want %q", c.inFile, got, c.want)
}
}
}

4
day01/input1.txt Normal file
View file

@ -0,0 +1,4 @@
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet