Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created December 6, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeMKH/751a6ca7542907954d5de8bd8e8028e4 to your computer and use it in GitHub Desktop.
Save MikeMKH/751a6ca7542907954d5de8bd8e8028e4 to your computer and use it in GitHub Desktop.
Rot 13 kata in C# with xUnit in one line.
using System;
using System.Linq;
namespace Cipher
{
public class Rot13
{
public static string Encode(string text)
=> new string(
text.ToCharArray()
.Select(c => char.IsLetter(c) ?
char.IsLower(c) ?
(char)((c - 'a' + 13) % 26 + 'a')
: (char)((c - 'A' + 13) % 26 + 'A')
: c
).ToArray());
}
}
using System;
using Xunit;
namespace Cipher.Tests
{
public class Rot13Tests
{
[Fact]
public void GivenEmptyItMustReturnEmpty()
{
var actual = Rot13.Encode(string.Empty);
Assert.True(string.IsNullOrEmpty(actual));
}
[Theory]
[InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "NOPQRSTUVWXYZABCDEFGHIJKLM")]
[InlineData("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")]
[InlineData("Why did the chicken cross the road?", "Jul qvq gur puvpxra pebff gur ebnq?")]
[InlineData("Gb trg gb gur bgure fvqr!", "To get to the other side!")]
public void GivenValueMustEncodeToExpectedValue(string given, string expected)
=> Assert.Equal(expected, Rot13.Encode(given));
}
}
@MikeMKH
Copy link
Author

MikeMKH commented Dec 6, 2017

:) Don’t let people know I know how to code like this.

@stehlikio
Copy link

@MikeMKH too late.

@markdreyer
Copy link

Love this! To make it even shorter - you can ditch text.ToCharArray().Select use Select right off of the string.

> "ABC".ToCharArray().Select(c => (char)((c - 'A' + 13) % 26 + 'A')).ToArray()
> char[3] { 'N', 'O', 'P' }

> "ABC".Select(c => (char)((c - 'A' + 13) % 26 + 'A')).ToArray()
> char[3] { 'N', 'O', 'P' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment