Created
August 25, 2017 09:57
-
-
Save dszakallas/8fc06d465a86f030664f183476a21614 to your computer and use it in GitHub Desktop.
FixedCapacityQueue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.reflect.ClassTag | |
class FixedCapQueue[A: ClassTag](size: Int) { | |
val queue: Array[A] = new Array(size) | |
var start: Int = 0 | |
var end: Int = 0 | |
var empty = size > 0 | |
def take(): A = { | |
if (end == start && empty) throw new Exception("Queue empty") | |
val res = queue(start) | |
queue.update(start, _: A) // let's not hold references | |
start = (start + 1) % size | |
empty = start == end | |
res | |
} | |
def add(elem: A) : Unit = { | |
if (end == start && !empty) throw new Error("Queue full") | |
queue.update(end, elem) | |
end = (end + 1) % size | |
empty = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment