Last active
December 23, 2016 15:58
-
-
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
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
/** | |
* 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