Skip to content

Instantly share code, notes, and snippets.

@tomatophobia
Created September 25, 2020 12:44
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 tomatophobia/3f1741978ae12a9d173c5d4622caa214 to your computer and use it in GitHub Desktop.
Save tomatophobia/3f1741978ae12a9d173c5d4622caa214 to your computer and use it in GitHub Desktop.
class BoundedSet2[T] {
val data: util.LinkedList[T] = new util.LinkedList[T]()
var capacity: Int = 0
def BoundedSet(capacity: Int) {
this.capacity = capacity;
}
def add(elem: T) {
if (elem==null) throw new NullPointerException()
data.remove(elem);
if (data.size() == capacity) {
data.removeFirst();
}
data.addLast(elem);
}
def contains(elem: T): Boolean = {
data.contains(elem);
}
}
object BoundedSetTestsScala {
val set: BoundedSet[Int] = new BoundedSet[Int](3)
def main(args: Array[String]): Unit = {
testSingleElement
testRepeatedElement
testOverflowKeepsSecond
testOverflowRemovesOldest
testOverflowKeepsNewest
testRenewal
}
def testSingleElement {
set.add(1);
assert(set.contains(1));
}
def testRepeatedElement {
set.add(1);
set.add(1);
set.add(1);
set.add(1);
assert(set.contains(1));
}
def testOverflowKeepsSecond {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
assert(set.contains(2));
}
def testOverflowRemovesOldest {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
assert(!set.contains(1));
}
def testOverflowKeepsNewest {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
assert(set.contains(4));
}
def testRenewal {
set.add(1);
set.add(2);
set.add(1);
set.add(3);
set.add(4);
assert(set.contains(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment