Created
February 16, 2018 02:08
-
-
Save ASRagab/82411aa5b78a9b06589d79238b15520e to your computer and use it in GitHub Desktop.
Banker's Queue Implementation
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
object queuesBankers { | |
import BankersQueue._ | |
case class BankersQueue[+A](sizeFront: Int, front: Stream[A], sizeRear: Int, rear: Stream[A]) { | |
def enqueue[B >: A](b: B) = | |
check(BankersQueue(sizeFront,front, sizeRear + 1, b #:: rear)) | |
def dequeue = front match { | |
case h #:: t => { | |
val remaining = BankersQueue(sizeFront - 1, t, sizeRear, rear) | |
(h, check(remaining)) | |
} | |
case _ => throw new NoSuchElementException() | |
} | |
} | |
object BankersQueue { | |
def check[A](q: BankersQueue[A]) = { | |
if (q.sizeFront >= q.sizeRear) q | |
else { | |
val newFrontSize = q.sizeFront + q.sizeRear | |
val newFront = q.front ++ q.rear.reverse | |
BankersQueue(newFrontSize, newFront, 0, Stream[A]()) | |
} | |
} | |
} | |
val bq = BankersQueue[Int](0, Stream(), 0, Stream()) | |
.enqueue(1) | |
.enqueue(2) | |
.enqueue(3) | |
.enqueue(4) | |
.enqueue(5) | |
val (next, bq2) = bq.dequeue | |
val (next1, bq3) = bq2.dequeue | |
val bq4 = bq3.enqueue(10) | |
val (next2, bq5) = bq4.dequeue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment