Created
October 13, 2021 13:10
-
-
Save leontabak/c7b513f5f017c8d246ea5301a3399ef1 to your computer and use it in GitHub Desktop.
Kotlin: What is familiar? What is new?
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
import kotlin.text.Regex | |
fun makeScrambler(order: List<Int>): (String) -> String { | |
fun scrambler(plainText: String): String { | |
val word = plainText.toList() | |
val code = order.indices.map { word[order[it] - 1] } | |
return code.joinToString( | |
prefix = "", | |
separator = "", | |
postfix = "") | |
} // scrambler() | |
return ::scrambler | |
} // makeScrambler() | |
// I have not used this function but | |
// thought it might be useful in some | |
// future enhancement of this program. | |
fun makeSuffix(n:Int):String { | |
// return a string that contains | |
// n X's | |
return (0 until n).joinToString( | |
prefix = "", | |
separator = "", | |
postfix = "" | |
) { "X" } | |
} // makeSuffix() | |
fun pad( blockOfLetters:String):String { | |
/* | |
pre-condition: length of blockOfLetters <= 5 | |
return blockOfLetters + how every many X's are | |
needed to make a string with a length = 5 | |
*/ | |
return when( blockOfLetters.length ) { | |
0 -> blockOfLetters + "XXXXX" | |
1 -> blockOfLetters + "XXXX" | |
2 -> blockOfLetters + "XXX" | |
3 -> blockOfLetters + "XX" | |
4 -> blockOfLetters + "X" | |
else -> blockOfLetters | |
} | |
} // pad() | |
fun main() { | |
// a five letter word | |
val programmingLanguage = "BASIC" | |
val farewellFromInstructor = | |
"Thank you for choosing to study with us!" | |
val fredBrooks = "A scientist builds in order to learn;" + | |
"an engineer learns in order to build." | |
val philipGlass = | |
"A new language requires a new technique. " + | |
"If what you are saying does not require a new " + | |
"language, then what you are saying probably is " + | |
"not new." | |
// The zip code for Mount Vernon, Iowa | |
// is our key for encryption. | |
// Any permutation of the integers | |
// 1, 2, 3, 4, 5 will work. | |
val zipcode = listOf(5, 2, 3, 1, 4) | |
// Choose a quotation. | |
val quotation = philipGlass | |
val re = Regex("\\w") | |
val plainText = quotation. | |
filter { re.matches(it.toString()) }. | |
uppercase(). | |
chunked(zipcode.size). | |
map { pad(it) } | |
println( farewellFromInstructor ) | |
println(plainText) | |
val encoder = makeScrambler(zipcode) | |
println( plainText.map { encoder(it) } ) | |
} // main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment