Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions solutions/c/crypto-square/1/crypto_square.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include "crypto_square.h"
#include <ctype.h>
#include <math.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>

char *ciphertext(const char *input){
if (!input) return NULL;

size_t len = strlen(input);
char *cleaned = malloc(len);
if (!cleaned) return NULL;

size_t count = 0;

{
size_t i = 0;
char c;
while ((c = input[i++])) if (isalpha(c)) cleaned[count++] = tolower(c); else if (isdigit(c)) cleaned[count++] = c;
}

if (count == 0) {
free(cleaned);
return calloc(1, 1);
}

size_t c = ceil(sqrt(count));
size_t r = (c * (c - 1) >= count) ? c - 1 : c;

size_t size = c * r + (c - 1) + 1;
char *cipher = malloc(size);
if (!cipher) { free(cleaned); return NULL; }

memset(cipher, ' ', size);

size_t counter = 0;
for (size_t i = 0; i < c; i++) {
size_t old_counter = counter;
for (size_t j = i; j < count; j += c) {
cipher[counter++] = cleaned[j];
}
if (counter != old_counter + r) counter = old_counter + r;
if (i < c - 1) cipher[counter++] = ' ';
}

free(cleaned);
cipher[counter] = '\0';
return cipher;
}
6 changes: 6 additions & 0 deletions solutions/c/crypto-square/1/crypto_square.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#ifndef CRYPTO_SQUARE_H
#define CRYPTO_SQUARE_H

char *ciphertext(const char *input);

#endif