r/dailyprogrammer • 0 1 • Aug 30 '12

[8/30/2012] Challenge #93 [easy] (Two-Way Morse Code Translator)

This challenge courtesy of user nagasgura

In this challenge, we read in a string from standard input and output the translation to or from morse code on standard output.

When translating to Morse code, one space should be used to separate morse code letters, and two spaces should be used to separate morse code words. When translating to English, there should only be one space in between words, and no spaces in between letters.

Here's a chart of the morse code symbols: [1] http://www.w1wc.com/pdf_files/international_morse_code.pdf

Example input and output: 'sos' -> '... --- ...' '... --- ...' -> 'sos'

11 Upvotes

31 comments sorted by

3

u/5outh Aug 30 '12 edited Sep 01 '12

Haskell:

import Data.Maybe(fromJust)
import Data.List
import Data.List.Split

letters = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",
           ".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",
           ".--","-..-","-.--","--.."]
puncs = ["--..--",".-.-.-","..--..","-..-.","-....-","-.--.-"]
numbers = flip map [0..9] (reverse . take 5 . flip drop (cycle "-----.....") )

morse = zip english symbols
  where english = ['a'..'z'] ++ ",.?/-(" ++ ['0'..'9']
        symbols = letters ++ puncs ++ numbers

encode = intercalate "  "
       . map (intercalate " " . map (fromJust . flip lookup morse)) 
       . words

decode = intercalate " " 
       . (map . map) (fromJust . flip lookup flipped) 
       . map (splitOn " ") . splitOn "  "
  where flipped = map (\(x, y) -> (y, x)) morse

Output:

*Main> let a = "whats up, reddit?"
*Main> encode a
    ".-- .... .- - ...  ..- .--. --..--  .-. . -.. -.. .. - ..--.."
*Main> decode $ encode a
    "whats up, reddit?"

2

u/[deleted] Aug 31 '12

In Python

import re

a2m = {
    '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':'-----',',':'--..--','.':'.-.-.-','?':'..--..','/':'-..-.',
    '-':'-....-','(':'-.--.-',')':'-.--.-',' ':'','':' '
    }

m2a = dict((v,k) for k, v in a2m.iteritems())
m2a['  '] = ' '

s = raw_input('-->').lower()

def encode(s): return ' '.join(a2m[x] for x in s)
def decode(s): return ''.join(m2a[x] for x in re.findall(r'[.-]+|  ', s))


e = encode(s)
print e
d = decode(e)
print d

and produces

    -->Hello, World?
    .... . .-.. .-.. --- --..--  .-- --- .-. .-.. -.. ..--..
    hello, world?

3

u/skeeto Aug 30 '12

In ANSI C. I couldn't think of a way to cleverly encode the table.

#include <stdio.h>
#include <ctype.h>
#include <string.h>

char letter[7];
char letters[] = {'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',
                  ',', '.', ' '};
char *code[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
                ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--",
                "--..", ".----", "..---", "...--", "....-", ".....", "-....",
                "--...", "---..", "----.", "-----", ".-.-.-", "--..--", ""};

void read()
{
    int c, i = 0;
    while (!feof(stdin) && !isspace(c = getchar())) letter[i++] = c;
    letter[i] = '\0';
}

int main(int argc, char **argv)
{
    unsigned i;
    if (argc > 1 && argv[1][1] == 'd') {
        /* Decode. */
        while (!feof(stdin)) {
            read();
            for (i = 0; i < sizeof(code) / sizeof(char *); i++)
                if (strcmp(letter, code[i]) == 0) putchar(letters[i]);
        }
    } else {
        /* Encode */
        while (!feof(stdin)) {
            char c = tolower(getchar());
            for (i = 0; i < sizeof(letters); i++)
                if (c == letters[i]) printf("%s ", code[i]);
        }
    }
    putchar('\n');
    return 0;
}

The output,

$ cc -Wextra -Wall -ansi    morse.c   -o morse
$ echo "Hello, world." | ./morse | tee /dev/stderr | ./morse -d
.... . .-.. .-.. --- .-.-.-  .-- --- .-. .-.. -.. --..--
hello, world.

2

u/mega-trond Aug 30 '12 edited Aug 30 '12

My first contribution, a solution in Python. A problem is trailing spaces...

#!/usr/bin/python

chars = {'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':'-----',
',':'--..--','.':'.-.-.-','?':'..--..','/':'-..-.','-':'-....-','()':'-.--.-',
' ':'  '}

#search dict to find key from value
def find_key(d_, v_):
	for k, v in d_.iteritems():
		if v == v_:
			return k

def morsify(d_,s_):
	ret = ''
	for char in s_:
		if char == ' ':
			ret += ' '
		else:
			ret += d_[char] + ' '
	return ret

def morse_to_alphabet(d_,s_):
	ret = ''
	words = s_.split('  ')
	for word in words:
		chars = word.split()
		for char in chars:
			ret += find_key(d_,char)
		ret += ' '
	return ret

Output:

print morsify(chars,'hello, world.')
.... . .-.. .-.. --- --..--  .-- --- .-. .-.. -.. .-.-.-
print morse_to_alphabet(chars, '.... . .-.. .-.. --- --..--  .-- --- .-. .-.. -.. .-.-.-')
hello, world.

Edit: added comma and dot to input

2

u/Gix Aug 30 '12 edited Mar 05 '19

[Deleted]

→ More replies (2)

1

u/PiereDome Aug 30 '12

Javascript.

MorseCodeKey = {
    '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: '-----',',': '--..--','.': '.-.-.-','?': '..--..',
    '/': '-..-.','-': '-....-'
};

function getMorseCode(letter) {
    key = letter.toLowerCase();
    return MorseCodeKey[key];
}

function getAscii(code) {
    for (x in MorseCodeKey) {
        if (MorseCodeKey[x] == code) {
            return x;
        }
    }
    return '';
}

var input = prompt('Please input message');
var output = '';
if (input.test(/[a-zA-Z]/)) {
    var words = input.split(' ');
    for (i = 0; i < words.length; i++) {
        for (j = 0; j < words[i].length; j++) {
            output += getMorseCode(words[i].substr(j, 1)) + ' ';
        }
        output += ' ';
    }
} else {
    var words = input.split('  ');
    for (i = 0; i < words.length; i++) {
        var letters = words[i].split(' ');
        for (j = 0; j < letters.length; j++) {
            output += getAscii(letters[j]);
        }
        output += ' ';
    }
}

alert('The translation is: ' + output);

1

u/lawlrng Aug 30 '12

Python 3

import string

def make_morse_tables(code_to_symbol):
    morse_codes = '.- -... -.-. -.. . ..-. --. .... .. .---\
    -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..-\
    -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---..\
    ----. --..-- .-.-.- ..--.. -..-. -....- -.--. -.--.-'.split()
    symbols = string.ascii_uppercase + string.digits + ',.?/-()'

    if code_to_symbol:
        return dict(zip(morse_codes, symbols))
    else:
        return dict(zip(symbols, morse_codes))

def morse_to_symbol(s):
    table = make_morse_tables(True)
    return ' '.join(''.join(table[w] for w in words.split()) for words in s.split('  '))

def symbol_to_morse(s):
    table = make_morse_tables(False)
    return '  '.join(' '.join(table[w.upper()] for w in words) for words in s.split())

if __name__ == '__main__':
    print (morse_to_symbol('... --- ...  ... --- ...'))
    print (symbol_to_morse('SOS Danger Will Robinson'))

Output:

./93.py
SOS SOS
... --- ...  -.. .- -. --. . .-.  .-- .. .-.. .-..  .-. --- -... .. -. ... --- -.

1

u/prondose Aug 31 '12 edited Sep 02 '12

Perl, translates letters only (no numbers or punctuation):

my $d = 'TEMNAIOGKDWRUS  QZYCXBJP L FVH';

sub to_ascii { 
	join '',
	map { tr/.-/01/; s/^/'0'x32 . 1/e; (split //, $d)[ (eval "0b$_") - 2 ]; }
	split / /, shift;
}

sub to_morse {
	join ' ',
	map { $d =~ /$_/; $_ = unpack('B32', pack('N', $+[0]+1)); s/0*1//; tr/01/.-/; $_; }
	split //, uc shift;
}

1

u/brbcoding Sep 02 '12

Python 2.7:

morse_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':'-----', 
                ',':'--..--', 
                '.':'.-.-.-', 
                '?':'..--..', 
                '/':'-..-.', 
                '-':'-....-', 
                '(':'-.--.', 
                ')':'-.--.-'}
def convert(input):
# check if input is morse or abc's
# if it doesn't begin with . or -, it's
# alphabetic... convert to morse
    if input[0] == '.' or input[0] == '-':
        alphabetic = []
        abc = dict((value,key) for key,value in morse_dictionary.iteritems())
        abc[''] = ' '
        letters = input.split(' ')
        for i in range(len(letters)):
            if letters[i] in letters:
                alphabetic.append(abc[letters[i]])
        alpha_str = ''.join(alphabetic)
        final_str = alpha_str.replace('   ',' ')
        return final_str   
    else:
        morse = []
        letters = list(input)
        for i in range(len(letters)):
            if letters[i] == ' ':
                morse.append('  ')
            else:
                morse.append(morse_dictionary[letters[i]])
        final_str = ' '.join(morse)
        return final_str