From dc8065cfd32bc45e8f750f6a51681d131e03147b Mon Sep 17 00:00:00 2001 From: Alexander Avery Date: Tue, 5 Dec 2023 22:20:27 -0500 Subject: [PATCH] day 5 part 1 test passes --- day05.go | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++ main_test.go | 45 +++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 day05.go diff --git a/day05.go b/day05.go new file mode 100644 index 0000000..842ce44 --- /dev/null +++ b/day05.go @@ -0,0 +1,81 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" +) + +type day05 struct{} + +type seedmap struct { + original int64 + previous int64 + current int64 +} + +func readseeds(line string) []seedmap { + seeds := make([]seedmap, 0, 10) + scanner := bufio.NewScanner(strings.NewReader(line)) + scanner.Split(bufio.ScanWords) + + for scanner.Scan() { + val, _ := strconv.ParseInt(scanner.Text(), 10, 64) + seeds = append(seeds, seedmap{original: val, current: val, previous: val}) + } + + return seeds +} + +func updateseeds(line string, seeds []seedmap) []seedmap { + input := strings.SplitN(line, " ", 3) + dst, _ := strconv.ParseInt(input[0], 10, 64) + src, _ := strconv.ParseInt(input[1], 10, 64) + rng, _ := strconv.ParseInt(input[2], 10, 64) + + for i, seed := range seeds { + if seed.current >= src && seed.current <= src+rng && seed.current == seed.previous { + seeds[i].current = seed.current + (dst - src) + } + } + return seeds +} + +func minint64(x, y int64) int64 { + if x > y { + return y + } + return x +} + +func (d day05) solve1(r io.Reader) string { + scanner := bufio.NewScanner(r) + + scanner.Scan() + _, seedline, _ := strings.Cut(scanner.Text(), ": ") + seeds := readseeds(seedline) + + for scanner.Scan() { + line := scanner.Text() + if strings.HasSuffix(line, "map:") || line == "" { + for i := range seeds { + seeds[i].previous = seeds[i].current + } + continue + } + seeds = updateseeds(scanner.Text(), seeds) + } + + min := minint64(seeds[0].current, seeds[1].current) + for i := 2; i < len(seeds); i++ { + min = minint64(min, seeds[i].current) + } + + return fmt.Sprintf("%d", min) +} + +func (d day05) solve2(r io.Reader) string { + return "incomplete" +} diff --git a/main_test.go b/main_test.go index 92187da..f488e5f 100644 --- a/main_test.go +++ b/main_test.go @@ -104,3 +104,48 @@ Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11` } } + +func TestDay05(t *testing.T) { + input := `seeds: 79 14 55 13 + +seed-to-soil map: +50 98 2 +52 50 48 + +soil-to-fertilizer map: +0 15 37 +37 52 2 +39 0 15 + +fertilizer-to-water map: +49 53 8 +0 11 42 +42 0 7 +57 7 4 + +water-to-light map: +88 18 7 +18 25 70 + +light-to-temperature map: +45 77 23 +81 45 19 +68 64 13 + +temperature-to-humidity map: +0 69 1 +1 0 69 + +humidity-to-location map: +60 56 37 +56 93 4` + + puzzle := day05{} + + ans := "35" + res := puzzle.solve1(strings.NewReader(input)) + if ans != res { + t.Errorf("solve1() = %s; wanted %s", res, ans) + } + +}