diff --git a/d05.go b/d05.go index b73166e..9c8acd8 100644 --- a/d05.go +++ b/d05.go @@ -13,24 +13,21 @@ type maprange struct { dst uint64 } -type mapdir struct { - src string - dst string -} - type mapval struct { cunt uint64 rnge maprange } type mapping struct { - dir mapdir + src string + dst string val []mapval } -func parse(f *os.File) (seeds []uint64, maps []mapping) { +func parse(f *os.File) (seeds []uint64, maps map[string]mapping) { s := bufio.NewScanner(f) + maps = make(map[string]mapping) inmap := false var curmap mapping for s.Scan() { @@ -44,7 +41,7 @@ func parse(f *os.File) (seeds []uint64, maps []mapping) { } case strings.HasSuffix(line, " map:"): - if inmap { maps = append(maps, curmap) } + if inmap { maps[curmap.src] = curmap } curmap = mapping{} inmap = true @@ -52,8 +49,8 @@ func parse(f *os.File) (seeds []uint64, maps []mapping) { split2 := strings.Index(line, " ") src := line[:split1] dst := line[split1 + 4:split2] - curmap.dir.src = src - curmap.dir.dst = dst + curmap.src = src + curmap.dst = dst case strings.Count(line, " ") >= 2 && inmap: thing := strings.Split(line, " ") @@ -64,28 +61,19 @@ func parse(f *os.File) (seeds []uint64, maps []mapping) { curmap.val = append(curmap.val, val) } } - if inmap { maps = append(maps, curmap) } + if inmap { maps[curmap.src] = curmap } return } -func part1(init_seeds []uint64, maps []mapping) uint64 { +func part1(init_seeds []uint64, maps map[string]mapping) uint64 { seeds := append(make([]uint64, 0, len(init_seeds)), init_seeds...) currency := "seed" for currency != "location" { - var map_cur mapping - map_found := false - for _, v := range maps { - if v.dir.src == currency { - map_cur = v - map_found = true - break - } - } - if !map_found { break } + map_cur := maps[currency] + currency = map_cur.dst - currency = map_cur.dir.dst for i, v := range seeds { for _, x := range map_cur.val { tmp := v - x.rnge.src @@ -105,7 +93,7 @@ func part1(init_seeds []uint64, maps []mapping) uint64 { return min } -func part2(init_seeds []uint64, maps []mapping) uint64 { +func part2(init_seeds []uint64, maps map[string]mapping) uint64 { seeds := make([]maprange, 0) for i, _ := range init_seeds { if i % 2 == 1 { continue } @@ -117,18 +105,9 @@ func part2(init_seeds []uint64, maps []mapping) uint64 { currency := "seed" for currency != "location" { - var map_cur mapping - map_found := false - for _, v := range maps { - if v.dir.src == currency { - map_cur = v - map_found = true - break - } - } - if !map_found { break } + map_cur := maps[currency] + currency = map_cur.dst - currency = map_cur.dir.dst newseedrnge := make([]maprange, 0) for _, v := range seeds { for _, x := range map_cur.val { @@ -160,11 +139,11 @@ func part2(init_seeds []uint64, maps []mapping) uint64 { seeds = newseedrnge } - minrnge := seeds[0].src + min := seeds[0].src for _, v := range seeds[1:] { - if v.src < minrnge { minrnge = v.src } + if v.src < min { min = v.src } } - return minrnge + return min } func main() {