Created
April 5, 2012 14:29
-
-
Save raymondtay/2311464 to your computer and use it in GitHub Desktop.
Hash-based search
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
// Sample implementation of a Hash-based search | |
// from a lazy sequence e.g. Streams in Scala | |
// @author Raymond Tay | |
// @date 5 April 2012 | |
import collection.mutable._ | |
object LazyHashSearch { | |
private[LazyHashSearch] var map = Map.empty[Int, List[Int]] | |
// Pass in the Stream's iterator so that the values | |
// can be hashed into the data structure | |
def load(iter: Iterator[Int]) : Unit = { | |
// pull all values from the iterator and find the | |
// bin to hash it to | |
while( iter.hasNext ) { | |
val a : Int = iter.next | |
// we're supposed to hash 'a' and bin it but since we're | |
// already at the 'bottom' of the types...well | |
if (! map.contains(a) ) map = map + (a -> List(a)) | |
if ( map.contains(a) ) map + (a -> map.get(a).get.::(a) ) | |
// if ( map.contains(a) ) map + (a, (a :: map.get(a).get) ) | |
} | |
} | |
def search(v: Int) : Boolean = { | |
if ( !map.contains(v) ) false | |
true | |
} | |
def main(args: Array[String]) = { | |
val iS = Stream.iterate(1, 10000){_ + 1} // generate a lazy list {1, 2, ... , 10000} | |
load(iS.iterator) | |
println( search(5555) ) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment