Created
December 25, 2014 22:57
-
-
Save bartosz-witkowski/455323c0dc7d3ff5e06c to your computer and use it in GitHub Desktop.
Bounded int queue POC
This file contains 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
package fsp | |
import scala.annotation.tailrec | |
class OhGodWhatHaveIDoneQueue[A]( | |
val min: Int, | |
val _0: List[A], | |
val _1: List[A], | |
val _2: List[A], | |
val _3: List[A]) { | |
def enqueue(priority: Int, a: A): OhGodWhatHaveIDoneQueue[A] = { | |
priority match { | |
case 0 => new OhGodWhatHaveIDoneQueue(Math.min(min, 0), a :: _0, _1, _2, _3) | |
case 1 => new OhGodWhatHaveIDoneQueue(Math.min(min, 1), _0, a :: _1, _2, _3) | |
case 2 => new OhGodWhatHaveIDoneQueue(Math.min(min, 2), _0, _1, a :: _2, _3) | |
case 3 => new OhGodWhatHaveIDoneQueue(Math.min(min, 3), _0, _1, _2, a :: _3) | |
case x => this | |
} | |
} | |
def dequeue: Option[(A, OhGodWhatHaveIDoneQueue[A])] = min match { | |
case 0 => | |
val a = _0.head | |
val new0 = _0.tail | |
val newMin = if (new0.isEmpty) { | |
findMin(1) | |
} else { | |
0 | |
} | |
Some((a, new OhGodWhatHaveIDoneQueue(newMin, new0, _1, _2, _3))) | |
case 1 => | |
val a = _1.head | |
val new1 = _1.tail | |
val newMin = if (new1.isEmpty) { | |
findMin(2) | |
} else { | |
1 | |
} | |
Some((a, new OhGodWhatHaveIDoneQueue(newMin, _0, new1, _2, _3))) | |
case 2 => | |
val a = _2.head | |
val new2 = _2.tail | |
val newMin = if (new2.isEmpty) { | |
findMin(3) | |
} else { | |
2 | |
} | |
Some((a, new OhGodWhatHaveIDoneQueue(newMin, _0, _1, new2, _3))) | |
case 3 => | |
val a = _3.head | |
val new3 = _3.tail | |
val newMin = if (new3.isEmpty) { | |
findMin(3) | |
} else { | |
3 | |
} | |
Some((a, new OhGodWhatHaveIDoneQueue(newMin, _0, _1, _2, new3))) | |
case x => None | |
} | |
@tailrec | |
private def findMin(i: Int): Int = i match { | |
case 1 => if (_1.isEmpty) findMin(2) else 1 | |
case 2 => if (_2.isEmpty) findMin(3) else 2 | |
case 3 => if (_2.isEmpty) findMin(4) else 3 | |
case x => 4 | |
} | |
} | |
object OhGodWhatHaveIDoneQueue { | |
def empty[A] = new OhGodWhatHaveIDoneQueue(4, List.empty[A], List.empty[A], List.empty[A], List.empty[A]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment