Skip to content

Instantly share code, notes, and snippets.

@ddunkin
Created December 25, 2018 18:23
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 ddunkin/9414c92c7c0a3e12510bc674693442c8 to your computer and use it in GitHub Desktop.
Save ddunkin/9414c92c7c0a3e12510bc674693442c8 to your computer and use it in GitHub Desktop.
using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MerryChristmas
{
public static class RLE
{
public static string Encode(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input == "")
return "";
var output = new StringBuilder();
int count = 1;
for (int i = 0; i < input.Length; i++)
{
var ch = input[i];
if (i < input.Length - 1 && ch == input[i + 1])
{
count++;
}
else
{
output.Append(count.ToString(CultureInfo.InvariantCulture));
output.Append(ch);
if (count != 1)
count = 1;
}
}
return output.ToString();
}
public static string Decode(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (input == "")
return "";
var output = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
int len = 0;
while (char.IsDigit(input[i + len]))
len++;
int count = Convert.ToInt32(input.Substring(i, len), CultureInfo.InvariantCulture);
i += len;
for (int x = 0; x < count; x++)
output.Append(input[i]);
}
return output.ToString();
}
}
[TestClass]
public class UnitTests
{
[TestMethod]
public void TestEncodeDecode()
{
var testCases = new[]
{
("", ""),
("AAAABBBCCDAA", "4A3B2C1D2A"),
("A", "1A"),
("AAAAAAAAAA", "10A")
};
foreach (var testCase in testCases)
{
Assert.AreEqual(testCase.Item2, RLE.Encode(testCase.Item1));
Assert.AreEqual(testCase.Item1, RLE.Decode(testCase.Item2));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment