Skip to content

Instantly share code, notes, and snippets.

@CaffeinatedDave
Created June 18, 2014 21:05
Show Gist options
  • Save CaffeinatedDave/b75d01018275853e8ac7 to your computer and use it in GitHub Desktop.
Save CaffeinatedDave/b75d01018275853e8ac7 to your computer and use it in GitHub Desktop.

Revisions

  1. CaffeinatedDave created this gist Jun 18, 2014.
    72 changes: 72 additions & 0 deletions BreakCypher.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    import java.net._
    import scala.io.BufferedSource
    import java.io._

    object HackJune extends App {
    val addr = "10.112.145.210"
    val socket = new Socket(InetAddress.getByName(addr), 8000)

    lazy val source = new BufferedSource(socket.getInputStream()).getLines()

    val dictionary = scala.io.Source.fromFile("/usr/share/dict/words").getLines.toSet

    val out = new PrintStream(socket.getOutputStream())

    while (source.hasNext) {
    val current = source.next
    print(current)
    if (current == "Language name?") {
    out.println("Scala")
    } else if (current == "Team name?") {
    out.println("Scala")
    } else if (current == "CORRECT!" || current == "INCORRECT!") {
    } else {
    val allSentences = split(current).flatMap(s => reverse(s)).flatMap(s => split(s)).flatMap(s => rotN(s)).toSet
    for (s <- allSentences) {
    if (isValidEnglish(s)) {
    print(" == " + s)
    out.println(s)
    }
    }
    }
    println()
    }

    // ROTn
    def rotN (enc: String): List[String] = {
    val lower = 'a' to 'z'
    val upper = 'A' to 'Z'

    (for (n <- 0 to 25) yield {
    enc.map(c => c match {
    case l if lower.contains(c) => lower(((l - 'a') + n) % 26)
    case u if upper.contains(c) => upper(((u - 'A') + n) % 26)
    case _ => c
    }).toString
    }).toList
    }

    // Reverse
    def reverse (enc: String): List[String] = {
    List(enc, enc.reverse)
    }

    // Split
    def split (enc: String): List[String] = {
    val (left, right) = enc.splitAt(enc.length / 2)
    val encZip = left.zip(right).foldLeft("")((acc, pair) => acc + pair._1 + pair._2)
    List(enc, encZip.mkString)
    }


    def isValidWord(word: String) : Boolean = {
    val toTest = word.toLowerCase().replaceAll("""\W+$""", "")
    dictionary.contains(toTest)
    }

    def isValidEnglish(sentence: String) : Boolean = {
    val words = sentence.split(' ').filter(x => x.length > 3)
    words.map(isValidWord).foldLeft(0)((acc, w) => if (w) acc + 1 else acc) > (words.length / 2)
    }

    }