Anonymous user
Vigenère cipher: Difference between revisions
→Alternate Scala implementation: refactored to remove usage of variables; shortened static setup of chars with for loop init; used single recursive instead of map call
m (→{{header|C}}: Added restrict) |
(→Alternate Scala implementation: refactored to remove usage of variables; shortened static setup of chars with for loop init; used single recursive instead of map call) |
||
Line 2,788:
</pre>
===Alternate Scala implementation===
This version first creates a sequence of characters from A to Z and a "flattened" Vigenere Square. It then encodes or decodes by just indexing between these two sequences. The code does no error checking, as well as encoding all lower case letters as upper case.
val key = "LEMON"
▲<lang scala>class Vigenere(val key: String) {
private def rotate(p: Int, s: IndexedSeq[Char]) = s.drop(p) ++ s.take(p)
val vSquare = (for (i <- Range(0, 25)) yield rotate(i, chars)).flatten
def encrypt(s: String) = enrOrDecode(0, s.toUpperCase, encode)
▲ private val chars = 'A' to 'Z'
def decrypt(s: String) = enrOrDecode(0, s.toUpperCase, decode)
private def enrOrDecode(i: Int , in: String, op:(Char, Int) => Char): String = {
if (in.length == 0) in else {
val index = if (i == key.length) 0 else
(if (chars.contains(in.head)) op(in.head, index) else in.head) + enrOrDecode(index + 1, in.tail, op)
}
private def encode(c: Char, index: Int): Char = {
▲ if (chars.contains(c)) vSquare((c - 'A') * 26 + key(encIndex) - 'A') else c
}
private def decode(c: Char, index: Int) = {
▲ val baseIndex = (key(decIndex) - 'A') * 26
val nextIndex = vSquare.indexOf(c, baseIndex)
chars(nextIndex - baseIndex)
▲ } else c
}
}
<lang scala>val text = "ATTACKATDAWN"
val
val decoded = Vigenere.decrypt(text)
println("
println("
println("Decrypted => " +
{{out}}
<pre>
=={{header|Seed7}}==
|