 # stackcats's solution

## to Crypto Square in the C Track

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

#### Note:

This exercise has changed since this solution 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 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
``````

## Getting Started

Make sure you have read the C page on the Exercism site. This covers the basic information on setting up the development environment expected by the exercises.

## Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development.

The included makefile can be used to create and run the tests using the `test` task.

``````make test
``````

Create just the functions you need to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, move onto the next test.

As you progress through the tests, take the time to refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard C99 facilities in preference to writing your own low-level algorithms or facilities by hand.

## 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.

### test_crypto_square.c

``````#include "vendor/unity.h"
#include "../src/crypto_square.h"
#include <stdlib.h>

void setUp(void)
{
}

void tearDown(void)
{
}

void test_empty_text_res_in_an_empty_ciphertext(void)
{
const char *input = "";
const char *expected = "";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_lowercase(void)
{
TEST_IGNORE();               // delete this line to run test
const char *input = "A";
const char *expected = "a";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_remove_spaces(void)
{
TEST_IGNORE();
const char *input = "  b ";
const char *expected = "b";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_remove_punctuation(void)
{
TEST_IGNORE();
const char *input = "@1,%!";
const char *expected = "1";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_9_char_plaintext_gives_3_chunks_of_3_chars(void)
{
TEST_IGNORE();
const char *input = "This is fun!";
const char *expected = "tsf hiu isn";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_8_char_plaintext_gives_3_chunks_last_one_with_trailing_space(void)
{
TEST_IGNORE();
const char *input = "Chill out.";
const char *expected = "clu hlt io ";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

void test_54_char_plaintext_gives_7_chunks_last_two_with_trailing_spaces(void)
{
TEST_IGNORE();
const char *input =
"If man was meant to stay on the ground, god would have given us roots.";
const char *expected =
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn  sseoau ";
char *res = ciphertext(input);
TEST_ASSERT_EQUAL_STRING(expected, res);
free(res);
}

int main(void)
{
UnityBegin("test/test_ciphertext.c");

RUN_TEST(test_empty_text_res_in_an_empty_ciphertext);
RUN_TEST(test_lowercase);
RUN_TEST(test_remove_spaces);
RUN_TEST(test_remove_punctuation);
RUN_TEST(test_9_char_plaintext_gives_3_chunks_of_3_chars);
RUN_TEST(test_8_char_plaintext_gives_3_chunks_last_one_with_trailing_space);
RUN_TEST
(test_54_char_plaintext_gives_7_chunks_last_two_with_trailing_spaces);

UnityEnd();
return 0;
}``````

### src/crypto_square.c

``````#include "crypto_square.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

char *ciphertext(const char *input) {
size_t input_len = strlen(input);
char *filtered = (char*)malloc((input_len + 1) * sizeof(char));
memset(filtered, 0, (input_len + 1) * sizeof(char));
while (*input != '\0') {
if (isalnum(*input)) {
sprintf(filtered, "%s%c", filtered, tolower(*input));
}
input++;
}

int len = strlen(filtered);
int end = sqrt(len) + 1;
int r, c = sqrt(len);
while (c <= end) {
r = c - 1;
if (r * c >= len) {
break;
}
r = c;
if (r * c >= len) {
break;
}
c++;
}

char *res = (char*)malloc((len + 1 + r) * sizeof(char));
memset(res, 0, sizeof(char) * (len + 1));
int k = 0;
for (int j = 0; j < c; j++) {
for (int i = 0; i < r; i++) {
if (i*c + j >= len) {
res[k++] = ' ';
} else {
res[k++] = filtered[i*c + j];
}
}
if (j < c - 1) {
res[k++] = ' ';
}
}

free(filtered);
return res;
}``````

### src/crypto_square.h

``````#ifndef CRYPTO_SQUARE_H
#define CRYPTO_SQUARE_H

char *ciphertext(const char*);
#endif``````