Skip to content

Commit e8687e0

Browse files
committed
Adds PriorityQueue
1 parent e6bf4c4 commit e8687e0

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

Assets/Scripts/PriorityQueue.cs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
using UnityEngine;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
5+
public class PriorityQueue< KeyType, PriorityType > where PriorityType : System.IComparable
6+
{
7+
struct Element< SubClassKeyType, SubClassPriorityType > where SubClassPriorityType : System.IComparable
8+
{
9+
public SubClassKeyType key;
10+
public SubClassPriorityType priority;
11+
12+
public Element( SubClassKeyType key, SubClassPriorityType priority )
13+
{
14+
this.key = key;
15+
this.priority = priority;
16+
}
17+
}
18+
19+
List< Element<KeyType, PriorityType> > queue = new List< Element<KeyType, PriorityType> >();
20+
21+
public void push( KeyType arg_key, PriorityType arg_priority )
22+
{
23+
Element<KeyType, PriorityType> new_elem = new Element<KeyType, PriorityType>( arg_key, arg_priority );
24+
25+
int index = 0;
26+
foreach ( var element in queue )
27+
{
28+
// if my new element's priority is less than than the element in this location
29+
if ( new_elem.priority.CompareTo( element.priority ) < 0 )
30+
{
31+
break;
32+
}
33+
34+
++index;
35+
}
36+
37+
// Insert at the found index
38+
queue.Insert( index, new_elem );
39+
}
40+
41+
public KeyType pop()
42+
{
43+
if ( isEmpty() )
44+
{
45+
throw new UnityException("Attempted to pop off an empty queue");
46+
}
47+
48+
Element<KeyType, PriorityType> top = queue[ 0 ];
49+
50+
queue.RemoveAt( 0 );
51+
52+
return top.key;
53+
}
54+
55+
public bool isEmpty()
56+
{
57+
return queue.Count == 0;
58+
}
59+
}

Assets/Scripts/PriorityQueue.cs.meta

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)