/
PriorityQueue.cs
150 lines (131 loc) · 3.26 KB
/
PriorityQueue.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PriorityQueue<T>where T : new()
{
private List<T>queueImpl;
public Comparison<T>comparator;
public PriorityQueue()
{
queueImpl = new List<T>();
// blank initial because 0 index shouldn't be used.
queueImpl.Add(new T());
}
public int Count
{
get
{
return queueImpl.Count - 1;
}
}
public T at(int index)
{
if (index >= 0 && index < Count)
{
return queueImpl[index + 1];
}
else
{
return default;
}
}
public void Clear()
{
queueImpl.Clear();
// blank initial because 0 index shouldn't be used.
queueImpl.Add(new T());
}
public bool Empty()
{
return queueImpl.Count <= 1;
}
public T Top
{
get
{
return queueImpl[1];
}
}
public void Add(T item)
{
queueImpl.Add(item);
BubbleUp(queueImpl.Count - 1);
}
public bool Remove(T item)
{
int ind = queueImpl.IndexOf(item);
if (ind > 0) {
int last = queueImpl.Count - 1;
queueImpl[ind] = queueImpl[last];
queueImpl.RemoveAt(last);
BubbleDown(ind);
if (queueImpl.Count == 0) { Debug.LogError("Woops, we're down to zero"); }
return true;
} else {
return false;
}
}
public bool Remove(Predicate<T>matchPred)
{
T item = queueImpl.Find(matchPred);
return Remove(item);
}
public T Find(Predicate<T>matchPred)
{
return queueImpl.Find(matchPred);
}
public bool Contains(T item)
{
return queueImpl.Contains(item);
}
public void Update(T item)
{
int ind = queueImpl.IndexOf(item);
if (ind > 0) {
// One of these two will be a noop
BubbleUp(ind);
BubbleDown(ind);
}
}
private void BubbleUp(int ind)
{
while (ind > 1) {
int parent = ind / 2;
if (comparator(queueImpl[ind], queueImpl[parent]) < 0) {
T tmp = queueImpl[parent];
queueImpl[parent] = queueImpl[ind];
queueImpl[ind] = tmp;
ind = parent;
} else {
break;
}
}
}
private void BubbleDown(int ind)
{
if (ind == 0) {
Debug.LogError("Bubbling an invalid index");
return;
}
while (ind < queueImpl.Count) {
int left = ind * 2;
int right = ind * 2 + 1;
if (left >= queueImpl.Count) { break; }
int minInd;
if (right >= queueImpl.Count || comparator(queueImpl[left], queueImpl[right]) < 0) {
minInd = left;
} else {
minInd = right;
}
if (comparator(queueImpl[minInd], queueImpl[ind]) < 0) {
T tmp = queueImpl[minInd];
queueImpl[minInd] = queueImpl[ind];
queueImpl[ind] = tmp;
ind = minInd;
} else {
break;
}
}
}
}