Когда вы играете с Сайфером, часто возникает вопрос: «Как работать с буквой, которой нет в нашем базовом алфавите?».
Идея алфавита - это простой способ обработки диапазона [az AZ 09]
и даже добавления пунктуации.Здесь мини-версия.
static string alphabet = "abcdefghijklmnopqrstuvwxyz";
Затем с помощью простой функции, чтобы разделить на простую задачу:
- ShiftChar, Shit Char в нашем алфавите с ключом шифра.
- Cypher, расшифровать слово.
-AllCypher, вычисли все шифры.
char ShiftChar(char letter, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
=> alphabet[EuclydianModulo(AlphabetIndex(letter, comparisonType) + key, alphabet.Length)];
int EuclydianModulo(int dividend, int divisor) //As % computes the remainder, not the modulo
=> ((dividend % divisor) + divisor) % divisor;
string Cypher(string word, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
=> new string( // To Return a string from char Array
word.Select(x => // If letter is not in the alphabet, Don't crypt that letter.
alphabet.IndexOf(word, comparisonType) >= 0 ? ShiftChar(x, key, comparisonType) : x
).ToArray()
);
List<string> AllCypher(string word, StringComparison comparisonType = StringComparison.CurrentCulture)
=> Enumerable.Range(0, alphabet.Length)
// If word is null, string.Empty.
.Select(key => Cypher(word??string.Empty, key, comparisonType))
.ToList();
internal void TestCase_SO_52991034()
{
var inputTest = new[] { "cake", "Ufhp rd gtc bnym knaj itejs qnvztw ozlx.", null };
var result = inputTest.Select(x => new { word = x, cypher = AllCypher(x) });
var ignoreCase = AllCypher("ABC", StringComparison.CurrentCultureIgnoreCase);
var caseSentitiv = AllCypher("ABC");
var crypt = Cypher("FooBar Crypt me!", 42, StringComparison.CurrentCultureIgnoreCase);
var decrypt = Cypher(crypt, alphabet.Length - 42);
}
Кроме того, Decrypt - это просто крипта, ключ которой alphabet.Length - key
:
string Decypher(string word, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
=> Cypher(word, alphabet.Length - key, comparisonType);