Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rotational-cipher exercise #279

Merged
merged 1 commit into from
Jan 30, 2024
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
11 changes: 11 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,17 @@
"difficulty": 3,
"topics": []
},
{
"slug": "rotational-cipher",
"name": "Rotational Cipher",
"uuid": "27b661f5-386c-4efb-8cce-53b6a3ba97d9",
"practices": [],
"prerequisites": [],
"difficulty": 3,
"topics": [
"strings"
]
},
{
"slug": "phone-number",
"name": "Phone Number",
Expand Down
29 changes: 29 additions & 0 deletions exercises/practice/rotational-cipher/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Instructions

Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.

The Caesar cipher is a simple shift cipher that relies on transposing all the letters in the alphabet using an integer key between `0` and `26`.
Using a key of `0` or `26` will always yield the same output due to modular arithmetic.
The letter is shifted for as many values as the value of the key.

The general notation for rotational ciphers is `ROT + <key>`.
The most commonly used rotational cipher is `ROT13`.

A `ROT13` on the Latin alphabet would be as follows:

```text
Plain: abcdefghijklmnopqrstuvwxyz
Cipher: nopqrstuvwxyzabcdefghijklm
```

It is stronger than the Atbash cipher because it has 27 possible keys, and 25 usable keys.

Ciphertext is written out in the same formatting as the input including spaces and punctuation.

## Examples

- ROT5 `omg` gives `trl`
- ROT0 `c` gives `c`
- ROT26 `Cool` gives `Cool`
- ROT13 `The quick brown fox jumps over the lazy dog.` gives `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.`
- ROT13 `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.` gives `The quick brown fox jumps over the lazy dog.`
19 changes: 19 additions & 0 deletions exercises/practice/rotational-cipher/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"keiravillekode"
],
"files": {
"solution": [
"rotational-cipher.sml"
],
"test": [
"test.sml"
],
"example": [
".meta/example.sml"
]
},
"blurb": "Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Caesar_cipher"
}
12 changes: 12 additions & 0 deletions exercises/practice/rotational-cipher/.meta/example.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
fun rotate (shiftKey: int): string -> string =
let
val A = ord #"A"
val a = ord #"a"

fun rotateChar (ch: char): char =
if ch >= #"A" andalso ch <= #"Z" then chr((shiftKey - A + ord ch) mod 26 + A)
else if ch >= #"a" andalso ch <= #"z" then chr((shiftKey - a + ord ch) mod 26 + a)
else ch
in
String.map rotateChar
end
40 changes: 40 additions & 0 deletions exercises/practice/rotational-cipher/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[74e58a38-e484-43f1-9466-877a7515e10f]
description = "rotate a by 0, same output as input"

[7ee352c6-e6b0-4930-b903-d09943ecb8f5]
description = "rotate a by 1"

[edf0a733-4231-4594-a5ee-46a4009ad764]
description = "rotate a by 26, same output as input"

[e3e82cb9-2a5b-403f-9931-e43213879300]
description = "rotate m by 13"

[19f9eb78-e2ad-4da4-8fe3-9291d47c1709]
description = "rotate n by 13 with wrap around alphabet"

[a116aef4-225b-4da9-884f-e8023ca6408a]
description = "rotate capital letters"

[71b541bb-819c-4dc6-a9c3-132ef9bb737b]
description = "rotate spaces"

[ef32601d-e9ef-4b29-b2b5-8971392282e6]
description = "rotate numbers"

[32dd74f6-db2b-41a6-b02c-82eb4f93e549]
description = "rotate punctuation"

[9fb93fe6-42b0-46e6-9ec1-0bf0a062d8c9]
description = "rotate all letters"
2 changes: 2 additions & 0 deletions exercises/practice/rotational-cipher/rotational-cipher.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fun rotate (shiftKey: int) (text: string): string =
raise Fail "'rotate' is not implemented"
92 changes: 92 additions & 0 deletions exercises/practice/rotational-cipher/test.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
(* version 1.0.0 *)

use "testlib.sml";
use "rotational-cipher.sml";

infixr |>
fun x |> f = f x

val testsuite =
describe "rotational-cipher" [
test "rotate a by 0, same output as input"
(fn _ => let
val phrase = "a"
val expect = "a"
in
rotate 0 phrase |> Expect.equalTo expect
end),

test "rotate a by 1"
(fn _ => let
val phrase = "a"
val expect = "b"
in
rotate 1 phrase |> Expect.equalTo expect
end),

test "rotate a by 26, same output as input"
(fn _ => let
val phrase = "a"
val expect = "a"
in
rotate 26 phrase |> Expect.equalTo expect
end),

test "rotate m by 13"
(fn _ => let
val phrase = "m"
val expect = "z"
in
rotate 13 phrase |> Expect.equalTo expect
end),

test "rotate n by 13 with wrap around alphabet"
(fn _ => let
val phrase = "n"
val expect = "a"
in
rotate 13 phrase |> Expect.equalTo expect
end),

test "rotate capital letters"
(fn _ => let
val phrase = "OMG"
val expect = "TRL"
in
rotate 5 phrase |> Expect.equalTo expect
end),

test "rotate spaces"
(fn _ => let
val phrase = "O M G"
val expect = "T R L"
in
rotate 5 phrase |> Expect.equalTo expect
end),

test "rotate numbers"
(fn _ => let
val phrase = "Testing 1 2 3 testing"
val expect = "Xiwxmrk 1 2 3 xiwxmrk"
in
rotate 4 phrase |> Expect.equalTo expect
end),

test "rotate punctuation"
(fn _ => let
val phrase = "Let's eat, Grandma!"
val expect = "Gzo'n zvo, Bmviyhv!"
in
rotate 21 phrase |> Expect.equalTo expect
end),

test "rotate all letters"
(fn _ => let
val phrase = "The quick brown fox jumps over the lazy dog."
val expect = "Gur dhvpx oebja sbk whzcf bire gur ynml qbt."
in
rotate 13 phrase |> Expect.equalTo expect
end)
]

val _ = Test.run testsuite
160 changes: 160 additions & 0 deletions exercises/practice/rotational-cipher/testlib.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
structure Expect =
struct
datatype expectation = Pass | Fail of string * string

local
fun failEq b a =
Fail ("Expected: " ^ b, "Got: " ^ a)

fun failExn b a =
Fail ("Expected: " ^ b, "Raised: " ^ a)

fun exnName (e: exn): string = General.exnName e
in
fun truthy a =
if a
then Pass
else failEq "true" "false"

fun falsy a =
if a
then failEq "false" "true"
else Pass

fun equalTo b a =
if a = b
then Pass
else failEq (PolyML.makestring b) (PolyML.makestring a)

fun nearTo delta b a =
if Real.abs (a - b) <= delta * Real.abs a orelse
Real.abs (a - b) <= delta * Real.abs b
then Pass
else failEq (Real.toString b ^ " +/- " ^ Real.toString delta) (Real.toString a)

fun anyError f =
(
f ();
failExn "an exception" "Nothing"
) handle _ => Pass

fun error e f =
(
f ();
failExn (exnName e) "Nothing"
) handle e' => if exnMessage e' = exnMessage e
then Pass
else failExn (exnMessage e) (exnMessage e')
end
end

structure TermColor =
struct
datatype color = Red | Green | Yellow | Normal

fun f Red = "\027[31m"
| f Green = "\027[32m"
| f Yellow = "\027[33m"
| f Normal = "\027[0m"

fun colorize color s = (f color) ^ s ^ (f Normal)

val redit = colorize Red

val greenit = colorize Green

val yellowit = colorize Yellow
end

structure Test =
struct
datatype testnode = TestGroup of string * testnode list
| Test of string * (unit -> Expect.expectation)

local
datatype evaluation = Success of string
| Failure of string * string * string
| Error of string * string

fun indent n s = (implode (List.tabulate (n, fn _ => #" "))) ^ s

fun fmt indentlvl ev =
let
val check = TermColor.greenit "\226\156\148 " (* ✔ *)
val cross = TermColor.redit "\226\156\150 " (* ✖ *)
val indentlvl = indentlvl * 2
in
case ev of
Success descr => indent indentlvl (check ^ descr)
| Failure (descr, exp, got) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) exp,
indent (indentlvl + 2) got]
| Error (descr, reason) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) (TermColor.redit reason)]
end

fun eval (TestGroup _) = raise Fail "Only a 'Test' can be evaluated"
| eval (Test (descr, thunk)) =
(
case thunk () of
Expect.Pass => ((1, 0, 0), Success descr)
| Expect.Fail (s, s') => ((0, 1, 0), Failure (descr, s, s'))
)
handle e => ((0, 0, 1), Error (descr, "Unexpected error: " ^ exnMessage e))

fun flatten depth testnode =
let
fun sum (x, y, z) (a, b, c) = (x + a, y + b, z + c)

fun aux (t, (counter, acc)) =
let
val (counter', texts) = flatten (depth + 1) t
in
(sum counter' counter, texts :: acc)
end
in
case testnode of
TestGroup (descr, ts) =>
let
val (counter, texts) = foldr aux ((0, 0, 0), []) ts
in
(counter, (indent (depth * 2) descr) :: List.concat texts)
end
| Test _ =>
let
val (counter, evaluation) = eval testnode
in
(counter, [fmt depth evaluation])
end
end

fun println s = print (s ^ "\n")
in
fun run suite =
let
val ((succeeded, failed, errored), texts) = flatten 0 suite

val summary = String.concatWith ", " [
TermColor.greenit ((Int.toString succeeded) ^ " passed"),
TermColor.redit ((Int.toString failed) ^ " failed"),
TermColor.redit ((Int.toString errored) ^ " errored"),
(Int.toString (succeeded + failed + errored)) ^ " total"
]

val status = if failed = 0 andalso errored = 0
then OS.Process.success
else OS.Process.failure

in
List.app println texts;
println "";
println ("Tests: " ^ summary);
OS.Process.exit status
end
end
end

fun describe description tests = Test.TestGroup (description, tests)
fun test description thunk = Test.Test (description, thunk)