2024 day 18 Complete

This commit is contained in:
2024-12-18 08:00:14 -06:00
parent 5ae4d0ca9b
commit 64bcac7d6a
6 changed files with 3745 additions and 126 deletions

View File

@@ -29,8 +29,8 @@ func part2(input []string) {
}
func solve(m *h.CoordByteMap, minStraight, maxStraight int) int {
q := NewPriorityQueue[heatState](func(a, b heatState) int {
return a.heatLoss - b.heatLoss
q := h.NewHeap[heatState](func(a, b heatState) bool {
return a.heatLoss < b.heatLoss
})
q.Push(heatState{
state: state{
@@ -50,7 +50,7 @@ func solve(m *h.CoordByteMap, minStraight, maxStraight int) int {
visitedCoords := make(map[h.Coordinate]bool)
visited := make(map[string]int)
for q.IsNotEmpty() {
for q.Len() != 0 {
chk := q.Pop()
if !m.ContainsCoord(*chk.state.pos) {
continue
@@ -126,67 +126,6 @@ type heatState struct {
heatLoss int
}
type PriorityQueue[T comparable] struct {
items []T
comparator func(a, b T) int
}
func NewPriorityQueue[T comparable](comparator func(a, b T) int) PriorityQueue[T] {
return PriorityQueue[T]{comparator: comparator}
}
func (pq *PriorityQueue[T]) Push(item T) {
pq.items = append(pq.items, item)
pq.heapifyUp(len(pq.items) - 1)
}
func (pq *PriorityQueue[T]) Pop() T {
top := pq.items[0]
lastIndex := len(pq.items) - 1
pq.items[0], pq.items[lastIndex] = pq.items[lastIndex], pq.items[0]
pq.items = pq.items[:lastIndex]
pq.heapifyDown(0)
return top
}
func (pq *PriorityQueue[T]) Peek() T {
return pq.items[0]
}
func (pq *PriorityQueue[T]) Len() int {
return len(pq.items)
}
func (pq *PriorityQueue[T]) IsEmpty() bool {
return len(pq.items) == 0
}
func (pq *PriorityQueue[T]) IsNotEmpty() bool {
return !pq.IsEmpty()
}
func (pq *PriorityQueue[T]) heapifyUp(index int) {
for index > 0 {
parentIndex := (index - 1) / 2
if pq.comparator(pq.items[index], pq.items[parentIndex]) < 0 {
pq.items[index], pq.items[parentIndex] = pq.items[parentIndex], pq.items[index]
index = parentIndex
} else {
break
}
}
}
func (pq *PriorityQueue[T]) heapifyDown(index int) {
for {
leftChild, rightChild, smallest := 2*index+1, 2*index+2, index
if leftChild < len(pq.items) && pq.comparator(pq.items[leftChild], pq.items[smallest]) < 0 {
smallest = leftChild
}
if rightChild < len(pq.items) && pq.comparator(pq.items[rightChild], pq.items[smallest]) < 0 {
smallest = rightChild
}
if smallest != index {
pq.items[index], pq.items[smallest] = pq.items[smallest], pq.items[index]
index = smallest
} else {
break
}
}
}
type direction h.Coordinate
func (d direction) Get(from *h.Coordinate) *h.Coordinate {
@@ -202,6 +141,7 @@ func (d direction) Get(from *h.Coordinate) *h.Coordinate {
}
return from
}
func (d direction) LeftTurn() direction {
switch d.String() {
case "N":
@@ -214,6 +154,7 @@ func (d direction) LeftTurn() direction {
return dirS
}
}
func (d direction) RightTurn() direction {
switch d.String() {
case "N":
@@ -226,6 +167,7 @@ func (d direction) RightTurn() direction {
return dirN
}
}
func (d direction) String() string {
switch {
case d.X == dirN.X && d.Y == dirN.Y: