本文整理汇总了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
}
示例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
}
示例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()
}
示例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
}
示例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())
}
}
}
示例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")
}
}
}
示例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
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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)
}
}
}
}
}
示例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
}
}
}
示例15: heapSort
func heapSort(a sort.Interface) {
helper := HeapHelper{a, a.Len()}
heap.Init(&helper)
for helper.length > 0 {
heap.Pop(&helper)
}
}