Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active March 3, 2016 09:40
Show Gist options
  • Save rbobillot/ae59cc2b8fdda24259be to your computer and use it in GitHub Desktop.
Save rbobillot/ae59cc2b8fdda24259be to your computer and use it in GitHub Desktop.
root-me.org - Programmation/ch1 - Suite arithmétique - solution
#!/usr/bin/env scala
import io.Source, java.net.{URL,URLConnection}, collection.mutable.Map
def compute[I<:Int](start:I, end:I, alpha:I, beta:I): BigInt =
(1 to end).foldLeft(BigInt(start)){ (acc,x) => acc + alpha + beta*(x-1) }
val enigmaUrl = "http://challenge01.root-me.org/programmation/ch1"
val answerUrl = enigmaUrl + "/ep1_v.php?result="
val headerMap = Map("Cookie" -> "")
def getContent(url: URLConnection) = { setHeader(url) ; url.getInputStream }
def setHeader (url: URLConnection) = url.setRequestProperty("Cookie", headerMap("Cookie"))
def parse(html:String): (Int, Array[Int]) = {
val res = "(\\] (\\+|\\-) \\[)|([ >=]\\-?\\d+[< ])".r.findAllIn(html)
.map(_.replaceAll(">0<|[\\[\\]>< ]", ""))
.take(6).filter(_.nonEmpty).toArray
val d = res.filter(e => (e == "+" || e == "-")).mkString
( if (d=="+") 1 else -1 , res.filter(e => e != d).map(_.toInt) )
}
val enigmaLink = new URL(enigmaUrl).openConnection
val enigmaData = getContent( enigmaLink )
val enigmaText = Source.fromInputStream(enigmaData).mkString.replace("\n", "")
headerMap.update("Cookie",
enigmaLink.getHeaderFields.get("Set-Cookie").toString drop 1 dropRight 1)
val (d,nums) = parse(enigmaText)
val result = compute(nums(2), nums(3), nums(0), d*nums(1))
val answerData = getContent( new URL(answerUrl + result).openConnection )
def beauty(html:String) = html
.substring(enigmaText.indexOf("U<"),enigmaText.lastIndexOf("<br /><br />"))
.replace("<sub>", "\u001b[95m").replace("</sub>", "\u001b[0m")
.replace("<br />", "\n")
println( beauty(enigmaText) +"\n\n"+ Source.fromInputStream(answerData).mkString )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment