Avatar of shikov

shikov's solution

to Crypto Square in the C Track

Published at Jul 29 2019 · 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 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 "

Getting Started

Make sure you have read the "Guides" section of the C track 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)
{
}

static 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);
}

static 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);
}

static 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);
}

static 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);
}

static 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);
}

static 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);
}

static 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);

   return UnityEnd();
}

src/crypto_square.h

#ifndef CRYPTO_SQUARE_H
#define CRYPTO_SQUARE_H

#define MAX_STR_LEN 201

char* ciphertext(const char* input);

#endif

src/crypto_square.c

#include "crypto_square.h"
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>

char* ciphertext(const char* input){
    char* text = calloc(MAX_STR_LEN, sizeof(char));
    char* output = calloc(MAX_STR_LEN, sizeof(char));
	size_t length = 0;
    for(size_t i = 0; input[i] != '\0'; i++) if (isalnum(input[i])) text[length++] = (char)tolower(input[i]);
    double cols = round(sqrt(length));
	double rows = cols + (length > cols * cols);
	for (size_t i = 0, l=length; i < cols*rows-l; i++) text[length++] = ' ';
	for (size_t i=0, col = 0; col < rows; col++) {
        for (size_t row = col; row < length; row += (size_t)rows) {
			output[i++] = text[row];
		}
		if (col < rows-1) output[i++] = ' ';
	}
    free(text);
	return output;
}

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?