Skip to content

Instantly share code, notes, and snippets.

@colinpollock
Created September 13, 2012 01:50
Show Gist options
  • Save colinpollock/3711345 to your computer and use it in GitHub Desktop.
Save colinpollock/3711345 to your computer and use it in GitHub Desktop.
stupid hashmap
import collection.mutable
case class Pair[A, B](key: A, value: B)
class HMap[K, V](numBuckets: Int) {
val buckets = Seq.fill(numBuckets)(mutable.ListBuffer.empty[Pair[K, V]])
def get(k: K): Option[V] =
buckets(k.hashCode % numBuckets).find(_.key == k).map(_.value)
def apply(k: K): Option[V] = get(k)
def put(k: K, v: V): Unit = {
val pair = Pair(k, v)
val bucket = buckets(k.hashCode % numBuckets)
bucket.indexWhere(_.key == k) match {
case -1 => bucket.append(pair)
case n => bucket(n) = pair
}
}
def size: Int = buckets.map(_.size).sum
def keys: Iterable[K] = buckets.flatMap(_.map(_.key))
def values: Iterable[V] = buckets.flatMap(_.map(_.value))
def toSeq: Seq[(K, V)] = buckets.flatMap(_.map(p => (p.key, p.value)))
def numEmptyBuckets: Int = buckets.count(_.isEmpty)
}
val m = new HMap[Int, Int](10)
assert(m.numEmptyBuckets == 10)
Range(1, 20).foreach(i => m.put(i, i * 11))
m.put(3, 333)
assert(m.size == 19)
assert(m.get(9) == Some(99))
assert(m.get(3) == Some(333))
assert(m.get(30) == None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment