Skip to content

Instantly share code, notes, and snippets.

@akselqviller
Last active November 26, 2018 07:22
Show Gist options
  • Save akselqviller/81326eda64e5e208a5f69be2dd992dd2 to your computer and use it in GitHub Desktop.
Save akselqviller/81326eda64e5e208a5f69be2dd992dd2 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace Caesar
{
static class Program
{
static void Main(string[] args)
{
// Skip argument checks, it is not essential to a clean and simple implementation of the algorithm
int offset = int.Parse(args[0]);
string inputFilename = args[1];
if (args.Any(s => s == "-d"))
offset = -offset; // Toggle Caesarian en/decryption, which is just shifting the opposite way
string inputText = File.ReadAllText(inputFilename);
// Use a range expression to avoid getting the alphabet wrong.
// string/List<char> don't matter, but is slightly more convenient with strings
// as you can type out the alphabet directly "abcdef..." instead of { 'a', 'b' ... }
string alphabet = Range('a', 'z').Concat("æøå").CharsToString();
// Caesarian encryption is just independent mappings of each character in the string:
string shiftedText = (from c in inputText
select CyclicShift(c, offset, alphabet)).CharsToString();
File.WriteAllText(inputFilename, shiftedText);
Console.WriteLine(shiftedText);
}
static char CyclicShift(char c, int offset, string alphabet)
{
char lowerC = char.ToLowerInvariant(c);
int index = alphabet.IndexOf(lowerC);
if (index < 0)
{
return c; // If not covered by the alphabet (spaces, line shifts etc.) just pass it through
}
else
{
var shifted = alphabet[(index + offset + alphabet.Length) % alphabet.Length];
if (char.IsUpper(c))
{
shifted = char.ToUpperInvariant(shifted);
}
return shifted;
}
}
static IEnumerable<char> Range(char first, char last)
{
for (char c = first; c <= last; c++)
yield return c;
}
static string CharsToString(this IEnumerable<char> @string)
{
return new string(@string.ToArray());
}
}
}
using System;
using System.Linq;
using System.IO;
namespace Caesar
{
class Program
{
static void Main(string[] args)
{
int offset = int.Parse(args[0]) * (args.Any(s => s == "-d") ? -1 : 1);
string alphabet = new string(Enumerable.Range('a', 26).Select(i => (char)i).Concat("æøå").ToArray());
string result = new string(File.ReadAllText(args[1])
.Select(c => char.IsWhiteSpace(c) ? c : alphabet[(alphabet.IndexOf(c) + offset + alphabet.Length) % alphabet.Length])
.ToArray());
Console.WriteLine(result);
File.WriteAllText(args[1], result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment