day9, part2
This commit is contained in:
parent
162d0d9ebf
commit
3919a70d09
|
@ -24,6 +24,23 @@ func Run() int {
|
|||
return result
|
||||
}
|
||||
|
||||
func Run2() int {
|
||||
log.Println("hello day 9, part2")
|
||||
filename := "day9/input"
|
||||
bytes, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintln("error reading file: ", err))
|
||||
}
|
||||
result := 0
|
||||
|
||||
for _, line := range strings.Split(string(bytes), "\n") {
|
||||
seq := CreateSequence(line)
|
||||
result += seq.Get(-1)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
type Cell struct {
|
||||
IsCached bool
|
||||
Value func() int
|
||||
|
@ -54,6 +71,7 @@ func CachedCell(val int) Cell {
|
|||
type Coord struct {
|
||||
Row, Col int
|
||||
}
|
||||
|
||||
func (c Coord) Equal(other Coord) bool {
|
||||
return c.Col == other.Col && c.Row == other.Row
|
||||
}
|
||||
|
@ -105,9 +123,11 @@ func (s *Sequence) GetAny(coord Coord) Cell {
|
|||
}
|
||||
|
||||
// log.Printf("creating new uncashed at %d %d\n", row, col)
|
||||
cell = Cell{
|
||||
IsCached: false,
|
||||
Value: func() int {
|
||||
|
||||
var calcFunc func() int
|
||||
|
||||
if col > 0 {
|
||||
calcFunc = func() int {
|
||||
if cell.IsCached {
|
||||
return cell.SavedValue
|
||||
}
|
||||
|
@ -118,7 +138,26 @@ func (s *Sequence) GetAny(coord Coord) Cell {
|
|||
cell.IsCached = true
|
||||
cell.SavedValue = value
|
||||
return value
|
||||
},
|
||||
}
|
||||
} else {
|
||||
// for part 2, propagate backward from known elements on the right
|
||||
calcFunc = func() int {
|
||||
if cell.IsCached {
|
||||
return cell.SavedValue
|
||||
}
|
||||
// log.Printf("calc value for %d %d cell\n", row, col)
|
||||
simplerCell := s.GetAny(Coord{row + 1, col})
|
||||
nextCell := s.GetAny(Coord{row, col + 1})
|
||||
value := nextCell.Value() - simplerCell.Value()
|
||||
cell.IsCached = true
|
||||
cell.SavedValue = value
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
cell = Cell{
|
||||
IsCached: false,
|
||||
Value: calcFunc,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
13
main.go
13
main.go
|
@ -9,17 +9,6 @@ import (
|
|||
func main() {
|
||||
log.Print("> starting run:")
|
||||
|
||||
// line := "0 3 6 9 12 15"
|
||||
// line := "1 3 6 10 15 21"
|
||||
// line := "10 13 16 21 30 45"
|
||||
// seq := day9.CreateSequence(line)
|
||||
// fmt.Println(seq.String())
|
||||
|
||||
// fmt.Printf("got %+v \n", seq)
|
||||
// fmt.Printf("%s\n", seq.String())
|
||||
|
||||
// fmt.Printf("next value is %d\n", seq.Next())
|
||||
|
||||
result := day9.Run()
|
||||
result := day9.Run2()
|
||||
log.Printf("day9 result: %d\n****\n", result)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue