Created
September 25, 2020 12:42
-
-
Save sungkmi/56bd2a907afef3dfe568c0fbe861fb14 to your computer and use it in GitHub Desktop.
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 lascala.sgs.ch5 | |
import scala.collection.immutable.Queue | |
case class BoundedSet[A]( | |
data: Queue[A], | |
capacity: Int, | |
) { | |
def add(elem: A): BoundedSet[A] = { | |
if (elem == null) throw new NullPointerException() | |
else { | |
val index = data.indexOf(elem) | |
val data1 = if (index == -1) data else { | |
val (f, b) = data.splitAt(index) | |
f ++ b.tail | |
} | |
val data2 = if (data1.size == capacity) data1.tail else data1 | |
val data3 = data2.enqueue(elem) | |
BoundedSet(data3, capacity) | |
} | |
} | |
def contains(elem: A): Boolean = data.contains(elem) | |
} |
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 lascala.sgs.ch5 | |
import scala.collection.immutable.Queue | |
class BoundedSetTest extends munit.FunSuite { | |
test("single element") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
assert(set1.contains(1) == true) | |
} | |
test("repeated element") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
val set2 = set1.add(1) | |
val set3 = set2.add(1) | |
val set4 = set3.add(1) | |
assert(set4.contains(1) == true) | |
} | |
test("overflow keeps second") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
val set2 = set1.add(2) | |
val set3 = set2.add(3) | |
val set4 = set3.add(4) | |
assert(set4.contains(2) == true) | |
} | |
test("overflow removes oldist") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
val set2 = set1.add(2) | |
val set3 = set2.add(3) | |
val set4 = set3.add(4) | |
assert(set4.contains(1) == false) | |
} | |
test("overflow keeps newest") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
val set2 = set1.add(2) | |
val set3 = set2.add(3) | |
val set4 = set3.add(4) | |
assert(set4.contains(4) == true) | |
} | |
test("renewal") { | |
val set = BoundedSet[Int](Queue.empty, 3) | |
val set1 = set.add(1) | |
val set2 = set1.add(2) | |
val set3 = set2.add(1) | |
val set4 = set3.add(3) | |
val set5 = set4.add(4) | |
assert(set5.contains(1) == true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment