diff --git a/day01/day01.go b/day01/day01.go new file mode 100644 index 0000000..7a6efda --- /dev/null +++ b/day01/day01.go @@ -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) +} \ No newline at end of file diff --git a/day01/day01_test.go b/day01/day01_test.go new file mode 100644 index 0000000..95e50e9 --- /dev/null +++ b/day01/day01_test.go @@ -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) + } + } +} \ No newline at end of file diff --git a/day01/input1.txt b/day01/input1.txt new file mode 100644 index 0000000..7bbc69a --- /dev/null +++ b/day01/input1.txt @@ -0,0 +1,4 @@ +1abc2 +pqr3stu8vwx +a1b2c3d4e5f +treb7uchet