Square

in #ita2 days ago

using System;
using System.Text.RegularExpressions;

public static class CryptoSquare
{
public static string NormalizedPlaintext(string plaintext)
{
string result = "";
for(int i=0; i<plaintext.Length; i++)
{
if(char.IsLetter(plaintext[i]) || char.IsDigit(plaintext[i]))
{
result += plaintext[i];
}
}
return result.ToLower();
}

public static IEnumerable<string> PlaintextSegments(string plaintext)
{
    string res = "";
    string norm = NormalizedPlaintext(plaintext);
    int len = norm.Length;
    IEnumerable<string> words = new List<string> { };
    int c = (int)Math.Ceiling(Math.Sqrt(len));
    int r = c*(c-1) >= len? c - 1 : c;
    
    for(int i=0; i<c; i++)
    {
        for (int j=0; j<r; j++)
        {
            int lim = j*c+i;
            if(lim < len) res += ((norm[j*c+i]).ToString());
            else res += " ";
        
        }
        words = words.Append(res);
        res  = "";
    }
    return words;
}

public static string Ciphertext(string plaintext)
{
    return string.Join(" ", PlaintextSegments(plaintext));
}

}