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


Golang heap.Init函數代碼示例

本文整理匯總了Golang中container/heap.Init函數的典型用法代碼示例。如果您正苦於以下問題:Golang Init函數的具體用法?Golang Init怎麽用?Golang Init使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Init函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: dijkstra

// Graph Int -> ()
// computes the shortest path to all elements in Graph g from node n
func (g Graph) dijkstra(n int) []int {
	maxIndex := len(g)
	if maxIndex < 1 {
		return make([]int, 0)
	} //set all Node distance to maxInt
	for i := 0; i < len(g); i++ {
		g[i].distance = 0x3f3f3f3f
		g[i].index = i
	}
	//initialize heap
	heap.Init(&g)
	//set starting Node distance to 0
	g.update(g[n-1], 0)
	heap.Init(&g)
	for len(g) > 1 {
		node := heap.Pop(&g).(*Node)
		node.explored = true
		for _, edge := range node.edges {
			if !edge.node.explored {
				g.update(edge.node, (edge.length + node.distance))
			}
		}
	}
	g = g[:maxIndex]
	values := make([]int, len(g))
	for _, v := range g {
		values[v.name-1] = v.distance
	}
	return values
}
開發者ID:JSoddy,項目名稱:goplay,代碼行數:32,代碼來源:dijkstra.go

示例2: Dijkstra

// Dijkstra returns the shortest path using Dijkstra algorithm with a min-priority queue.
// This algorithm does not work with negative weight edges.
// (http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
//
//	1  function Dijkstra(Graph, source):
//	2      dist[source] ← 0                      // Initialization
//	3      for each vertex v in Graph:
//	4          if v ≠ source
//	5              dist[v] ← infinity            // Unknown distance from source to v
//	6              prev[v] ← undefined           // Predecessor of v
//	7          end if
//	8          Q.add_with_priority(v, dist[v])
//	9      end for
//	10
//	11     while Q is not empty:               // The main loop
//	12         u ← Q.extract_min()            // Remove and return best vertex
//	13         for each neighbor v of u:
//	14             alt = dist[u] + length(u, v)
//	15             if alt < dist[v]
//	16                 dist[v] ← alt
//	17                 prev[v] ← u
//	18                 Q.decrease_priority(v, alt)
//	19             end if
//	20         end for
//	21     end while
//	22     return prev[]
//
func (d *Data) Dijkstra(src, dst *Node) ([]*Node, map[*Node]float32) {

	mapToDistance := make(map[*Node]float32)
	mapToDistance[src] = 0.0

	minHeap := &nodeDistanceHeap{}

	// initialize mapToDistance
	for nd := range d.NodeMap {
		if nd != src {
			mapToDistance[nd] = 2147483646.0
		}
		ndd := nodeDistance{}
		ndd.node = nd
		ndd.distance = mapToDistance[nd]
		heap.Push(minHeap, ndd)
	}

	mapToPrevID := make(map[string]string)
	heap.Init(minHeap)

	for minHeap.Len() != 0 {
		elem := heap.Pop(minHeap)
		for ov, weight := range elem.(nodeDistance).node.WeightTo {
			if mapToDistance[ov] > mapToDistance[elem.(nodeDistance).node]+weight {
				mapToDistance[ov] = mapToDistance[elem.(nodeDistance).node] + weight
				minHeap.updateDistance(ov, mapToDistance[elem.(nodeDistance).node]+weight)
				heap.Init(minHeap)

				mapToPrevID[ov.ID] = elem.(nodeDistance).node.ID
			}
		}
		for iv, weight := range elem.(nodeDistance).node.WeightTo {
			if mapToDistance[iv] > mapToDistance[elem.(nodeDistance).node]+weight {
				mapToDistance[iv] = mapToDistance[elem.(nodeDistance).node] + weight
				minHeap.updateDistance(iv, mapToDistance[elem.(nodeDistance).node]+weight)
				heap.Init(minHeap)

				mapToPrevID[iv.ID] = elem.(nodeDistance).node.ID
			}
		}
	}

	pathSlice := []*Node{dst}
	id := dst.ID
	for mapToPrevID[id] != src.ID {
		prevID := mapToPrevID[id]
		id = prevID
		copied := make([]*Node, len(pathSlice)+1) // push front
		copied[0] = d.GetNodeByID(prevID)
		copy(copied[1:], pathSlice)
		pathSlice = copied
	}
	copied := make([]*Node, len(pathSlice)+1) // push front
	copied[0] = d.GetNodeByID(src.ID)
	copy(copied[1:], pathSlice)
	pathSlice = copied

	return pathSlice, mapToDistance
}
開發者ID:hsavit1,項目名稱:goraph,代碼行數:87,代碼來源:dijkstra_heap.go

示例3: main

func main() {

	//創建一個heap
	h := &Heap{}

	heap.Init(h)
	//向heap中插入元素
	h.Push(5)
	h.Push(2)
	h.Push(1)
	h.Push(8)
	h.Push(4)
	h.Push(6)
	h.Push(2)

	//輸出heap中的元素,相當於一個數組,原始數組
	fmt.Println(h)

	//這裏必須要reheapify,建立好堆了
	heap.Init(h)

	//小頂堆對應的元素在數組中的位置
	fmt.Println(h)

	//移除下標為5的元素,下標從0開始
	h.Remove(5)

	//按照堆的形式輸出
	for h.Len() > 0 {
		fmt.Printf("%d ", heap.Pop(h))
	}
	fmt.Println()
}
開發者ID:quchunguang,項目名稱:test,代碼行數:33,代碼來源:testheap.go

示例4: docAtATime

func docAtATime(q []*Term, k int) []*Result {
	results := &ResultHeap{}
	terms := &TermHeap{}
	heap.Init(results)
	heap.Init(terms)
	for i := 0; i < k; i++ {
		heap.Push(results, &Result{0, 0})
	}
	for i := 0; i < len(q); i++ {
		nextDoc := nextDoc(q[i], 0)
		if nextDoc != nil {
			heap.Push(terms, &TermNextDoc{term: q[i], nextDoc: nextDoc})
		}
	}

	var term *TermNextDoc
	var d int
	var score float64
	var nDoc *Document
	var res *Result
	popped := false
	for len(*terms) > 0 {
		popped = false
		term = heap.Pop(terms).(*TermNextDoc)
		d = term.nextDoc.docId
		score = 0.0

		for d == term.nextDoc.docId {
			score += BM25(term.term, term.nextDoc)
			nDoc = nextDoc(term.term, d)
			if nDoc != nil {
				heap.Push(terms, &TermNextDoc{term: term.term, nextDoc: nDoc})
			}

			if len(*terms) > 0 {
				term = heap.Pop(terms).(*TermNextDoc)
				popped = true
			} else {
				break
			}
		}
		if popped {
			heap.Push(terms, term)
		}
		if score > 0.0 {
			res = &Result{doc: d, score: score}
			results.PushGreater(res)
		}
	}

	sortedResults := make([]*Result, (*results).Len())
	for i := len(sortedResults) - 1; i >= 0; i-- {
		sortedResults[i] = heap.Pop(results).(*Result)
	}
	return sortedResults
}
開發者ID:s1na,項目名稱:fetch,代碼行數:56,代碼來源:retrieve.go

示例5: Handler

func (s *serverHeap) Handler() {
	var rec *heapCommand

	ticker := time.Tick(30 * 1000000000)
	for {
		select {
		case rec = <-s.serverChan:
			if rec.command == 0 {
				s.vec.Push(rec.server)
				rec.retChan <- &heapCommand{}
			}
			if rec.command == 1 {
				rec.retChan <- &heapCommand{1, s.vec.Pop(), nil}
			}
			if rec.command == 2 {
				deadServer := rec.server.(*server)
				//find the server to remove
				for cnt := 0; cnt < s.vec.Len(); cnt++ {

					testserv := s.vec.At(cnt).(*server)
					if testserv.id == deadServer.id {
						log.Printf("master: heap Handler: found server %d to delete\n", deadServer.id)

						//find each chunk to modify
						for cnt1 := 0; cnt1 < testserv.chunks.Len(); cnt1++ {

							tempchunk := testserv.chunks.At(cnt1).(*chunk)

							//find the server to remove from EACH CHUNK LIST
							for cnt2 := 0; cnt2 < tempchunk.servers.Len(); cnt2++ {

								tempserv := tempchunk.servers.At(cnt2).(*server)
								if tempserv.id == deadServer.id {
									tempchunk.servers.Delete(cnt2)
								}
							}
						}
						prevCnt := s.vec.Len()
						s.vec.Delete(cnt)
						log.Printf("master: heap Handler: prev vec count %d, now %d\n", prevCnt, s.vec.Len())
						break
					}
				}
				heap.Init(s)
				rec.retChan <- &heapCommand{}
			}
		case <-ticker:
			log.Printf("master: scheduled reheap\n")
			log.Printf("BEFORE \n %s \n", s.printPresent())
			heap.Init(s)
			log.Printf("AFTER  \n %s \n", s.printPresent())
		}
	}
}
開發者ID:alangenfeld,項目名稱:cs639,代碼行數:54,代碼來源:serverHeap.go

示例6: solve

func solve(r *os.File, w *os.File) {
	reader := bufio.NewReader(r)

	count := int(nextNumber(reader))
	minHeap := &MinHeap{}
	maxHeap := &MaxHeap{}

	heap.Init(minHeap)
	heap.Init(maxHeap)

	var median float64

	for i := 0; i < count; i++ {
		num := int64(nextNumber(reader))

		// Push on correct heap
		if 2 == i && maxHeap.Root() > minHeap.Root() {
			min := heap.Pop(minHeap)
			max := heap.Pop(maxHeap)
			heap.Push(minHeap, max)
			heap.Push(maxHeap, min)
		}
		if minHeap.Len() == 0 {
			heap.Push(minHeap, num)
		} else if (maxHeap.Len() == 0) || (num < maxHeap.Root()) {
			heap.Push(maxHeap, num)
		} else {
			heap.Push(minHeap, num)
		}

		// Rebalance
		if minHeap.Len()-maxHeap.Len() > 1 {
			heap.Push(maxHeap, heap.Pop(minHeap))
		} else if maxHeap.Len()-maxHeap.Len() > 1 {
			heap.Push(minHeap, heap.Pop(maxHeap))
		}

		if maxHeap.Len() == minHeap.Len() {
			median = (float64(maxHeap.Root()) + float64(minHeap.Root())) / 2
		} else if maxHeap.Len() > minHeap.Len() {
			median = float64(maxHeap.Root())
		} else {
			median = float64(minHeap.Root())
		}

		w.WriteString(strconv.FormatFloat(median, 'f', 1, 32))

		if (i + 1) < count {
			w.WriteString("\n")
		}
	}
}
開發者ID:lanej,項目名稱:gonuts,代碼行數:52,代碼來源:solution.go

示例7: NewStorePool

// NewStorePool creates a StorePool and registers the store updating callback
// with gossip.
func NewStorePool(
	ambient log.AmbientContext,
	g *gossip.Gossip,
	clock *hlc.Clock,
	rpcContext *rpc.Context,
	timeUntilStoreDead time.Duration,
	stopper *stop.Stopper,
	deterministic bool,
) *StorePool {
	sp := &StorePool{
		AmbientContext:     ambient,
		clock:              clock,
		timeUntilStoreDead: timeUntilStoreDead,
		rpcContext:         rpcContext,
		failedReservationsTimeout: envutil.EnvOrDefaultDuration("COCKROACH_FAILED_RESERVATION_TIMEOUT",
			defaultFailedReservationsTimeout),
		declinedReservationsTimeout: envutil.EnvOrDefaultDuration("COCKROACH_DECLINED_RESERVATION_TIMEOUT",
			defaultDeclinedReservationsTimeout),
		resolver:      GossipAddressResolver(g),
		deterministic: deterministic,
	}
	sp.mu.storeDetails = make(map[roachpb.StoreID]*storeDetail)
	heap.Init(&sp.mu.queue)
	sp.mu.nodeLocalities = make(map[roachpb.NodeID]roachpb.Locality)
	storeRegex := gossip.MakePrefixPattern(gossip.KeyStorePrefix)
	g.RegisterCallback(storeRegex, sp.storeGossipUpdate)
	deadReplicasRegex := gossip.MakePrefixPattern(gossip.KeyDeadReplicasPrefix)
	g.RegisterCallback(deadReplicasRegex, sp.deadReplicasGossipUpdate)
	sp.start(stopper)

	return sp
}
開發者ID:nvanbenschoten,項目名稱:cockroach,代碼行數:34,代碼來源:store_pool.go

示例8: TestEvictAndReplaceWithMedian

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

	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, 6)

	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)
	c.Check(heap.Pop(&q), utility.ValueEquals, 7.0)
}
開發者ID:grobie,項目名稱:golang_instrumentation,代碼行數:27,代碼來源:eviction_test.go

示例9: TestEvictAndReplaceWithFirstMode

func (s *S) TestEvictAndReplaceWithFirstMode(c *C) {
	q := make(utility.PriorityQueue, 0, 10)
	heap.Init(&q)
	e := EvictAndReplaceWith(5, maths.FirstMode)

	for i := 0; i < 10; i++ {
		heap.Push(&q, &utility.Item{
			Value:    float64(i),
			Priority: int64(i),
		})
	}

	c.Check(q, HasLen, 10)

	e(&q)

	c.Check(q, HasLen, 6)

	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)
	c.Check(heap.Pop(&q), utility.ValueEquals, 9.0)
}
開發者ID:grobie,項目名稱:golang_instrumentation,代碼行數:25,代碼來源:eviction_test.go

示例10: Clear

// Clear removes all the entries in the cache
func (c *Cache) Clear() {
	c.lock.Lock()
	defer c.lock.Unlock()

	c.entries = make(entries, c.capacity)
	heap.Init(&c.entriesH)
}
開發者ID:rahulxkrishna,項目名稱:weave,代碼行數:8,代碼來源:cache.go

示例11: sandboxAdd

func (c *controller) sandboxAdd(key string, create bool, ep *endpoint) (sandbox.Sandbox, error) {
	c.Lock()
	sData, ok := c.sandboxes[key]
	c.Unlock()

	if !ok {
		sb, err := sandbox.NewSandbox(key, create)
		if err != nil {
			return nil, fmt.Errorf("failed to create new sandbox: %v", err)
		}

		sData = &sandboxData{
			sbox:      sb,
			endpoints: epHeap{},
		}

		heap.Init(&sData.endpoints)
		c.Lock()
		c.sandboxes[key] = sData
		c.Unlock()
	}

	if err := sData.addEndpoint(ep); err != nil {
		return nil, err
	}

	return sData.sandbox(), nil
}
開發者ID:souravbh,項目名稱:lattice-release,代碼行數:28,代碼來源:sandboxdata.go

示例12: DialWithTimeout

// goroutine safe
func DialWithTimeout(url string, sessionNum int, dialTimeout time.Duration, timeout time.Duration) (*DialContext, error) {
	if sessionNum <= 0 {
		sessionNum = 100
		log.Release("invalid sessionNum, reset to %v", sessionNum)
	}

	s, err := mgo.DialWithTimeout(url, dialTimeout)
	if err != nil {
		return nil, err
	}
	s.SetSyncTimeout(timeout)
	s.SetSocketTimeout(timeout)

	c := new(DialContext)

	// sessions
	c.sessions = make(SessionHeap, sessionNum)
	c.sessions[0] = &Session{s, 0, 0}
	for i := 1; i < sessionNum; i++ {
		c.sessions[i] = &Session{s.New(), 0, i}
	}
	heap.Init(&c.sessions)

	return c, nil
}
開發者ID:Ribosome2,項目名稱:leaf,代碼行數:26,代碼來源:mongodb.go

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

示例14: Run

// Run is the block's main loop. Here we listen on the different channels we set up.
func (b *Queue) Run() {
	pq := &PriorityQueue{}
	heap.Init(pq)
	for {
		select {
		case <-b.quit:
			// quit the block
			return
		case msg := <-b.inPush:
			queueMessage := &PQMessage{
				val: msg,
				t:   time.Now(),
			}
			heap.Push(pq, queueMessage)
		case <-b.inPop:
			if len(*pq) == 0 {
				continue
			}
			msg := heap.Pop(pq).(*PQMessage).val
			b.out <- msg
		case MsgChan := <-b.queryPop:
			var msg interface{}
			if len(*pq) > 0 {
				msg = heap.Pop(pq).(*PQMessage).val
			}
			MsgChan <- msg
		case MsgChan := <-b.queryPeek:
			var msg interface{}
			if len(*pq) > 0 {
				msg = pq.Peek().(*PQMessage).val
			}
			MsgChan <- msg
		}
	}
}
開發者ID:jprobinson,項目名稱:streamtools,代碼行數:36,代碼來源:queue.go

示例15: heapSort

func heapSort(a sort.Interface) {
	helper := HeapHelper{a, a.Len()}
	heap.Init(&helper)
	for helper.length > 0 {
		heap.Pop(&helper)
	}
}
開發者ID:travis1230,項目名稱:RosettaCodeData,代碼行數:7,代碼來源:sorting-algorithms-heapsort-1.go


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