Skip to content

Instantly share code, notes, and snippets.

@pokutuna
Created September 19, 2012 20:05
Show Gist options
  • Save pokutuna/3751905 to your computer and use it in GitHub Desktop.
Save pokutuna/3751905 to your computer and use it in GitHub Desktop.
import scala.io.Source
val code = Source.fromURL("http://projecteuler.net/project/cipher1.txt").mkString.trim.split(",").map(_.toInt.toChar).toList
def decode(pass: List[Char], code: List[Char]): List[Char] =
code.zipWithIndex.map( p => p._1 ^ pass(p._2 % pass.length) toChar )
val frequentlyWord = "the".r
def isGraphicChar(c: Char): Boolean = return if (c < ' ' || '~' < c) false else true
val passes = for (a <- 'a' to 'z'; b <- 'a' to 'z'; c <- 'a' to 'z') yield List(a, b, c)
val correctPass = passes.maxBy { pass =>
val decoded = decode(pass, code)
if (decoded.forall(isGraphicChar)) frequentlyWord.findAllIn(decoded.mkString).length else -1
}
println(correctPass) // => List(g, o, d)
println(decode(correctPass, code).mkString) // => (The Gospel of ...
val answer = decode(correctPass, code).map(_.toInt).sum
println(answer) // => 107359
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment