 # tex's solution

## to Crypto Square in the PureScript Track

Published at Apr 17 2020 · 0 comments
Instructions
Test suite
Solution

Implement the classic method for composing secret messages called a square code.

Given an English text, output the encoded version of that text.

First, the input is normalized: the spaces and punctuation are removed from the English text and the message is downcased.

Then, the normalized characters are broken into rows. These rows can be regarded as forming a rectangle when printed with intervening newlines.

For example, the sentence

If man was meant to stay on the ground, god would have given us roots.

is normalized to:

ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots

The plaintext should be organized in to a rectangle. The size of the rectangle (`r x c`) should be decided by the length of the message, such that `c >= r` and `c - r <= 1`, where `c` is the number of columns and `r` is the number of rows.

Our normalized text is 54 characters long, dictating a rectangle with `c = 8` and `r = 7`:

``````ifmanwas
meanttos
tayonthe
groundgo
dwouldha
vegivenu
sroots
``````

The coded message is obtained by reading down the columns going left to right.

The message above is coded as:

``````imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau
``````

Output the encoded text in chunks. Phrases that fill perfect squares `(r X r)` should be output in `r`-length chunks separated by spaces. Imperfect squares will have `n` empty spaces. Those spaces should be distributed evenly across the last `n` rows.

``````imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
``````

Notice that were we to stack these, we could visually decode the cyphertext back in to the original message:

``````imtgdvs
fearwer
mayoogo
anouuio
ntnnlvt
wttddes
aohghn
sseoau
``````

## Source

J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### Main.purs

``````module Test.Main where

import Prelude

import Effect (Effect)
import Test.Unit.Assert as Assert
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Main (runTest)
import CryptoSquare ( normalizedPlaintext
, plaintextSegments
, encoded
, ciphertext
)

main :: Effect Unit
main = runTest suites

suites :: TestSuite
suites = do
suite "CryptoSquare.normalizedPlaintext" do

test "Lowercase" \$
Assert.equal "hello"
(normalizedPlaintext "Hello")

test "Remove spaces" \$
Assert.equal "hithere"
(normalizedPlaintext "Hi there")

test "Remove punctuation" \$
Assert.equal "123go"
(normalizedPlaintext "@1, 2%, 3 Go!")

suite "CryptoSquare.plaintextSegments" do

test "empty plaintext results in an empty rectangle" \$
Assert.equal
[]
(plaintextSegments "")

test "4 character plaintext results in an 2x2 rectangle" \$
Assert.equal
[ "ab"
, "cd"
]
(plaintextSegments "Ab Cd")

test "9 character plaintext results in an 3x3 rectangle" \$
Assert.equal
[ "thi"
, "sis"
, "fun"
]
(plaintextSegments "This is fun!")

test "54 character plaintext results in an 8x7 rectangle" \$
Assert.equal
[ "ifmanwas"
, "meanttos"
, "tayonthe"
, "groundgo"
, "dwouldha"
, "vegivenu"
, "sroots"
]
(plaintextSegments "If man was meant to stay on the ground, god would have given us roots.")

suite "CryptoSquare.encoded" do

test "empty plaintext results in an empty encode" \$
Assert.equal
""
(encoded "")

test "Non-empty plaintext results in the combined plaintext segments" \$
Assert.equal
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau"
(encoded "If man was meant to stay on the ground, god would have given us roots.")

suite "CryptoSquare.ciphertext" do

test "empty plaintext results in an empty ciphertext" \$
Assert.equal
""
(ciphertext "")

test "9 character plaintext results in 3 chunks of 3 characters" \$
Assert.equal
"tsf hiu isn"
(ciphertext "This is fun!")

test "54 character plaintext results in 7 chunks, the last two padded with spaces" \$
Assert.equal
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau "
(ciphertext "If man was meant to stay on the ground, god would have given us roots.")``````
``````module CryptoSquare
( normalizedPlaintext
, plaintextSegments
, encoded
, ciphertext
) where

import Prelude

import Data.Array (filter, foldl, replicate, updateAt)
import Data.Char.Unicode (isAlphaNum)
import Data.Int (ceil, floor, toNumber)
import Data.Maybe (fromMaybe)
import Data.String (drop, joinWith, length, take, toLower)
import Data.String.CodeUnits (fromCharArray, toCharArray)
import Math (sqrt)

normalizedPlaintext ∷ String → String
normalizedPlaintext =
toLower <<< fromCharArray <<< filter isAlphaNum <<< toCharArray

chunk ∷ Int → String → Array String
chunk _     ""  = []
chunk size  s   = [take size s] <> (chunk size \$ drop size s)

matrixSize ∷ String → { x ∷ Int, y ∷ Int }
matrixSize s = { x: ceil rt, y: floor rt }
where rt = sqrt \$ toNumber \$ length s

plaintextSegments ∷ String → Array String
plaintextSegments s = chunk (_.x \$ matrixSize ns) ns
where ns = normalizedPlaintext s

encoded' ∷ (Array Char → Array Char) → String → String
encoded' fn s
= fromCharArray
\$ fn
\$ _.a
\$ foldl go { i: 0, a: replicate (x * y) ' ' }
\$ toCharArray =<< plaintextSegments s
where
{ x, y } = matrixSize \$ normalizedPlaintext s
transpose i = (i `mod` x) * y + i / x
go { i, a } c = { i: i + 1, a: fromMaybe a \$ updateAt (transpose i) c a }

encoded ∷ String → String
encoded = encoded' \$ filter isAlphaNum

ciphertext ∷ String → String
ciphertext s = joinWith " " (chunk (_.y \$ matrixSize es) es)
where es = encoded' identity s``````