Avatar of xffox

xffox's solution

to Crypto Square in the Common Lisp Track

Published at Aug 21 2019 · 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 that fill perfect rectangles (r X c), with c chunks of r length, separated by spaces. For phrases that are n characters short of the perfect rectangle, pad each of the last n chunks with a single trailing space.

"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau "

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

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

Setup

Check out Installing Common Lisp for instructions to get started or take a look at the guides available in the track's side bar.

Formatting

While Common Lisp doesn't care about indentation and layout of code, nor whether you use spaces or tabs, this is an important consideration for submissions to exercism.io. Excercism.io's code widget cannot handle mixing of tab and space characters well so using only spaces is recommended to make the code more readable to the human reviewers. Please review your editors settings on how to accomplish this. Below are instructions for popular editors for Common Lisp.

VIM

Use the following commands to ensure VIM uses only spaces for indentation:

:set tabstop=2
:set shiftwidth=2
:set expandtab

(or as a oneliner :set tabstop=2 shiftwidth=2 expandtab). This can be added to your ~/.vimrc file to use it all the time.

Emacs

Emacs is very well suited for editing Common Lisp and has many powerful add-on packages available. The only thing that one needs to do with a stock emacs to make it work well with exercism.io is to evaluate the following code:

(setq-default indent-tabs-mode nil)

This can be placed in your ~/.emacs (or ~/.emacs.d/init.el) in order to have it set whenever Emacs is launched.

One suggested add-on for Emacs and Common Lisp is SLIME which offers tight integration with the REPL; making iterative coding and testing very easy.

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.

crypto-square-test.lisp

(ql:quickload "lisp-unit")
#-xlisp-test (load "crypto-square")

(defpackage #:crypto-square-test
  (:use #:common-lisp #:lisp-unit))

(in-package #:crypto-square-test)

(define-test empty-plaintext-results-in-an-empty-ciphertext
  (assert-equal
   ""
   (crypto-square:encipher "")))
(define-test lowercase
  (assert-equal
   "a"
   (crypto-square:encipher"A")))
(define-test remove-spaces
  (assert-equal
   "b"
   (crypto-square:encipher "  b ")))
(define-test remove-punctuation
  (assert-equal
   "1"
   (crypto-square:encipher "@1,%!")))
(define-test 9-character-plaintext-results-in-3-chunks-of-3-characters
  (assert-equal
   "tsf hiu isn"
   (crypto-square:encipher "This is fun!")))
(define-test 8-character-plaintext-results-in-3-chunks-the-last-one-with-a-trailing-space
  (assert-equal
   "clu hlt io "
   (crypto-square:encipher "Chill out.")))
(define-test 54-character-plaintext-results-in-7-chunks-the-last-two-with-trailing-spaces
  (assert-equal
   "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau "
   (crypto-square:encipher "If man was meant to stay on the ground, god would have given us roots.")))

#-xlisp-test
(let ((*print-errors* t)
      (*print-failures* t))
  (run-tests :all))
(in-package #:cl-user)
(defpackage #:crypto-square
  (:use #:cl)
  (:export #:encipher))
(in-package #:crypto-square)

(defun encipher (plaintext)
  (let* ((normtext (map 'array #'char-downcase
                        (remove-if-not #'alphanumericp plaintext)))
         (len (length normtext)))
    (coerce (if (/= len 0)
              (let* ((c (ceiling (sqrt len)))
                     (r (1+ (truncate (1- len) c))))
                (intersperse
                  r #\space
                  (loop :for i :from 0 :below (* r c)
                        :collect
                        (let ((offset (+ (* (mod i r) c) (truncate i r))))
                          (if (< offset len)
                            (aref normtext offset)
                            #\space)))))
              nil) 'string)))

(defun intersperse (sz v lst)
  (labels ((do-intersperse
             (res i vs)
             (if vs
               (if (equal 0 i)
                 (do-intersperse
                   (cons v res) sz vs)
                 (do-intersperse
                   (cons (car vs) res) (1- i) (cdr vs)))
               (reverse res))))
    (do-intersperse '() sz lst)))

Community comments

Find this solution interesting? Ask the author a question to learn more.

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?