Browse Source

restructure d05

master
mid-kid 11 months ago
parent
commit
32141d5d64
  1. 59
      d05.go

59
d05.go

@ -28,26 +28,22 @@ type mapping struct {
val []mapval
}
func main() {
f, _ := os.Open(os.Args[1])
s := bufio.NewScanner(f)
func parse(f *os.File) (seeds []uint64, maps []mapping) {
s := bufio.NewScanner(f)
var maps []mapping
var init_seeds []uint64
inmap := false
var curmap mapping
for s.Scan() {
for s.Scan() {
line := s.Text()
switch {
case strings.HasPrefix(line, "seeds: "):
thing := strings.Split(line[7:], " ")
switch {
case strings.HasPrefix(line, "seeds: "):
thing := strings.Split(line[7:], " ")
for _, v := range thing {
val, _ := strconv.ParseUint(v, 0, 64)
init_seeds = append(init_seeds, val)
seeds = append(seeds, val)
}
case strings.HasSuffix(line, " map:"):
case strings.HasSuffix(line, " map:"):
if inmap { maps = append(maps, curmap) }
curmap = mapping{}
inmap = true
@ -67,10 +63,15 @@ func main() {
val.cunt, _ = strconv.ParseUint(thing[2], 0, 64)
curmap.val = append(curmap.val, val)
}
}
}
if inmap { maps = append(maps, curmap) }
return
}
func part1(init_seeds []uint64, maps []mapping) uint64 {
seeds := append(make([]uint64, 0, len(init_seeds)), init_seeds...)
currency := "seed"
for currency != "location" {
var map_cur mapping
@ -97,22 +98,24 @@ func main() {
}
}
minloc := seeds[0]
min := seeds[0]
for _, v := range seeds[1:] {
if v < minloc { minloc = v }
if v < min { min = v }
}
fmt.Println(minloc)
return min
}
seedrnge := make([]maprange, 0)
func part2(init_seeds []uint64, maps []mapping) uint64 {
seeds := make([]maprange, 0)
for i, _ := range init_seeds {
if i % 2 == 1 { continue }
var rnge maprange
rnge.src = init_seeds[i + 0]
rnge.dst = rnge.src + init_seeds[i + 1]
seedrnge = append(seedrnge, rnge)
seeds = append(seeds, rnge)
}
currency = "seed"
currency := "seed"
for currency != "location" {
var map_cur mapping
map_found := false
@ -127,7 +130,7 @@ func main() {
currency = map_cur.dir.dst
newseedrnge := make([]maprange, 0)
for _, v := range seedrnge {
for _, v := range seeds {
for _, x := range map_cur.val {
src := x.rnge.src
end := x.rnge.src + x.cunt
@ -154,12 +157,20 @@ func main() {
}
if v.src != v.dst { newseedrnge = append(newseedrnge, v) }
}
seedrnge = newseedrnge
seeds = newseedrnge
}
minrnge := seedrnge[0].src
for _, v := range seedrnge[1:] {
minrnge := seeds[0].src
for _, v := range seeds[1:] {
if v.src < minrnge { minrnge = v.src }
}
fmt.Println(minrnge)
return minrnge
}
func main() {
f, _ := os.Open(os.Args[1])
seeds, maps := parse(f)
fmt.Println(part1(seeds, maps))
fmt.Println(part2(seeds, maps))
}

Loading…
Cancel
Save