Skip to content

Instantly share code, notes, and snippets.

@oakwhiz
Created May 3, 2014 23:13
Show Gist options
  • Save oakwhiz/b42ba8984119265a544a to your computer and use it in GitHub Desktop.
Save oakwhiz/b42ba8984119265a544a to your computer and use it in GitHub Desktop.
Program to exhaustively decode Morse Code that is missing delimiting spaces.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MorseDecoder
{
class Program
{
private static Dictionary<string, string> map = new Dictionary<string, string>()
{
{ ".-", "a" },
{ "-...", "b" },
{ "-.-.", "c" },
{ "-..", "d" },
{ ".", "e" },
{ "..-.", "f" },
{ "--.", "g" },
{ "....", "h" },
{ "..", "i" },
{ ".---", "j" },
{ "-.-", "k" },
{ ".-..", "l" },
{ "--", "m" },
{ "-.", "n" },
{ "---", "o" },
{ ".--.", "p" },
{ "--.-", "q" },
{ ".-.", "r" },
{ "...", "s" },
{ "-", "t" },
{ "..-", "u" },
{ "...-", "v" },
{ ".--", "w" },
{ "-..-", "x" },
{ "-.--", "y" },
{ "--..", "z" },
{ ".----", "1" },
{ "..---", "2" },
{ "...--", "3" },
{ "....-", "4" },
{ ".....", "5" },
{ "-....", "6" },
{ "--...", "7" },
{ "---..", "8" },
{ "----.", "9" },
{ "-----", "0" },
};
public static IEnumerable<string> DecodeMorse(string morse)
{
var letters =
map
.Where(kvp => morse.StartsWith(kvp.Key))
.Select(kvp => new
{
letter = kvp.Value,
remainder = morse.Substring(kvp.Key.Length)
})
.ToArray();
if (letters.Any())
{
var query =
from l in letters
from x in DecodeMorse(l.remainder)
select l.letter + x;
return query.ToArray();
}
else
{
return new[] { "" };
}
}
static void Main(string[] args)
{
Console.Error.WriteLine("Decode Morse Code Without Spaces");
Console.Error.WriteLine("Enter morse code using . and - characters:");
foreach (var i in DecodeMorse(Regex.Replace(Console.ReadLine(),@"[^.\-]","")))
{
Console.WriteLine(i);
}
Console.Error.WriteLine();
Console.Error.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment