Parallelize
This commit is contained in:
@@ -38,17 +38,34 @@ func optimize(h *heap.Heap, samples [][]byte) *heap.Heap {
|
|||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type sampleResult struct {
|
||||||
|
heap *heap.Heap
|
||||||
|
score int
|
||||||
|
}
|
||||||
|
|
||||||
func optimize2(baseHeap *heap.Heap, samples [][]byte) *heap.Heap {
|
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
|
var best *heap.Heap = nil
|
||||||
bestScore := totalLength(baseHeap, samples)
|
bestScore := totalLength(baseHeap, samples)
|
||||||
|
|
||||||
for i := 0; i < 256; i++ {
|
for i := 0; i < 256; i++ {
|
||||||
h := baseHeap.Clone()
|
res := <-ch
|
||||||
h.IncrementSymbol(byte(i))
|
if res.score < bestScore {
|
||||||
score := totalLength(h, samples)
|
best = res.heap
|
||||||
if score < bestScore {
|
bestScore = res.score
|
||||||
best = h
|
|
||||||
bestScore = score
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"maps"
|
"maps"
|
||||||
"slices"
|
"slices"
|
||||||
"sort"
|
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -78,8 +77,6 @@ func (h Heap) String() string {
|
|||||||
strs = append(strs, fmt.Sprintf("{%#U}=%d", node.symbol, node.count))
|
strs = append(strs, fmt.Sprintf("{%#U}=%d", node.symbol, node.count))
|
||||||
}
|
}
|
||||||
|
|
||||||
sort.Strings(strs)
|
|
||||||
|
|
||||||
return strings.Join(strs, ", ")
|
return strings.Join(strs, ", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user