The challenge
The shortest code by character count, that will input a string using only alphabetical characters (upper and lower case), numbers, commas, periods and question mark, and returns a representation of the string in Morse code.
The Morse code output should consist of a dash (-
, ASCII 0x2D) for a long beep (AKA 'dah') and a dot (.
, ASCII 0x2E) for short beep (AKA 'dit').
Each letter should be separated by a space (' '
, ASCII 0x20), and each word should be separated by a forward slash (/
, ASCII 0x2F).
Morse code table:
alt text http://liranuna.com/junk/morse.gif
Test cases:
Input:
Hello world
Output:
.... . .-.. .-.. --- / .-- --- .-. .-.. -..
Input:
Hello, Stackoverflow.
Output:
.... . .-.. .-.. --- --..-- / ... - .- -.-. -.- --- ...- . .-. ..-. .-.. --- .-- .-.-.-
Code count includes input/output (that is, the full program).
Python (210 characters)
This is a complete solution based on Alec's one
Here's my contribution as a console application in VB.Net
I left he white space in to make it readable. Totals 1100 characters. It will read the input from the command line, one line at a time, and send the corresponding output back to the output stream. The compressed version is below, with only 632 characters.
Python 3 One Liner: 172 characters
(Encoding the tranlation table into unicode code points. Works fine, and they display here fine in my test on my Windows Vista machine.)
Edited to pare down to 184 characters by removing some unnecessary spaces and brackets (making list comps gen exps).
Edit again: More spaces removed that I didn't even know was possible before seeing other answers here - so down to 176.
Edit again down to 172 (woo woo!) by using ' '.join instead of ''.join and doing the spaces separately. (duh!)
C# Using Linq (133 chars)
OK, so I cheated. You also need to define a dictionary as follows (didn't bother counting the chars, since this blows me out of the game):
Still, can someone provide a more concise C# implementation which is also as easy to understand and maintain as this?
C (248 characters)
Another tree-based solution.
Could be errors in source tree because wikipedia seems to have it wrong or maybe I misunderstood something.
REBOL (118 characters)
A roughly 10 year-old implementation
Quoted from: http://www.rebol.com/oneliners.html
(no digits though and words are just separated by double spaces :/ ...)