Last active
August 29, 2015 14:09
-
-
Save justinhj/b1e43224a917f281dc93 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Determine if a value is the product of any two numbers in a vector | |
// Converts the array to a stream so it can be consumed lazily | |
// the helper function is recursive but subject to tail call optimization | |
def prod(in: Array[Int], v: Int): Boolean = { | |
def helper(in: Stream[Int], v: Int, found: Map[Int, Int]): Boolean = in match { | |
case x #:: xs => { | |
val r = v / x | |
if(r * x != v) helper(xs, v, found) | |
else if(found.contains(x)) true | |
else helper(xs, v, found + (r -> x)) | |
} | |
case _ => false | |
} | |
helper(in.toStream, v, Map()) | |
} | |
// (1 to 10).map(n => prod(sample, n)) //> res3: scala.collection.immutable.IndexedSeq[Boolean] = Vector(false, false, | |
//| false, false, false, true, false, true, false, true) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment