Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Morse without white spaces to text

Tags:

c#

morse-code

Is there any possibility to decode Morse code to text if the code is in following format(without any white spaces):

-.-..--.....-...--..----.

Normally it looks like that,

- .-. .- -. ... .-.. .- - .. --- -.
t  r  a  n   s   l   a  t  i  o  n 

but is it possible, to get the same text from Morse code without white spaces?

like image 995
Kalvis Avatar asked Dec 26 '22 12:12

Kalvis


1 Answers

This is possible to do, but it becomes problematic as you end up generating a large number of possible options.

First start with a Morse mapping:

private 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" }, 
    { ".--", "x" }, 
    { "-..-", "y" }, 
    { "-.--", "z" }, 
    { "--..", " " }, 
};

Then this function can produce the possible decodings:

public 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 [] { "" };
    }
}

Now, given a shorter version of your input morse, "-.-..--....", I got 741 possible strings. Here's the cut down version:

cabe
cadee
cadi
…
tranie
trans
trateeee
…
trxii
trxse

It includes "trans" so it seems to be working.

Running on the full string produces 5,914,901 possible with "translation" as one of the possibilities.

Incidentally, there were 4,519 possible strings that simply started with "trans". How humans could do this on the fly is amazing!

like image 179
Enigmativity Avatar answered Jan 03 '23 08:01

Enigmativity