This commit is contained in:
2025-02-14 15:14:03 +00:00
parent a529516bab
commit 759b9c9544
23 changed files with 11146 additions and 6 deletions

View File

@@ -1,7 +1,6 @@
package dijkstra
import (
"fmt"
"math"
"sync"
)
@@ -92,7 +91,7 @@ func getShortestPath(startNode *Node, endNode *Node, g *ItemGraph) ([]Point, int
pathval = prev[pathval]
}
finalArr = append(finalArr, pathval)
fmt.Println(finalArr)
// fmt.Println(finalArr)
for i, j := 0, len(finalArr)-1; i < j; i, j = i+1, j-1 {
finalArr[i], finalArr[j] = finalArr[j], finalArr[i]
}

View File

@@ -0,0 +1,47 @@
package memo
import "sync"
type Func func(key interface{}) interface{}
type result struct {
value interface{}
}
type Memo struct {
f Func
cache map[interface{}]result
mu sync.RWMutex // Allows concurrent reads.
}
func New(f Func) *Memo {
return &Memo{
f: f,
cache: make(map[interface{}]result),
}
}
func (memo *Memo) Get(key interface{}) interface{} {
// First, try to read the cache using a read lock.
memo.mu.RLock()
res, ok := memo.cache[key]
memo.mu.RUnlock()
if ok {
return res.value
}
// Compute the result without holding the lock.
computed := memo.f(key)
// Now acquire a write lock to update the cache.
memo.mu.Lock()
// Double-check: another goroutine may have stored the result in the meantime.
res, ok = memo.cache[key]
if !ok {
res.value = computed
memo.cache[key] = res
}
memo.mu.Unlock()
return res.value
}

View File

@@ -0,0 +1,56 @@
package ringbuffer
import (
"sync"
)
type RingBuffer[T any] struct {
buffer []T
size int
mu sync.Mutex
write int
count int
}
// NewRingBuffer creates a new ring buffer with a fixed size.
func NewRingBuffer[T any](size int) *RingBuffer[T] {
return &RingBuffer[T]{
buffer: make([]T, size),
size: size,
}
}
// Add inserts a new element into the buffer, overwriting the oldest if full.
func (rb *RingBuffer[T]) Add(value T) {
rb.mu.Lock()
defer rb.mu.Unlock()
rb.buffer[rb.write] = value
rb.write = (rb.write + 1) % rb.size
if rb.count < rb.size {
rb.count++
}
}
// Get returns the contents of the buffer in FIFO order.
func (rb *RingBuffer[T]) Get() []T {
rb.mu.Lock()
defer rb.mu.Unlock()
result := make([]T, 0, rb.count)
for i := 0; i < rb.count; i++ {
index := (rb.write + rb.size - rb.count + i) % rb.size
result = append(result, rb.buffer[index])
}
return result
}
// Len returns the current number of elements in the buffer.
func (rb *RingBuffer[T]) Len() int {
rb.mu.Lock()
defer rb.mu.Unlock()
return rb.count
}