using System; using System.Collections.Generic; namespace SBRL.Algorithms.MorseCodeTranslator { /// /// A simple class to translate a morse code string into a normal string. /// /// Mozilla Public License version 2.0 /// /// Starbeamrainbowlabs (https://starbeamrainbowlabs.com/) /// /// v0.1 - 26th May 2017: /// - Creation! 😁 /// public static class MorseDecoder { /// /// The morse code lookup table. Use the methods in this class is possible, /// rather than accessing this lookup table directly! /// public static Dictionary morseCodeLookup = new Dictionary() { [".-"] = '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', }; /// /// Translates a single letter from morse code. /// /// The morse code to translate. /// The translated letter. public static char TranslateLetter(string morseSource) { return morseCodeLookup[morseSource.Trim()]; } /// /// Translates a string of space-separated morse code strings from morse code. /// /// The morse code to translate. /// The translated word. public static string TranslateWord(string morseSource) { string result = string.Empty; string[] morseLetters = morseSource.Split(" ".ToCharArray()); foreach(string morseLetter in morseLetters) result += TranslateLetter(morseLetter); return result; } /// /// Translates a list of morse-encoded words. /// /// The morse-encoded words to decipher. /// The decoded text. public static string TranslateText(IEnumerable morseSources) { string result = string.Empty; foreach(string morseSource in morseSources) result += $"{TranslateWord(morseSource)} "; return result.Trim(); } } }