Avatar of rabuf

rabuf's solution

to Crypto Square in the Common Lisp Track

Published at Jan 21 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 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))
(unless (find-package :screamer)
  (ql:quickload :screamer))
(unless (find-package :iterate)
  (ql:quickload :iterate))
(in-package #:cl-user)
(defpackage #:crypto-square
  (:use #:cl #:screamer #:iterate)
  (:export #:encipher))
(in-package #:crypto-square)

(defun shape (length)
  (let ((c (make-variable "C"))
        (r (make-variable "R")))
    (assert! (integerpv c))
    (assert! (integerpv r))
    (assert! (<=v length (*v r c)))
    (assert! (<=v r c))
    (assert! (<=v (-v c r) 1))
    (one-value (let ((x (an-integer-between 1 length))
                     (y (an-integer-between 1 length)))
                 (assert! (=v c x))
                 (assert! (=v r y))
                 (list (value-of x) (value-of y))))))
(defun encipher (plaintext)
  (cond ((plusp (length plaintext))
         (let ((plaintext (remove-if-not #'alphanumericp (string-downcase plaintext))))
           (destructuring-bind (c r) (shape (length plaintext))
             (let* ((result (make-array (list r c) :initial-element #\Space))
                    (displaced (make-array (* c r) :displaced-to result)))
               (iter (for i from 0)
                     (for c in-string plaintext)
                     (setf (aref displaced i) c))
               (concatenate 'string
                            (iter outer
                                  (for j from 0 below c)
                                  (iter (for i from 0 below r)
                                        (in outer
                                            (collect (aref result i j))))
                                  (unless (= j (1- c))
                                    (collect #\Space))))))))
        (t "")))

Community comments

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

rabuf's Reflection

I intend to revisit this one to clean up `encipher`, it's very busy right now.

I also had some fun using `screamer` to determine the dimensions based on the specification. There are, of course, infinitely many potential values of `c` and `r`, but the first one happens to be the minimum needed to cover the length. That portion could also be cleaned up a bit and still produce the correct result.