本文整理匯總了Golang中container/heap.Push函數的典型用法代碼示例。如果您正苦於以下問題:Golang Push函數的具體用法?Golang Push怎麽用?Golang Push使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Push函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: add
func (z *zpHeap) add(y *y, s *State) {
var a []string
for sym := range s.actions {
a = append(a, sym.Name)
}
sort.Strings(a)
for _, nm := range a {
sym := y.Syms[nm]
actions := s.actions[sym]
action := actions[0]
if action.kind == 's' {
heap.Push(z, &zpElem{s, y.States[action.arg], sym, s.distance + len(sym.MinString())})
}
}
a = a[:0]
for sym := range s.gotos {
a = append(a, sym.Name)
}
sort.Strings(a)
for _, nm := range a {
sym := y.Syms[nm]
action := s.gotos[sym]
heap.Push(z, &zpElem{s, y.States[action.arg], sym, s.distance + len(sym.MinString())})
}
}
示例2: ingest
// Ingests an alert into the memoryAlertManager and creates a new
// AggregationInstance for it, if necessary.
func (s *memoryAlertManager) ingest(a *Alert) {
fp := a.Fingerprint()
agg, ok := s.aggregates[fp]
if !ok {
agg = &AlertAggregate{
Created: time.Now(),
}
agg.Ingest(a)
for _, r := range s.rules {
if r.Handles(agg.Alert) {
agg.Rule = r
break
}
}
s.aggregates[fp] = agg
heap.Push(&s.aggregatesByLastRefreshed, agg)
heap.Push(&s.aggregatesByNextNotification, agg)
s.needsNotificationRefresh = true
} else {
agg.Ingest(a)
heap.Init(&s.aggregatesByLastRefreshed)
}
}
示例3: TestScanCursors
func TestScanCursors(t *testing.T) {
s := ScanCursors{}
heap.Init(&s)
heap.Push(&s, &testScanCursor{
key: "b",
})
heap.Push(&s, &testScanCursor{
key: "a",
})
heap.Push(&s, &testScanCursor{
key: "c",
})
a := heap.Pop(&s).(*testScanCursor)
if a.key != "a" {
t.Errorf("expected a")
}
b := heap.Pop(&s).(*testScanCursor)
if b.key != "b" {
t.Errorf("expected b")
}
c := heap.Pop(&s).(*testScanCursor)
if c.key != "c" {
t.Errorf("expected c")
}
}
示例4: Dijkstra
// Dijkstra's Algorithm is essentially a goalless Uniform Cost Search. That is, its results are roughly equivalent to
// running A* with the Null Heuristic from a single node to every other node in the graph -- though it's a fair bit faster
// because running A* in that way will recompute things it's already computed every call. Note that you won't necessarily get the same path
// you would get for A*, but the cost is guaranteed to be the same (that is, if multiple shortest paths exist, you may get a different shortest path).
//
// Like A*, Dijkstra's Algorithm likely won't run correctly with negative edge weights -- use Bellman-Ford for that instead
//
// Dijkstra's algorithm usually only returns a cost map, however, since the data is available this version will also reconstruct the path to every node
func Dijkstra(source Node, graph Graph, Cost func(Node, Node) float64) (paths map[int][]Node, costs map[int]float64) {
if Cost == nil {
if cgraph, ok := graph.(Coster); ok {
Cost = cgraph.Cost
} else {
Cost = UniformCost
}
}
nodes := graph.NodeList()
openSet := &aStarPriorityQueue{}
closedSet := set.NewSet() // This is to make use of that same
costs = make(map[int]float64, len(nodes)) // May overallocate, will change if it becomes a problem
predecessor := make(map[int]Node, len(nodes))
nodeIDMap := make(map[int]Node, len(nodes))
heap.Init(openSet)
// I don't think we actually need the init step since I use a map check rather than inf to check if we're done
/*for _, node := range nodes {
if node == source {
heap.Push(openSet, internalNode{node, 0, 0})
costs[node] = 0
} else {
heap.Push(openSet, internalNode{node, math.MaxFloat64, math.MaxFloat64})
predecessor[node] = -1
}
}*/
costs[source.ID()] = 0
heap.Push(openSet, internalNode{source, 0, 0})
for openSet.Len() != 0 {
node := heap.Pop(openSet).(internalNode)
/* if _, ok := costs[node.int]; !ok {
break
} */
if closedSet.Contains(node.ID()) { // As in A*, prevents us from having to slowly search and reorder the queue
continue
}
nodeIDMap[node.ID()] = node
closedSet.Add(node.ID())
for _, neighbor := range graph.Successors(node) {
tmpCost := costs[node.ID()] + Cost(node, neighbor)
if cost, ok := costs[neighbor.ID()]; !ok || tmpCost < cost {
costs[neighbor.ID()] = cost
predecessor[neighbor.ID()] = node
heap.Push(openSet, internalNode{neighbor, cost, cost})
}
}
}
paths = make(map[int][]Node, len(costs))
for node, _ := range costs { // Only reconstruct the path if one exists
paths[node] = rebuildPath(predecessor, nodeIDMap[node])
}
return paths, costs
}
示例5: DerivePath
// DerivePath returns the cheapest way to satisfy the MSP (the one with the minimal number of delegations).
//
// ok: True if the MSP can be satisfied with current delegations; false if not.
// names: The names in the top-level threshold gate that need to be delegated.
// locs: The index in the treshold gate for each name.
// trace: All names that must be delegated for for this gate to be satisfied.
func (m MSP) DerivePath(db UserDatabase) (ok bool, names []string, locs []int, trace []string) {
ts := &TraceSlice{}
for i, cond := range m.Conds {
switch cond := cond.(type) {
case Name:
if db.CanGetShare(cond.string) {
heap.Push(ts, TraceElem{
i,
[]string{cond.string},
[]string{cond.string},
})
}
case Formatted:
sok, _, _, strace := MSP(cond).DerivePath(db)
if sok {
heap.Push(ts, TraceElem{i, []string{}, strace})
}
}
if (*ts).Len() > m.Min { // If we can otherwise satisfy the threshold gate
heap.Pop(ts) // Drop the TraceElem with the heaviest trace (the one that requires the most delegations).
}
}
ok = (*ts).Len() >= m.Min
locs, names, trace = ts.Compact()
return
}
示例6: TestRemove
func TestRemove(t *testing.T) {
var count int
if golangcafeheap.Len() <= 0 {
// Add時に0件になるので…。
heap.Push(golangcafeheap, GolangCafe{Name: "ttyokoyama", Priority: 1, Count: 13, Index: 2})
heap.Push(golangcafeheap, GolangCafe{Name: "taknb2nch", Priority: 2, Count: 13, Index: 3})
heap.Push(golangcafeheap, GolangCafe{Name: "qt_luigi", Priority: 3, Count: 13, Index: 4})
heap.Push(golangcafeheap, GolangCafe{Name: "tam_x", Priority: 4, Count: 1, Index: 1})
} else {
count = golangcafeheap.Len()
}
heap.Remove(golangcafeheap, 2)
if golangcafeheap.Len() != (count - 1) {
t.Errorf("golangcafeheap.Len() = %d, %d", golangcafeheap.Len(), count)
}
n := golangcafeheap.Len()
for i := 0; i < n; i++ {
item := golangcafeheap.Pop()
golangcafe := item.(*GolangCafe)
t.Logf("Name: %s Priority: %d Count: %d Index: %d",
golangcafe.Name, golangcafe.Priority, golangcafe.Count, golangcafe.Index)
}
}
示例7: TestPriorityQueueInit
func TestPriorityQueueInit(t *testing.T) {
items := map[string]int{
"c": 5, "d": 3, "e": 0, "b": 15,
}
pq := JobQueue{}
heap.Init(&pq)
for id, pri := range items {
heap.Push(&pq, newJob(id, pri))
}
//push in a new job with a high and low priority
heap.Push(&pq, newJob("a", 99))
heap.Push(&pq, newJob("z", -19))
// make sure the ordering is correct
target_order := []string{"a", "b", "c", "d", "e", "z"}
i := 0
for pq.Len() > 0 {
j := heap.Pop(&pq).(*Job)
t.Logf("Found job:%s pri:%f", j.Id, j.priority)
if j.Id != target_order[i] {
t.Errorf("Job id %s expected, but found %s at position %d priority %f", target_order[i], j.Id, i, j.priority)
}
i++
}
}
示例8: startNextJob
func startNextJob(event *models.Event, node *models.Node,
job *models.Job, scheduler scheduling.Scheduler,
eventQueue *models.EventQueue) {
node.CurJob = job
node.EstCompletion = event.Time + scheduler.GetAllocation(job)
completeTime := event.Time + job.RealExec
if job.AbsoluteDeadline() < node.EstCompletion && job.AbsoluteDeadline() < completeTime {
heap.Push(eventQueue, &models.Event{
Job: job,
Time: job.AbsoluteDeadline(),
Node: node,
Type: models.Miss,
})
} else if node.EstCompletion < completeTime {
heap.Push(eventQueue, &models.Event{
Job: job,
Time: node.EstCompletion,
Node: node,
Type: models.Stretch,
})
} else {
heap.Push(eventQueue, &models.Event{
Job: event.Job,
Time: completeTime,
Node: node,
Type: models.Complete,
})
}
}
示例9: TestInit
func TestInit(t *testing.T) {
x = []string{"x", "y", "z"}
a = []string{"a", "b", "c"}
//fmt.Println(x, a)
hh := NewHistory(20)
heap.Init(hh)
//hh.PrintDump()
heap.Push(hh, x)
//hh.Add(x)
//hh.PrintDump()
if hh.heap[0][0] != "x" {
t.Errorf("First element incorrect: %#v", hh.heap[0][0])
}
heap.Push(hh, a)
//hh.Add(a)
//fmt.Printf("hh: %#v\n", hh)
if hh == nil {
t.Errorf("First history stored is: %#v", hh)
}
if hh.heap[0][0] != "a" {
t.Errorf("First element incorrect: %#v", hh.heap[0][0])
}
}
示例10: ShortestPath2
func (src Point) ShortestPath2(dst Point, m *Map, fp io.Writer) ([]Point, os.Error) {
h := &myHeap2{}
heap.Init(h)
heap.Push(h, NewNode(src, dst))
// Each entry points to previous point in path
seen := make(map[Location]bool)
expansions := make([]Point, 0)
popped := make([]*Node2, 0)
defer func() {
fmt.Fprintf(fp, "popped = %s;\n\n", nodes2js(popped))
fmt.Fprintf(fp, "expansions= %s;\n\n", points2js(expansions))
}()
for h.Len() != 0 {
n := heap.Pop(h).(*Node2)
popped = append(popped, n)
for n2 := range n.expand(m, dst, seen) {
log.Printf("%s -> %s", n, n2)
expansions = append(expansions, n2.Point)
if n2.Equals(dst) {
return n2.path(), nil
}
heap.Push(h, n2)
}
}
return nil, fmt.Errorf("no path found")
}
示例11: cluster
// Cluster by repeatedly splitting clusters.
// Use a heap as priority queue for picking clusters to split.
// The rule is to spilt the cluster with the most pixels.
// Terminate when the desired number of clusters has been populated
// or when clusters cannot be further split.
func (qz *quantizer) cluster() {
pq := new(queue)
// Initial cluster. populated at this point, but not analyzed.
c := &qz.cs[0]
var m uint32
for i := 1; ; {
// Only enqueue clusters that can be split.
if qz.setWidestChannel(c) {
heap.Push(pq, c)
}
// If no clusters have any color variation, mark the end of the
// cluster list and quit early.
if len(*pq) == 0 {
qz.cs = qz.cs[:i]
break
}
s := heap.Pop(pq).(*cluster) // get cluster to split
m = qz.medianCut(s)
c = &qz.cs[i] // set c to new cluster
i++
qz.split(s, c, m) // split s into c and s at value m
// Normal exit is when all clusters are populated.
if i == len(qz.cs) {
break
}
if qz.setWidestChannel(s) {
heap.Push(pq, s) // return s to queue
}
}
}
示例12: TestEventQueue
func TestEventQueue(t *testing.T) {
queue := make(EventQueue, 0, 4)
heap.Push(&queue, &Event{Y: 5})
heap.Push(&queue, &Event{Y: 3})
heap.Push(&queue, &Event{Y: 7})
heap.Push(&queue, &Event{Y: 1})
var e *Event
e = heap.Pop(&queue).(*Event)
if e.Y != 7 {
t.Fatalf("Wanted priority 7, got %v", e.Y)
}
e = heap.Pop(&queue).(*Event)
if e.Y != 5 {
t.Fatalf("Wanted priority 5, got %v", e.Y)
}
e = heap.Pop(&queue).(*Event)
if e.Y != 3 {
t.Fatalf("Wanted priority 3, got %v", e.Y)
}
e = heap.Pop(&queue).(*Event)
if e.Y != 1 {
t.Fatalf("Wanted priority 1, got %v", e.Y)
}
}
示例13: Update
func (self *esSampler) Update(d interface{}) {
self.lock.Lock()
defer self.lock.Unlock()
u := rand.Float64()
key := math.Pow(u, 1.0/self.weight(d))
if self.samples.Len() < self.maxSize {
heap.Push(self.samples, esSampleItem{
data: d,
key: key,
})
return
}
s := *(self.samples)
min := s[0]
// The key of the new item is larger than a key in existing item.
// Add this new item.
if key > min.key {
heap.Pop(self.samples)
heap.Push(self.samples, esSampleItem{
data: d,
key: key,
})
}
}
示例14: createTreeFromFrequencies
func createTreeFromFrequencies(frequencies []uint, sizes_ []byte, ranks []byte) error {
// Create Huffman tree of (present) symbols
queue := make(HuffmanPriorityQueue, 0)
for i := range ranks {
heap.Push(&queue, &HuffmanNode{symbol: ranks[i], weight: frequencies[ranks[i]]})
}
for queue.Len() > 1 {
// Extract 2 minimum nodes, merge them and enqueue result
lNode := heap.Pop(&queue).(*HuffmanNode)
rNode := heap.Pop(&queue).(*HuffmanNode)
// Setting the symbol is critical to resolve ties during node sorting !
heap.Push(&queue, &HuffmanNode{weight: lNode.weight + rNode.weight, left: lNode, right: rNode, symbol: lNode.symbol})
}
rootNode := heap.Pop(&queue).(*HuffmanNode)
var err error
if len(ranks) == 1 {
sizes_[rootNode.symbol] = byte(1)
} else {
err = fillSizes(rootNode, 0, sizes_)
}
return err
}
示例15: makeFlows
func (fg FlowGenerator) makeFlows(logger chan LogEvent) EventQueue {
lambda := (fg.bandwidth * 1e9 * fg.load) / (fg.cdf.meanFlowSize() * 1500 * 8)
lambda /= 143
creationQueue := make(EventQueue, 0)
defer func() {
creationQueue = nil
}()
heap.Init(&creationQueue)
for i := 0; i < NUM_HOSTS; i++ {
for j := 0; j < NUM_HOSTS; j++ {
if i == j {
continue
}
f := &Flow{Start: 1e6 + (rand.ExpFloat64()/lambda)*1e6, Size: fg.cdf.value(), Source: uint8(i), Dest: uint8(j), LastTime: 0, FinishEvent: nil}
heap.Push(&creationQueue, makeCreationEvent(f))
}
}
eventQueue := make(EventQueue, 0)
for uint(len(eventQueue)) < fg.numFlows {
ev := heap.Pop(&creationQueue).(*Event)
logger <- LogEvent{Time: 0, Type: LOG_FLOW_GEN, Flow: ev.Flow}
eventQueue = append(eventQueue, makeArrivalEvent(ev.Flow))
nextTime := ev.Time + (rand.ExpFloat64()/lambda)*1e6
f := &Flow{Start: nextTime, Size: fg.cdf.value(), Source: ev.Flow.Source, Dest: ev.Flow.Dest, LastTime: 0, FinishEvent: nil}
heap.Push(&creationQueue, makeCreationEvent(f))
}
return eventQueue
}