ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Jul 13 2018
·
3 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 rectangles
`(r X c)`

should be output `c`

chunks of `r`

length, separated by spaces.
Phrases that do not fill perfect rectangles will have `n`

empty spaces.
Those spaces should be distributed evenly, added to the end of the last
`n`

chunks.

```
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
```

To run the tests, run the command `busted`

from within the exercise directory.

For more detailed information about the Lua track, including how to get help if you're having trouble, please visit the exercism.io Lua language page.

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

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

```
local cs = require('crypto-square')
describe('crypto-square', function()
describe('normalized_plaintext', function()
it('should convert all uppercase letters to lowercase', function()
assert.equal('abcdefg', cs.normalized_plaintext('AbcDEfG'))
end)
it('should remove all whitespace', function()
assert.equal('helloworld', cs.normalized_plaintext([[he ll o
wor l d ]]))
end)
it('should remove all punctuation and special characters', function()
assert.equal('helloworld', cs.normalized_plaintext('[{h|e!l@?><l.,o;}]w:"\'\\/o.+%-=rld@`~'))
end)
it('should retain numbers', function()
assert.equal('hello123', cs.normalized_plaintext('hello123'))
end)
end)
describe('size', function()
it('should determine the size of a small perfect square', function()
assert.equal(2, cs.size('1234'))
end)
it('should determine the size of a larger perfect square', function()
assert.equal(3, cs.size('123456789'))
end)
it('should determine the size of a non-perfect square', function()
assert.equal(4, cs.size('123456789abc'))
end)
it('should determine the size based on normalized plaintext', function()
assert.equal(4, cs.size('Oh hey, this is nuts!'))
end)
end)
describe('segments', function()
it('should split plaintext into segments of size', function()
assert.same(
{ 'neverv', 'exthin', 'eheart', 'withid', 'lewoes' },
cs.segments('never vex thine heart with idle woes')
)
end)
it('should split normalized plaintext', function()
assert.same(
{ 'zomg', 'zomb', 'ies' },
cs.segments('ZOMG! ZOMBIES!!!')
)
end)
end)
describe('ciphertext', function()
it('should generate ciphertext for a string', function()
assert.equal(
'wneiaweoreneawssciliprerlneoidktcms',
cs.ciphertext('we all know interspecies romance is weird')
)
end)
it('should normalize a string when generating ciphertext', function()
assert.equal(
'tasneyinicdsmiohooelntuillibsuuml',
cs.ciphertext('Time is an illusion. Lunchtime doubly so.')
)
end)
end)
describe('normalized_ciphertext', function()
it('should generate normalized ciphertext', function()
assert.equal(
'vrel aepe mset paoo irpo',
cs.normalized_ciphertext('Vampires are people too!')
)
end)
it('should generate normalized ciphertext with a short segment', function()
assert.equal(
'msemo aanin dnin ndla etlt shui',
cs.normalized_ciphertext('Madness, and then illumination.')
)
end)
it('should generate normalized ciphertext when just less than a full square', function()
assert.equal('im a', cs.normalized_ciphertext('I am'))
end)
end)
end)
```

```
local function normalized_plaintext(input)
return input:lower():gsub('%W', '')
end
local function size(input)
local norm = normalized_plaintext(input)
return math.ceil(math.sqrt(#norm)), norm
end
local function segments(input)
local size, norm = size(input)
local segmentedTable = {}
for i = 1, #norm, size do
table.insert(segmentedTable, norm:sub(i, i + size - 1))
end
return segmentedTable, size
end
local function ciphertext(input)
local segTable, size = segments(input)
local cipherText = ''
local cipherTable = {}
for i = 1, size do
local elementOfCipherText = ''
for j = 1, #segTable do
elementOfCipherText = elementOfCipherText .. segTable[j]:sub(i,i) or ''
end
cipherText = cipherText .. elementOfCipherText
table.insert(cipherTable, elementOfCipherText)
end
return cipherText, cipherTable
end
local function normalized_ciphertext(input)
local _, cipherTable = ciphertext(input)
return table.concat(cipherTable, ' ')
end
return {
normalized_plaintext = normalized_plaintext,
size = size,
segments = segments,
ciphertext = ciphertext,
normalized_ciphertext = normalized_ciphertext
}
```

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?

Level up your programming skills with 3,449 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments

In ciphertext, since you're already creating a table of all of the elements, you can return table.concat(cipherTable), cipherTable instead of manually concatenating each cipherText chunk.

@ryanplusplus commented:

In ciphertext, since you're already creating a table of all of the elements, you can return table.concat(cipherTable), cipherTable instead of manually concatenating each cipherText chunk.

Right.. actually I was gonna do that. but on the second thought I would just return the table so that other method can manipulate the data whatever they want.. I chose the flexibility over the simplicity :-)

What I mean is that you can return exactly what you return now, but do it more simply: local function ciphertext(input) local segTable, size = segments(input) local cipherTable = {} for i = 1, size do local elementOfCipherText = '' for j = 1, #segTable do elementOfCipherText = elementOfCipherText .. segTable[j]:sub(i,i) or '' end table.insert(cipherTable, elementOfCipherText) end return table.concat(cipherTable), cipherTable end