当前位置: 首页>>代码示例>>Golang>>正文


Golang heap.Pop函数代码示例

本文整理汇总了Golang中container/heap.Pop函数的典型用法代码示例。如果您正苦于以下问题:Golang Pop函数的具体用法?Golang Pop怎么用?Golang Pop使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Pop函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestPush

func TestPush(t *testing.T) {
	h := &uint64Heap{}
	heap.Init(h)

	e := elem{val: 5}
	heap.Push(h, e)
	e.val = 3
	heap.Push(h, e)
	e.val = 4
	heap.Push(h, e)

	require.Equal(t, h.Len(), 3)
	require.EqualValues(t, (*h)[0].val, 3)

	e.val = 10
	(*h)[0] = e
	heap.Fix(h, 0)
	require.EqualValues(t, (*h)[0].val, 4)

	e.val = 11
	(*h)[0] = e
	heap.Fix(h, 0)
	require.EqualValues(t, (*h)[0].val, 5)

	e = heap.Pop(h).(elem)
	require.EqualValues(t, e.val, 5)

	e = heap.Pop(h).(elem)
	require.EqualValues(t, e.val, 10)

	e = heap.Pop(h).(elem)
	require.EqualValues(t, e.val, 11)

	require.Equal(t, h.Len(), 0)
}
开发者ID:dgraph-io,项目名称:dgraph,代码行数:35,代码来源:heap_test.go

示例2: main

func main() {
	in, _ := os.Open("10954.in")
	defer in.Close()
	out, _ := os.Create("10954.out")
	defer out.Close()

	var n, num int
	for {
		if fmt.Fscanf(in, "%d", &n); n == 0 {
			break
		}
		pq := make(priorityQueue, n)
		for i := range pq {
			fmt.Fscanf(in, "%d", &num)
			pq[i] = &item{num}
		}
		heap.Init(&pq)
		total := 0
		for pq.Len() > 1 {
			n1 := heap.Pop(&pq).(*item)
			n2 := heap.Pop(&pq).(*item)
			total += n1.value + n2.value
			heap.Push(&pq, &item{n1.value + n2.value})
		}
		fmt.Fprintln(out, total)
	}
}
开发者ID:codingsince1985,项目名称:UVa,代码行数:27,代码来源:10954.go

示例3: TestQueue

func TestQueue(t *testing.T) {
	q := NewImageCache()
	heap.Push(q, NewCacheItem("item1", nil))
	time.Sleep(time.Duration(1) * time.Millisecond)
	heap.Push(q, NewCacheItem("item2", nil))
	time.Sleep(time.Duration(1) * time.Millisecond)
	heap.Push(q, NewCacheItem("item3", nil))
	time.Sleep(time.Duration(1) * time.Millisecond)
	heap.Push(q, NewCacheItem("item4", nil))
	time.Sleep(time.Duration(1) * time.Millisecond)
	t.Log(q.GetPaths())

	q.Update("item1")
	t.Log(q.GetPaths())

	t.Log(q.Top().path)
	heap.Pop(q)
	t.Log(q.GetPaths())

	t.Log(q.Top().path)
	heap.Pop(q)
	t.Log(q.GetPaths())

	t.Log(q.Top().path)
	heap.Pop(q)
	t.Log(q.GetPaths())
}
开发者ID:vectorjohn,项目名称:imgserv,代码行数:27,代码来源:main_test.go

示例4: Harvest

// Retorna a arvore
func Harvest(freqMap map[string]int) *tree.Node {
	// Primeiro a gente cria a nossa priorityqueue a partir do dicionario de frequencias
	hh := huffmanHeap.New(freqMap)

	for {
		// Caso a heap contenha um unico elemento retornamos ela
		if hh.Len() == 1 {
			return heap.Pop(&hh).(*huffmanHeap.Item).Node
		}

		// Caso contrario pegamos os dois elementos do topo
		r, ok1 := heap.Pop(&hh).(*huffmanHeap.Item)
		l, ok2 := heap.Pop(&hh).(*huffmanHeap.Item)
		if !ok1 || !ok2 {
			panic(errors.New("Element was not of type huffmanHeap.Item"))
		}

		//E criamos uma "arvore" intermediaria com eles
		newItem := &huffmanHeap.Item{
			Node:      tree.New("", r.Node, l.Node),
			Frequency: r.Frequency + l.Frequency,
		}
		// Adicionando em seguida ao
		heap.Push(&hh, newItem)
	}
}
开发者ID:caiquelira,项目名称:Huffman,代码行数:27,代码来源:gardener.go

示例5: makeTreeFromNodeSlice

// makeTreeFromNodeSlice makes a tree from a slice of huffNodes, with the
// lowest-count nodes going farthest from the root. Returns a non-nil error
// on failure, nil error otherwise. Returns the created tree. If nodes is empty,
// returns an error.
func makeTreeFromNodeSlice(nodes []*huffNode) (t *huffNode, err error) {
	if len(nodes) == 0 {
		return nil, errors.New("Too few elements!")
	}
	// We're going to put the nodes in a heap, with low-ness determined
	// by the nodes' counts.
	nh := &nodeHeap{}
	heap.Init(nh)
	for _, node := range nodes {
		heap.Push(nh, node)
	}

	// Now, we're going to do the following:
	//
	// Until there's only one node in the heap:
	// 		Remove the lowest-count two nodes
	// 		Make a new node with those two as children, whose count is the
	//			sum of its childrens' counts
	//		Add that new node to the heap
	//
	// This will create an optimally-balanced tree, based on byte counts. For
	// more information, see http://en.wikipedia.org/wiki/Huffman_coding.
	for nh.Len() > 1 {
		nodeOne := heap.Pop(nh).(*huffNode)
		nodeTwo := heap.Pop(nh).(*huffNode)
		newNode := &huffNode{char: 1,
			count: nodeOne.count + nodeTwo.count,
			left:  nodeOne,
			right: nodeTwo}
		heap.Push(nh, newNode)
	}

	// Great, now there's only one node and it's the root of the tree!
	return heap.Pop(nh).(*huffNode), nil
}
开发者ID:BenedictEggers,项目名称:huffman,代码行数:39,代码来源:huffTree.go

示例6: nearestNeighbours

// This helper function finds the k nearest neighbours of target in items. It's
// slower than the VPTree, but its correctness is easy to verify, so we can
// test the VPTree against it.
func nearestNeighbours(target uint64, items []Item, k int) (coords []Item, distances []float64) {
	pq := &priorityQueue{}

	// Push all items onto a heap
	for _, v := range items {
		d := hamming(v.Sig, target)
		heap.Push(pq, &heapItem{v, d})
	}

	// Pop all but the k smallest items
	for pq.Len() > k {
		heap.Pop(pq)
	}

	// Extract the k smallest items and distances
	for pq.Len() > 0 {
		hi := heap.Pop(pq)
		coords = append(coords, hi.(*heapItem).Item)
		distances = append(distances, hi.(*heapItem).Dist)
	}

	// Reverse coords and distances, because we popped them from the heap
	// in large-to-small order
	for i, j := 0, len(coords)-1; i < j; i, j = i+1, j-1 {
		coords[i], coords[j] = coords[j], coords[i]
		distances[i], distances[j] = distances[j], distances[i]
	}

	return
}
开发者ID:TPNguyen,项目名称:go-simstore,代码行数:33,代码来源:vptree_test.go

示例7: TestEvictOldest

func (s *S) TestEvictOldest(c *C) {
	q := make(utility.PriorityQueue, 0, 10)
	heap.Init(&q)
	var e EvictionPolicy = EvictOldest(5)

	for i := 0; i < 10; i++ {
		var item utility.Item = utility.Item{
			Value:    float64(i),
			Priority: int64(i),
		}

		heap.Push(&q, &item)
	}

	c.Check(q, HasLen, 10)

	e(&q)

	c.Check(q, HasLen, 5)

	c.Check(heap.Pop(&q), utility.ValueEquals, 4.0)
	c.Check(heap.Pop(&q), utility.ValueEquals, 3.0)
	c.Check(heap.Pop(&q), utility.ValueEquals, 2.0)
	c.Check(heap.Pop(&q), utility.ValueEquals, 1.0)
	c.Check(heap.Pop(&q), utility.ValueEquals, 0.0)
}
开发者ID:grobie,项目名称:golang_instrumentation,代码行数:26,代码来源:eviction_test.go

示例8: DeleteDuplicates

// DeleteDuplicates heap sorts a slice and returns a new slice with duplicate
// entries removed.
func DeleteDuplicates(theArray []int) []int {
	// Need to get a mutable copy of the heap
	heapHelper := make(HeapHelper, len(theArray))
	i := 0
	for _, value := range theArray {
		heapHelper[i] = value
		i++
	}
	heap.Init(&heapHelper)

	//  How to do this in-place?
	result := make([]int, 0)

	if len(theArray) > 0 {
		prevElement := heap.Pop(&heapHelper).(int)

		result = append(result, prevElement)

		for heapHelper.Len() > 0 {
			currentElement := heap.Pop(&heapHelper).(int)
			if currentElement != prevElement {
				result = append(result, currentElement)
				prevElement = currentElement
			}
		}
	}
	return result
}
开发者ID:gsdayton98,项目名称:deldupes,代码行数:30,代码来源:delete_dupes.go

示例9: 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

示例10: findMin

func findMin(n, k, a, b, c, r int) int {
	m := []int{a}
	for i := 1; i < k; i++ {
		m = append(m, (b*m[i-1]+c)%r)
	}
	o := make([]int, k)
	copy(o, m)
	sort.Ints(o)
	h := &intHeap{}
	heap.Init(h)
	var x, y int
	for i := 0; i <= k; {
		if y >= k || x < o[y] {
			heap.Push(h, x)
			x++
			i++
		} else {
			if x == o[y] {
				x++
			}
			y++
		}
	}
	for len(m)+1 < n {
		p := heap.Pop(h).(int)
		if h.notyet(m[len(m)-k]) && notagain(m[len(m)-k+1:len(m)], m[len(m)-k]) {
			heap.Push(h, m[len(m)-k])
		}
		m = append(m, p)
	}
	return heap.Pop(h).(int)
}
开发者ID:nikai3d,项目名称:ce-challenges,代码行数:32,代码来源:find_min.go

示例11: TestPriorityQueue

func TestPriorityQueue(t *testing.T) {
	pq := New()
	heap.Init(pq)
	heap.Push(pq, &Item{Value: "hello3", Priority: 3})
	heap.Push(pq, &Item{Value: "hello1", Priority: 1})
	heap.Push(pq, &Item{Value: "hello8", Priority: 8})

	assert.Equal(t, 3+1+8, pq.PrioritySum())

	item := pq.Peek()
	assert.Equal(t, "hello8", item.(*Item).Value.(string))
	item = pq.Peek()
	assert.Equal(t, "hello8", item.(*Item).Value.(string))

	item = heap.Pop(pq)
	assert.Equal(t, "hello8", item.(*Item).Value.(string))
	assert.Equal(t, 3+1, pq.PrioritySum())

	item = heap.Pop(pq)
	assert.Equal(t, "hello3", item.(*Item).Value.(string))

	item = heap.Pop(pq)
	assert.Equal(t, "hello1", item.(*Item).Value.(string))

	assert.Equal(t, 0, pq.Len())
}
开发者ID:postfix,项目名称:golib-1,代码行数:26,代码来源:pqueue_test.go

示例12: TestJobHeap

func TestJobHeap(t *testing.T) {
	jobs := &JobHeap{}
	heap.Init(jobs)

	job1 := Job{Description: "job 1", Created: time.Now()}
	job2 := Job{Description: "job 2", Created: time.Now()} //, Ctrl: JobControl{JobPriority: 100}}
	job3 := Job{Description: "job 3", Created: time.Now()} //, Ctrl: JobControl{JobPriority: 104}}

	heap.Push(jobs, &job2)
	heap.Push(jobs, &job3)
	heap.Push(jobs, &job1)

	for _, job := range *jobs {
		fmt.Println(job)
	}

	fmt.Println("===")
	fmt.Println(jobs.Peek())

	fmt.Println("---")
	ret1 := heap.Pop(jobs)
	ret2 := heap.Pop(jobs)
	ret3 := heap.Pop(jobs)

	fmt.Println(ret1)
	fmt.Println(ret2)
	fmt.Println(ret3)

}
开发者ID:kmanley,项目名称:golang-grid,代码行数:29,代码来源:job_heap_test.go

示例13: 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

示例14: addMinPathLeft

func addMinPathLeft(graph *m.Graph) {
	dp := &m.DijkstraPrio{}
	heap.Init(dp)
	visited := make(map[*m.Node]bool)
	endNode := graph.EndNode()
	endNode.SetMinPathLeft(0)
	visited[endNode] = true
	for _, edge := range endNode.ToEdges() {
		node := edge.From()
		node.SetMinPathLeft(edge.FastestTime())
		heap.Push(dp, node)
	}
	if dp.Len() > 0 {
		for node := heap.Pop(dp).(*m.Node); dp.Len() > 0; node = heap.Pop(dp).(*m.Node) {
			visited[node] = true
			for _, edge := range node.ToEdges() {
				innerNode := edge.From()
				if !visited[innerNode] {
					innerNode.SetMinPathLeft(edge.FastestTime() + node.MinPathLeft())
					heap.Push(dp, innerNode)
				}
			}
		}
	}
}
开发者ID:hzck,项目名称:speedroute,代码行数:25,代码来源:algorithm.go

示例15: ConsiderWeighted

// ConsiderWeighted lets the sample inspect a new value with a positive given
// weight. A weight of one corresponds to the unweighted reservoir sampling
// algorithm. A nonpositive weight will lead to the item being rejected without
// having been observed. To avoid numerical instabilities, it is advisable to
// stay away from zero and infinity, or more generally from regions in which
// computing x**1/weight may be ill-behaved.
func (rs *WeightedReservoirSample) ConsiderWeighted(value interface{}, weight float64) {
	if weight <= 0 {
		glog.Warningf("reservoir sample received non-positive weight %f", weight)
		return
	}
	h := rs.Heap
	wv := WeightedValue{
		Value: value,
		key:   rs.makeKey(weight),
	}
	if h.Len() < rs.size {
		heap.Push(h, wv)
		if rs.threshold == 0 || wv.key < rs.threshold {
			rs.threshold = wv.key
		}
		return
	}

	if wv.key > rs.threshold {
		// Remove the element with threshold key.
		heap.Pop(h)
		// Add in the new element (which has a higher key).
		heap.Push(h, wv)
		// Update the threshold to reflect the new threshold.
		twv := heap.Pop(h).(WeightedValue)
		rs.threshold = twv.key
		heap.Push(h, twv)
	}
}
开发者ID:josephwinston,项目名称:cockroach,代码行数:35,代码来源:sampling.go


注:本文中的container/heap.Pop函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。