Skip to content

Instantly share code, notes, and snippets.

@zanza00
Last active December 23, 2016 15:58
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 zanza00/de8961dadfa9c210799ff1e980612496 to your computer and use it in GitHub Desktop.
Save zanza00/de8961dadfa9c210799ff1e980612496 to your computer and use it in GitHub Desktop.
A more general approach to resolve verbal arithmetic using scala API, completely based on the talk by Filippo Vitale => https://youtu.be/sot44l8zKuo
/**
* Created by simone.picciani on 21/12/2016.
*/
object ScalaAPI {
def main(args: Array[String]): Unit = {
val initTime = System.currentTimeMillis
// val phrase = "send more money"
val phrase = "leia luke han rebel"
val phraseNoSpaces = phrase.replace(" ", "")
val phraseList = phrase split " " toList
val question = phraseList init
val initials = phraseList map (_.head)
val answer = phraseList last
val maps = for {
combination <- (0 to 9).combinations(phraseNoSpaces.distinct.length)
permutation <- combination.permutations
} yield (phraseNoSpaces.distinct zip permutation).toMap
val reducer = (str: String, m: Map[Char, Int]) => str map m reduce (_ * 10 + _)
val solutions = {
val result = for {
m <- maps if initials forall (m(_) != 0)
first = question.map(reducer(_, m))
last = reducer(answer, m)
if first.sum == last
} yield (first, last)
result
}
println(s"result is ${solutions.next()}")
val elapsedTime = System.currentTimeMillis - initTime
println(s"Total Duration of scalaAPI-> $elapsedTime ms")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment