Skip to content

Instantly share code, notes, and snippets.

@rmartinsdepaula
Created February 26, 2023 20:11
Show Gist options
  • Save rmartinsdepaula/e1618e13b540226e647862108a79a0f8 to your computer and use it in GitHub Desktop.
Save rmartinsdepaula/e1618e13b540226e647862108a79a0f8 to your computer and use it in GitHub Desktop.
Return the cache so it is not needed to use mutable map (horrible)
object GridTraveler extends App {
def gridTraveler(r: Int, c: Int, cache: collection.mutable.Map[(Int, Int), Long]): Long = {
cache.get((r, c)) match {
case Some(n) => return n
case None =>
}
cache.get((c, r)) match {
case Some(n) => return n
case None =>
}
if (r <= 0) return 0
if (c <= 0) return 0
if (r == 1 & c == 1) return 1
val result = gridTraveler(r - 1, c, cache) + gridTraveler(r, c - 1, cache) // can't inline because of compiler errors...
cache += ((r, c) -> result)
cache((r, c))
}
println(gridTraveler(0, 1, collection.mutable.Map.empty))
//println(gridTraveler(1, 0, Map.empty))
println()
// println(gridTraveler(1, 1, Map.empty))
// println(gridTraveler(2, 3, Map.empty))
// println(gridTraveler(3, 2, Map.empty))
// println(gridTraveler(3, 3, Map.empty))
println(gridTraveler(18, 18, collection.mutable.Map.empty))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment