Skip to content

Instantly share code, notes, and snippets.

@TGRyu
Last active September 25, 2020 12:52
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 TGRyu/e9f70c8e1c72af6a95f42a0eb6fa2696 to your computer and use it in GitHub Desktop.
Save TGRyu/e9f70c8e1c72af6a95f42a0eb6fa2696 to your computer and use it in GitHub Desktop.
ch05_BoundedSet
package ch05
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()
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)
}
package ch05
import org.scalatest.funsuite.AnyFunSuite
import scala.collection.immutable.Queue
class BoundedSetTests extends AnyFunSuite{
test("testSingleElement" ){
val set = BoundedSet[Int](Queue.empty, 3)
val set1 = set.add(1)
assert(set1.contains(1) == true)
}
test("testRepeatedElement" ){
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("testOverflowKeepsSecond" ){
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("testOverflowRemovesOldest" ){
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("testOverflowKeepsNewest" ){
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("testRenewal" ){
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