From 855b15ad29fb51df4669072f45039171bd5ff243 Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Fri, 29 Dec 2023 22:02:07 -0700 Subject: [PATCH] Parallelize --- genseed/genseed.go | 29 +++++++++++++++++++++++------ heap/heap.go | 3 --- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/genseed/genseed.go b/genseed/genseed.go index d7f32ed..9847eb4 100644 --- a/genseed/genseed.go +++ b/genseed/genseed.go @@ -38,17 +38,34 @@ func optimize(h *heap.Heap, samples [][]byte) *heap.Heap { return h } +type sampleResult struct { + heap *heap.Heap + score int +} + func optimize2(baseHeap *heap.Heap, samples [][]byte) *heap.Heap { + ch := make(chan sampleResult, 100) + + for i := 0; i < 256; i++ { + i := i + go func () { + h := baseHeap.Clone() + h.IncrementSymbol(byte(i)) + ch <- sampleResult{ + heap: h, + score: totalLength(h, samples), + } + }() + } + var best *heap.Heap = nil bestScore := totalLength(baseHeap, samples) for i := 0; i < 256; i++ { - h := baseHeap.Clone() - h.IncrementSymbol(byte(i)) - score := totalLength(h, samples) - if score < bestScore { - best = h - bestScore = score + res := <-ch + if res.score < bestScore { + best = res.heap + bestScore = res.score } } diff --git a/heap/heap.go b/heap/heap.go index 3553f87..74164ad 100644 --- a/heap/heap.go +++ b/heap/heap.go @@ -4,7 +4,6 @@ import ( "fmt" "maps" "slices" - "sort" "strings" ) @@ -78,8 +77,6 @@ func (h Heap) String() string { strs = append(strs, fmt.Sprintf("{%#U}=%d", node.symbol, node.count)) } - sort.Strings(strs) - return strings.Join(strs, ", ") }