當前位置: 首頁>>代碼示例>>Golang>>正文


Golang heap.Push函數代碼示例

本文整理匯總了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())})
	}
}
開發者ID:postfix,項目名稱:y,代碼行數:25,代碼來源:y.go

示例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)
	}
}
開發者ID:robbiet480,項目名稱:alertmanager,代碼行數:28,代碼來源:manager.go

示例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")
	}
}
開發者ID:steveyen,項目名稱:cbgt,代碼行數:25,代碼來源:scan_test.go

示例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
}
開發者ID:nathankerr,項目名稱:graph,代碼行數:68,代碼來源:graphSearch.go

示例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
}
開發者ID:constabulary,項目名稱:docker-depfile-example,代碼行數:36,代碼來源:msp.go

示例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)
	}
}
開發者ID:qt-luigi,項目名稱:golangcafe,代碼行數:27,代碼來源:heapsample_test.go

示例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++
	}

}
開發者ID:byxorna,項目名稱:moroccron,代碼行數:28,代碼來源:priority_queue_test.go

示例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,
		})
	}
}
開發者ID:rpcastagna,項目名稱:schedulesim,代碼行數:30,代碼來源:simulation.go

示例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])
	}
}
開發者ID:Ropes,項目名稱:Sheave-Bot,代碼行數:25,代碼來源:history_test.go

示例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")
}
開發者ID:gcapell,項目名稱:ai-challenge-2011,代碼行數:32,代碼來源:path2.go

示例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
		}
	}
}
開發者ID:courtf,項目名稱:quant,代碼行數:35,代碼來源:median.go

示例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)
	}
}
開發者ID:kurrik,項目名稱:voronoi,代碼行數:25,代碼來源:voronoi_test.go

示例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,
		})
	}
}
開發者ID:289,項目名稱:kubernetes,代碼行數:28,代碼來源:es.go

示例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
}
開發者ID:rzel,項目名稱:kanzi,代碼行數:28,代碼來源:HuffmanCodec.go

示例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
}
開發者ID:NetSys,項目名稱:ideal-simulator,代碼行數:33,代碼來源:flowgen.go


注:本文中的container/heap.Push函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。