Avatar of dbalmain

dbalmain's solution

to Crypto Square in the PureScript Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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 Control.Monad.Eff (Eff)
import Control.Monad.Eff.AVar (AVAR)
import Control.Monad.Eff.Console (CONSOLE)
import Test.Unit.Assert as Assert
import Test.Unit (TestSuite, suite, test)
import Test.Unit.Console (TESTOUTPUT)
import Test.Unit.Main (runTest)
import CryptoSquare ( normalizedPlaintext
                    , plaintextSegments
                    , encoded
                    , ciphertext
                    )

main :: forall eff
  . Eff ( avar :: AVAR
        , console :: CONSOLE
        , testOutput :: TESTOUTPUT
        | eff                     
        )
        Unit
main = runTest suites

suites :: forall e. TestSuite e
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 Data.Array (filter, head)
import Data.Char.Unicode (isAlphaNum)
import Data.List (fromFoldable, toUnfoldable, transpose)
import Data.Maybe (fromMaybe)
import Data.String (drop, fromCharArray, joinWith, take, toCharArray, toLower)
import Data.String as S
import Prelude (map, otherwise, ($), (*), (+), (-), (<$>), (<<<), (<>), (>=), (>>>))

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

plaintextSegments ∷ String → Array String
plaintextSegments s = chunks (squareSize ns) ns
  where ns = normalizedPlaintext s

squareSize ∷ String → Int
squareSize s = ss 1 $ S.length s
  where ss n l
          | n * n >= l = n
          | otherwise = ss (n + 1) l
    
segments :: String → Array String
segments =
    plaintextSegments >>>
    map (fromFoldable <<< toCharArray) >>>
    fromFoldable >>>
    transpose >>>
    toUnfoldable >>>
    map (fromCharArray <<< toUnfoldable)

encoded ∷ String → String
encoded = segments >>> joinWith ""

ciphertext ∷ String → String
ciphertext s = joinWith " " $ normalize <$> segs
  where
    segs = segments s
    width = S.length $ fromMaybe "" $ head segs
    n = squareSize $ normalizedPlaintext s
    normalize s' = s' <> spaces (width - S.length s')
    spaces 0 = ""
    spaces c = " " <> spaces (c - 1)

chunks ∷ Int → String → Array String
chunks _ "" = []
chunks n xs = [take n xs] <> (chunks n $ drop n xs)

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?