Skip to content

Instantly share code, notes, and snippets.

@dszakallas
Created August 25, 2017 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dszakallas/8fc06d465a86f030664f183476a21614 to your computer and use it in GitHub Desktop.
Save dszakallas/8fc06d465a86f030664f183476a21614 to your computer and use it in GitHub Desktop.
FixedCapacityQueue
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