-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvigenere.cs
More file actions
51 lines (41 loc) · 1.55 KB
/
vigenere.cs
File metadata and controls
51 lines (41 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
void Main()
{
Console.WriteLine(Encode("reddit", "todayismybirthday"));
Console.WriteLine(Decode("reddit", "KSGDGBJQBEQKKLGDG"));
//"ZEJFOKHTMSRMELCPODWHCGAW"
}
// Define other methods and classes here
string Encode(string cipher, string text) {
int asciiIndex = 65;
cipher = cipher.ToUpper();
text = text.ToUpper();
var cipherArray = cipher.ToCharArray().Select(x => x-asciiIndex).ToArray();
var textArray = text.ToCharArray().Select(x => x-asciiIndex).ToArray();
var outputArray = new int[textArray.Count()];
int cipherIndex = 0;
for(int i = 0; i < outputArray.Count(); i++) {
outputArray[i] = mod((textArray[i] + cipherArray[cipherIndex]), 26);
cipherIndex = (cipherIndex + 1) % cipher.Length;
}
char[] output = outputArray.Select(x => Convert.ToChar(x+asciiIndex)).ToArray();
return string.Join("", output);
}
string Decode(string cipher, string cipherText) {
int asciiIndex = 65;
cipher = cipher.ToUpper();
cipherText = cipherText.ToUpper();
var cipherArray = cipher.ToCharArray().Select(x => x-asciiIndex).ToArray();
var cipherTextArray = cipherText.ToCharArray().Select(x => x-asciiIndex).ToArray();
var outputArray = new int[cipherTextArray.Count()];
int cipherIndex = 0;
for(int i = 0; i < outputArray.Count(); i++) {
outputArray[i] = mod((cipherTextArray[i] - cipherArray[cipherIndex]),26);
cipherIndex = (cipherIndex + 1) % cipher.Length;
}
char[] output = outputArray.Select(x => Convert.ToChar(x+asciiIndex)).ToArray();
return string.Join("", output);
}
int mod(int x, int m) {
int r = x%m;
return r<0 ? r+m : r;
}