Skip to content

Instantly share code, notes, and snippets.

@justinhj
Last active August 29, 2015 14:09
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 justinhj/b1e43224a917f281dc93 to your computer and use it in GitHub Desktop.
Save justinhj/b1e43224a917f281dc93 to your computer and use it in GitHub Desktop.
// 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