AudioMorseDecoder/MorseCodeParser/MorseDecoder.cs

103 lines
2.9 KiB
C#
Raw Normal View History

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