Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 10 additions & 25 deletions exercises/practice/simple-cipher/.meta/Example.scala
Original file line number Diff line number Diff line change
@@ -1,32 +1,17 @@
import scala.util.Random

case class Cipher(keyOpt: Option[String]) {
require(keyOpt.isEmpty || keyOpt.get.matches("^[a-z]+$"))
case class Cipher(keyOpt: Option[String]):
require(keyOpt.forall(_.matches("[a-z]+")), "the key must be lowercase letters")

private val alphabet = ('a' to 'z').toVector
private lazy val randomKey = Seq.fill(26)((Random.nextInt(25) + 'a').toChar).mkString
// Without a key, a random one of 100 lowercase letters.
val key: String = keyOpt.getOrElse(Seq.fill(100)(('a' + Random.nextInt(26)).toChar).mkString)

val key = keyOpt.getOrElse(randomKey)
def encode(text: String): String = shift(text, 1)

def encode(s: String): String =
(for (i <- 0 until s.length) yield encodeChar(s, i)).mkString
def decode(text: String): String = shift(text, -1)

private def encodeChar(plainText: String, index: Int) = {
var alphaIdx = alphabet.indexOf(plainText(index)) + alphabet.indexOf(key(index))
// Each letter moves by the key's letter at the same position; the key repeats as often as needed.
private def shift(text: String, direction: Int): String =
text.zipWithIndex.map((letter, i) => rotate(letter, direction * (key(i % key.length) - 'a'))).mkString

if (alphaIdx >= alphabet.length) alphaIdx -= alphabet.length

alphabet(alphaIdx)
}

def decode(s: String): String =
(for (i <- 0 until s.length) yield decodeChar(s, i)).mkString

private def decodeChar(cipherText: String, index: Int) = {
var alphaIdx = alphabet.indexOf(cipherText(index)) - alphabet.indexOf(key(index))

if (alphaIdx < 0) alphaIdx += alphabet.length

alphabet(alphaIdx)
}
}
private def rotate(letter: Char, by: Int): Char = ('a' + Math.floorMod(letter - 'a' + by, 26)).toChar
3 changes: 2 additions & 1 deletion exercises/practice/simple-cipher/.meta/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"contributors": [
"ErikSchierboom",
"ppartarr",
"rajeshpg"
"rajeshpg",
"rabestro"
],
"files": {
"solution": [
Expand Down
36 changes: 36 additions & 0 deletions exercises/practice/simple-cipher/.meta/template.j2
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{%- import "macros.j2" as macros -%}
{#- Without a key the cipher picks a random one, so those cases check against `cipher.key`. -#}
{{ macros.header("Cipher") }}
Comment thread
rabestro marked this conversation as resolved.
Resolved
{% for case in cases %}
{% set input = case.input %}

{{ macros.test_open(case) }}
{% if not loop.first %}
pending
{% endif %}
val cipher = Cipher({{ "Some(" ~ (input.key | scala) ~ ")" if input.key is defined else "None" }})
{% if case.property == "key" %}
cipher.key should fullyMatch regex {{ case.expected.match | scala }}
{% elif input.get("ciphertext") == "cipher.encode" %}
cipher.decode(cipher.encode({{ input.plaintext | scala }})) should be({{ case.expected | scala }})
{% elif input.key is defined %}
cipher.{{ case.property }}({{ (input.plaintext if case.property == "encode" else input.ciphertext) | scala }}) should be({{ case.expected | scala }})
{% elif case.property == "encode" %}
cipher.encode({{ input.plaintext | scala }}) should be(cipher.key.substring(0, {{ input.plaintext | length }}))
{% else %}
cipher.decode(cipher.key.substring(0, {{ case.expected | length }})) should be({{ case.expected | scala }})
{% endif %}
{% endfor %}

// Not in the canonical data: the instructions ask for a key of lowercase letters only.
test("Invalid key - contains caps"):
pending
assertThrows[IllegalArgumentException](Cipher(Some("ABCD")))

test("Invalid key - contains numerics"):
pending
assertThrows[IllegalArgumentException](Cipher(Some("123")))

test("Invalid key - is empty"):
pending
assertThrows[IllegalArgumentException](Cipher(Some("")))
6 changes: 6 additions & 0 deletions exercises/practice/simple-cipher/src/main/scala/Cipher.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
case class Cipher(keyOpt: Option[String]):
def key: String = ???

def encode(text: String): String = ???

def decode(text: String): String = ???
101 changes: 60 additions & 41 deletions exercises/practice/simple-cipher/src/test/scala/CipherTest.scala
Original file line number Diff line number Diff line change
@@ -1,65 +1,84 @@
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers

/** Generated from the canonical data in problem-specifications.
*
* Do not edit by hand: change .meta/template.j2 and run bin/generate-tests.
*/
class CipherTest extends AnyFunSuite with Matchers:

/** @version created manually **/
class CipherTest extends AnyFunSuite with Matchers {
test("Random key cipher - Can encode"):
val cipher = Cipher(None)
cipher.encode("aaaaaaaaaa") should be(cipher.key.substring(0, 10))

test("Random key cipher - can encode/decode") {
// Here we take advantage of the fact that plaintext of "aaa..."
// outputs the key. This is a critical problem with shift ciphers, some
// characters will always output the key verbatim.
test("Random key cipher - Can decode"):
pending
val cipher = Cipher(None)
cipher.decode(cipher.key.substring(0, 10)) should be("aaaaaaaaaa")

test(
"Random key cipher - Is reversible. I.e., if you apply decode in a encoded result, you must see the same plaintext encode parameter as a result of the decode method",
):
pending
val cipher = Cipher(None)
cipher.encode("aaaaaaaaaa") should be (cipher.key.substring(0, 10))
cipher.decode(cipher.key.substring(0, 10)) should be ("aaaaaaaaaa")
}
cipher.decode(cipher.encode("abcdefghij")) should be("abcdefghij")

test("Invalid key - contains caps") {
test("Random key cipher - Key is made only of lowercase letters"):
pending
intercept[IllegalArgumentException] {
Cipher(Some("ABCD"))
}
}
val cipher = Cipher(None)
cipher.key should fullyMatch regex "^[a-z]+$"

test("Invalid key - contains numerics") {
test("Substitution cipher - Can encode"):
pending
intercept[IllegalArgumentException] {
Cipher(Some("123"))
}
}
val cipher = Cipher(Some("abcdefghij"))
cipher.encode("aaaaaaaaaa") should be("abcdefghij")

test("Invalid key - is empty") {
test("Substitution cipher - Can decode"):
pending
intercept[IllegalArgumentException] {
Cipher(Some(""))
}
}
val cipher = Cipher(Some("abcdefghij"))
cipher.decode("abcdefghij") should be("aaaaaaaaaa")

test("Substitution cipher - can encode") {
test(
"Substitution cipher - Is reversible. I.e., if you apply decode in a encoded result, you must see the same plaintext encode parameter as a result of the decode method",
):
pending
Cipher(Some("abcdefghij")).encode("aaaaaaaaaa") should be ("abcdefghij")
}
val cipher = Cipher(Some("abcdefghij"))
cipher.decode(cipher.encode("abcdefghij")) should be("abcdefghij")

test("Substitution cipher - can decode") {
test("Substitution cipher - Can double shift encode"):
pending
Cipher(Some("abcdefghij")).decode("abcdefghij") should be ("aaaaaaaaaa")
}
val cipher = Cipher(Some("iamapandabear"))
cipher.encode("iamapandabear") should be("qayaeaagaciai")

test("Substitution cipher - is reversible") {
test("Substitution cipher - Can wrap on encode"):
pending
val cipher = Cipher(Some("abcdefghij"))
cipher.decode(cipher.encode("abcdefghij")) should be ("abcdefghij")
}
cipher.encode("zzzzzzzzzz") should be("zabcdefghi")

test("Substitution cipher - can double shift") {
test("Substitution cipher - Can wrap on decode"):
pending
val cipher = Cipher(Some("iamapandabear"))
cipher.encode("iamapandabear") should be ("qayaeaagaciai")
}
val cipher = Cipher(Some("abcdefghij"))
cipher.decode("zabcdefghi") should be("zzzzzzzzzz")

test("Substitution cipher - Can encode messages longer than the key"):
pending
val cipher = Cipher(Some("abc"))
cipher.encode("iamapandabear") should be("iboaqcnecbfcr")

test("Substitution cipher - Can decode messages longer than the key"):
pending
val cipher = Cipher(Some("abc"))
cipher.decode("iboaqcnecbfcr") should be("iamapandabear")

// Not in the canonical data: the instructions ask for a key of lowercase letters only.
test("Invalid key - contains caps"):
pending
assertThrows[IllegalArgumentException](Cipher(Some("ABCD")))

test("Invalid key - contains numerics"):
pending
assertThrows[IllegalArgumentException](Cipher(Some("123")))

test("Substitution cipher - can wrap") {
test("Invalid key - is empty"):
pending
Cipher(Some("abcdefghij")).encode("zzzzzzzzzz") should be ("zabcdefghi")
}
}
assertThrows[IllegalArgumentException](Cipher(Some("")))
Loading