Created
August 11, 2017 09:23
-
-
Save andrewrlee/4bb748f6b86b0e3de589e2d61844eeec to your computer and use it in GitHub Desktop.
Playing with kotlin: Implementing the Caesar Cipher
This file contains 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
package aaa | |
import java.util.concurrent.ThreadLocalRandom | |
private fun caesar(key: Int) : (Char) -> Char { | |
val seq = generateSequence('a' + key) { last -> if (last + 1 > 'z') 'a' else last + 1} | |
return { c -> seq.elementAt(c - 'a') } | |
} | |
private fun unCaesar(key: Int) : (Char) -> Char { | |
val seq = generateSequence('z' - (key - 1)) { last -> if (last + 1 > 'z') 'a' else last + 1} | |
return { c -> seq.elementAt((c - 'a')) } | |
} | |
fun translate(translate: (Char) -> Char) : (String) -> String { | |
return { input -> input | |
.map { it.toLowerCase() } | |
.map { if (it == ' ') it else translate(it) } | |
.fold("") { acc, c -> acc + c } } | |
} | |
fun main(args: Array<String>) { | |
val encode = { key: Int -> translate(caesar(key)) } | |
val decode = { key: Int -> translate(unCaesar(key)) } | |
val key = ThreadLocalRandom.current().nextInt(1, 26) | |
check("askrible doxz" == decode(key)(encode(key)("askrible doxz"))) { "decoded encoded string matches input" } | |
val phrase = "a fox ran aCroSS thE plAIN in the moonlight and said hi" | |
val encodedPhrase = encode(key)(phrase) | |
println("Phrase to find: $encodedPhrase\n\nVariations:") | |
(1..25).forEach { | |
val phraseByThisKey = encode(it)(phrase) | |
if (encodedPhrase == phraseByThisKey) { | |
println("Found under key: $it, \"$phraseByThisKey\" decoded: ${decode(it)(encodedPhrase)}") | |
} | |
} | |
println("\nKey was: $key") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment