Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

International Morse Code

share|improve this question
    
Are both capital and lowercase letters encoded? –  Joey Adams Jan 28 '11 at 15:00
2  
Also, could you provide a sample input and output to clarify details like spacing between words? –  Joey Adams Jan 28 '11 at 15:12
    
Well, in Morse, there's no difference between lower and upper case. There's no real symbol for space (it's just a 3/4 times silence) so I guess it should be translated as a space. –  Shikiryu Jan 28 '11 at 15:20
    
@Joey: The details are up to you. –  Alexandru Jan 28 '11 at 15:49
    
Similar to the Stack Overflow question Code Golf: Morse code. –  dmckee Jan 28 '11 at 16:04

13 Answers 13

up vote 6 down vote accepted

Golfscript - 74 chars

This answer supports only uppercase and digits. The letters are separated by newlines and words are separated by 2 newlines

{." ETIANMSURWDKGOHVF L PJBXCYZQ"?)"?/'#! 08<>"@))10%=or 2base(;{!45+}%n}%

Analysis

    { }%          as usual works like a map over the array
    .             push a copy of the char onto the stack
    " ETIAN..."   this is a lookup table for the uppercase characters
    ?             like a string.find returns the index of the char in the string
                  or -1 if it is not found (ie it's a digit)
    )             increment that index so E=>2 T=>3 I=>4 etc. notice that if the
                  char is not an uppercase letter or space this is now 0 (False)
    "?/'#!..."    this is a lookup table for the digits. it will be used in the
                  reverse way to the other lookup table.
    @             pull that copy we made of the char to the top of the stack
    ))%10         convert ascii digit to a number by adding 2 and taking mod 10.
                  It's important to do it this way because all the uppercase
                  letters hit this code too, and we need to make sure they fall
                  in the range 0..9 or the next step will fail.
    =             pull the nth char from the string eg "Hello"1= gives "e"
    or            remember if the uppercase lookup fails we have a 0 result, so
                  the digit lookup will be used
    2base         convert to base 2 so E=>[1 0], T=>[1 1], I=>[1 0 0] etc.
    (;            pop the front of the list and throw it away so E=>[0], T=>[1]
    {!45+}%       negate each bit and add 45, this gives ascii value of . and -
    n             newline separates each word. this could be 32 if you wanted to
                  separate the words with spaces for a cost of 1 stroke

Golfscript - 85 chars

This is shorter than my SO answer due to the relaxed requirements here The input must be uppercase/digits and the punctuation characters ".,?"

{." ETIANMSURWDKGOHVF!L!PJBXCYZQ"?)"UsL?/'#! 08<>"@".,?"58,48>+?=or
2base(;{!45+}%n}%

Since the punctuation is not even required here, I may shorten the answer even more

My answer from SO
Golfscript - 107 chars

newline at the end of the input is not supported, so use something like this

echo -n Hello, Codegolfers| ../golfscript.rb morse.gs

Letters are a special case and converted to lowercase and ordered in their binary positions. Everything else is done by a translation table

' '/{{.32|"!etianmsurwdkgohvf!l!pjbxcyzq"?)"UsL?/'#! 08<>"@".,?0123456789"?=or
2base(;>{'.-'\=}%' '}%}%'/'*
share|improve this answer
    
The order of your code blocks here is confusing George's UserScript. Could I trouble you to rearrange? And I would like to see it explained. I get the implicit tree, but the rest is a mystery to me. –  dmckee Feb 13 '11 at 3:03
    
@dmckee, done. George's script noticed my count was out by one, so I fixed that too –  gnibbler Feb 13 '11 at 3:06
    
Requiring upvotes to see the analysis... boo! The analysis is what makes answers worth the upvotes! –  NickLarsen Feb 14 '11 at 14:05
    
@Nick, ok I think it's as short as I can get it, so I'll get to work on that analysis –  gnibbler Feb 16 '11 at 11:24

C# (213 characters)

I'm sure this wont stand long, but at least I got the technique here first!

class P{static void Main(string[] a){foreach(var t in a[0]){var c="";for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;System.Console.Write(c+"  ");}}}

And in readable format:

class P
{
    static void Main(string[] a)
    {   
        foreach(var t in a[0])
        {
            var c="";
            for(int i=" ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(t);i>0;i/=2)c="-."[i--%2]+c;
            System.Console.Write(c+" ");
        }
    }
}

For a brief explanation, the string of characters is a heap in which the left child is a dot and the right child is a dash. To build the letter, you traverse back up and reverse the order.

share|improve this answer
1  
This is the best idea I've seen so far. –  Alexandru Jan 28 '11 at 19:37
    
And then I read the linked thread and noticed this is far from original. –  NickLarsen Jan 28 '11 at 22:08
1  
When I saw the ETIAN... in there, I assumed it worked the same as the golfscript, but you have a different way of interpreting the string. I think it is equivalent but I add 1 to the index and use the binary representation to get the dots and dashes for all the digits after the leading 1" eg F=>18=>0b10010=>..-. –  gnibbler Feb 13 '11 at 21:23

tr + sed (347)

tr a-z A-Z | sed 's/0/--O/g;s/1/.-O/g;s/2/.J/g;s/3/..W/g;s/4/.V/g;s/5/.H/g;
 s/6/-.H/g;s/7/-B/g;s/8/-Z/g;s/9/--G/g;s/X/-U/g;s/V/.U/g;s/U/.A/g;
 s/Q/-K/g;s/K/-A/g;s/A/.T/g;s/J/.O/g;s/O/-M/g;s/Y/-W/g;s/W/.M/g;
 s/M/-T/g;s/T/- /g;s/H/.S/g;s/B/-S/g;s/S/.I/g;s/L/.D/g;s/Z/-D/g;
 s/D/-I/g;s/I/.E/g;s/C/-R/g;s/F/.R/g;s/R/.N/g;s/P/.G/g;s/G/-N/g;
 s/N/-E/g;s/E/. /g'
share|improve this answer
    
+1 for using strictly command-line tools! –  Daniel Standage Jan 28 '11 at 16:02
1  
The space around a pipe could be eliminated as well ;-) –  Yasir Arsanukaev Jan 28 '11 at 17:01
1  
Yes, I'm not counting those spaces, I just print them here for clarity :) –  Eelvex Jan 28 '11 at 17:04
2  
You could use brace expansion to shorten it lots (/g;s/ becomes , -- plus a bit of overhead). –  Nabb Feb 3 '11 at 12:56
1  
You can drop the tr, use sed's y command instead –  Hasturkun Feb 13 '11 at 17:52

Haskell — 314 292 291 characters

import Data.List
i=intercalate
m=i"       ".map(i" ".map(\c->words".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."!!(head.findIndices(==c)$['a'..'z']++['0'..'9']))).words

A more user readable form:

tbl :: [String]
tbl = words ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----."

lookupChar :: Char -> String
lookupChar c = tbl !! (fromJust . elemIndex c $ ['a'..'z'] ++ ['0'..'9'])

encWord :: String -> String
encWord = intercalate " " . map lookupChar

encSent :: String -> String
encSent = intercalate "       " . map encWord . words

Sample run:

*Main> m "welcome humans"
".-- . .-.. -.-. --- -- .       .... ..- -- .- -. ..."

There's a single whitespace between two letters, and seven whitespaces between two words.

share|improve this answer
    
Just checked the question referenced by @dmckee "Code Golf: Morse code" and didn't find a Haskell version. I think, shorter than 314 would be possible. –  Yasir Arsanukaev Jan 28 '11 at 17:33
    
fromJust.elemIndex c can be written as head.findIndices(==c). That is one character more, but you can then get rid of import Data.Maybe, so you'll save 17 characters total. You can also save two characters by removing the space in front of the string each time you call intercalate. And another few characters by doing i=intercalate at the beginning and replacing the two calls to intercalate with i. –  sepp2k Feb 1 '11 at 16:25
    
@sepp2k: Nice idea! Thanks. I also played with intercalate and have saved another 6 characters! :-) –  Yasir Arsanukaev Feb 1 '11 at 16:54
    
You can also do w=words, which saves one character if I'm not mistaken. And instead of l c=... and map l, you should do map\c->... (you don't even need parens around the lambda since there's already a closing paren afterwards anyway). –  sepp2k Feb 1 '11 at 17:02
    
@sepp2k: Inlining of l c=... did save me 1 character, but I couldn't put it without parens, only as map(\c->...). GHC version 6.12.3. –  Yasir Arsanukaev Feb 1 '11 at 17:15

Ruby (161)

d=proc{|x|x>1?d[x/2]+".-"[x&1]:' '}
$><<$<.gets.bytes.map{|i|
e=i>64?"-@B4*:68,?5</.7>E20+193ACD"[(i&95)-65]:i>47?"gWOKIHX`df"[i-48]:nil
e ?d[e.ord-40]:i.chr}*''

Encodes each digit into a single char, where 1 is dash, 0 is dot, with a leading 1 as a marker bit (+ an offset to keep it printable. Uses ASCII math to use the input chars as lookup indices.

share|improve this answer

Lisp (532 466 chars)

(loop(princ(let((c(read-char)))(case c(#\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"----- ")(t c)))))

This encodes lower case letters, and morse code sequences are printed with a trailing space

share|improve this answer

Perl6 (238)

my%h="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--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.".split(/<wb>/)[1..72];while$*IN.getc ->$c{print %h{$c.uc}||$c}

Readable version

# Split string on word breaks to create a hash
# I get an extra token at the beginning and end for some reason
# [1..72] is a slice without the extra pieces
my %h = "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--..0-----1.----2..---3...--4....-5.....6-....7--...8---..9----."
    .split(/<wb>/)[1..72];

# For each character in STDIN, print either the looked up value, or itself
while $*IN.getc -> $c {
    print %h{$c.uc} || $c;
}
share|improve this answer

In Java, 475 characters.

    import java.io.*;class M{public static void main(String[]b){String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}

Translates a-z, A-Z and 0-9.

Edit:

Or in 447 characters, if you don't mind Java throwing an error after the translation.

    import java.io.*;class M{static{String s,t="-",m=t+t,o=m+t,z="",e=".",i=e+e,p=t+e,a=e+t,n=i+e,c[]={o+m,a+o,i+o,n+m,n+a,n+i,p+n,m+n,o+i,o+p,z,z,z,z,z,z,z,a,t+n,p+p,t+i,e,i+p,m+e,n+e,i,e+o,p+t,a+i,m,p,o,a+p,m+a,e+p,n,t,i+t,n+t,e+m,p+a,p+m,m+i};BufferedReader r=new BufferedReader(new InputStreamReader(System.in));try{s=r.readLine().toUpperCase();for(int j=48;j<91;j++)s=s.replace(z+(char)j,c[j-48]+" ");System.out.println(s);}catch(Exception x){}}}
share|improve this answer

Postscript (310) (462) (414) (319) including (46) for the table.

Combined numbers and letters with a ternary encoding. 5 ternary digits fit in a byte! This eliminates those silly difference loops, and special-casing numbers entirely.

ASCII85 cuts 1/3 of each table. And simplifying the code (finally!) gets back under 400!

errordict/undefined{pop( )dup 0 4 3 roll put print{}}put<</*{{[exch/@ cvx]cvx 1
index 1 add}forall pop}def/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def/#{load
exec}/P{print}0{}1{(.)P}2{(---)P}/S{( )P}48<~o'u/0b'A;]L7n~>* 65 C 97 C/@{5{dup
3 mod # S 3 idiv}repeat # S S S}>>begin{(%stdin)(r)file read not{exit}if #}loop

Sample output

Luser Dr00g!
. --- . .     . . ---      . . .      .        . --- .          --- . .      . --- .      --- --- --- --- ---    --- --- --- --- ---    --- --- .      !

Ungolfed and commented. I'm very proud of this one. I feel it's elegant, making the numbers do the work. :)

%!
%Morse Code Translator (Simplified)

%if `load` signals /undefined in /#{load exec},
%  pop --load--,
%  print the char,
%  leave dummy object for `exec` to find
errordict/undefined{pop( )dup 0 4 3 roll put print{}}put

<<
%create int->proc pairs
%from initial int and string values
/*{{[exch/@ cvx]cvx 1 index 1 add}forall pop}def

%the alpha map is applied to Upper and Lower case
/C{<~#:VD<!AP07"A]ga#R),'7h?+2(./s-9e6~>*}def
65 C 97 C

%the number map
48<~o'u/0b'A;]L7n~>*

/#{load exec}  %execute a number
/P{print}

0{}       % 0: nop
1{(.)P}   % 1: '.' dit
2{(---)P} % 2: '---' dah
/S{( )P}  % S: space

%execute a morse sequence, from the table
/@{5{dup 3 mod # S 3 idiv}repeat # S S S}
>>begin

%read and execute each char from stdin
{(%stdin)(r)file read not{exit}if #}loop

The tables (33)+(13)=(46)

Here's how the strings encode the table. Each byte represents a 5-digit ternary number. And the bytes are further encoded in ASCII85 (which postscript can automagically decode).

%The Morse Table in Ternary Encoding
% 3  ^4 ^3 ^2 ^1 ^0
%    81 27  9  3  1                 Dec  Hex  dc ->ASCII85
%   ---------------                 ---  ---  ---
% A            2  1            6+1    7    7  7 256*41+256*50+256*14+
% B      1  1  1  2      27+ 9+3+2   41   29  d85%n85/d85%n85/d85%n85/d85%n85/n
% C      1  2  1  2      27+18+3+2   50   32  2 25 53 35 27  chr(x+33)
% D         1  1  2          9+3+2   14    E  #  :  V  D  <
% E               1              1    1    1
% F      1  2  1  1      27+18+3+1   49   31
% G         1  2  2          9+6+2   17   11  0 32 47 15 22
% H      1  1  1  1      27+ 9+3+1   40   28  !  A  P  0  7
% I            1  1            3+1    4    4
% J      2  2  2  1      54+18+6+1   79   4F
% K         2  1  2         18+3+2   23   17  1 32 60 70 64
% L      1  1  2  1      27+ 9+6+1   43   2B  "  A  ]  g  a
% M            2  2            6+2    8    8
% N            1  2            3+2    5    5
% O         2  2  2         18+6+2   26   1A  2 49 8 11 6
% P      1  2  2  1      27+18+6+1   52   34  #  R )  , '
% Q      2  1  2  2      54+ 9+6+2   71   47
% R         1  2  1          9+6+1   16   10
% S         1  1  1          9+3+1   13    D  22 71 30 10 17
% T               2              2    2    2   7  h  ?  +  2
% U         2  1  1         18+3+1   22   16
% V      2  1  1  1      54+ 9+3+1   67   43
% W         2  2  1         18+6+1   25   19  7 13 14 82 12
% X      2  1  1  2      54+ 9+3+2   68   44  (  .  /  s  -
% Y      2  2  1  2      54+18+3+2   77   4D  77 256*44+256*256*
% Z      1  1  2  2      27+ 9+6+2   44   2C  24 68 21 [23 36]
%                                              9  e  6 [ 8  E] (omit final 2)
% 0   2  2  2  2  2  162+54+18+6+2  242   F2
% 1   2  2  2  2  1  162+54+18+6+1  241   F1
% 2   2  2  2  1  1  162+54+18+3+1  238   EE  78 6 84 14 15
% 3   2  2  1  1  1  162+54+ 9+3+1  229   E5   o '  u  /  0
% 4   2  1  1  1  1  162+27+ 9+3+1  202   CA
% 5   1  1  1  1  1   81+27+ 9+3+1  121   79
% 6   1  1  1  1  2   81+27+ 9+3+2  122   7A  65 6 32 26 60
% 7   1  1  1  2  2   81+27+ 9+6+2  125   7D   b '  A  ;  ]
% 8   1  1  2  2  2   81+27+18+6+2  134   86  134 256*161+256*256*
% 9   1  2  2  2  2   81+54+18+6+2  161   A1  43 22 77 [50 40]
%                                              L  7  n [ S  I] (omit final 2)
share|improve this answer

Perl (489 chars)

%c=("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=>"-----");while(<>){foreach(split(//)){if(exists($c{$_})){printf"%s ",$c{$_}}else{print"$_"}}}

Can be executed via command line like so.

$ perl -e '$CODE' < textfile

Edit: Thanks @tobyodavies for pointing out that my original solution had the translation backwards!

share|improve this answer
1  
doesn't this translate from morse to ascii? which is backwards... –  tobyodavies Jan 28 '11 at 16:18

PHP, 474 characters

<?$a=strtoupper(fgets(STDIN));$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];

Its 462 characters if all input is in uppercase:

<?$a=fgets(STDIN);$m=array(65=>".-",66=>"-...",67=>"-.-.",68=>"-..",69=>".",70=>"..-.",71=>"--.",72=>"....",73=>"..",74=>".---",75=>"-.-",76=>".-..",77=>"--",78=>"-.",79=>"---",80=>".--.",81=>"--.-",82=>".-.",83=>"...",84=>"-",85=>"..-",86=>"...-",87=>".--",88=>"-..-",89=>"-.--",90=>"--..",49=>".----",50=>"..---",51=>"...--",52=>"..---",53=>".....",54=>"-....",55=>"--...",56=>"---..",57=>"----.",48=>"-----",32=>" ");while($i++<strlen($a))echo$m[ord($a[$i])];
share|improve this answer

C, 162 chars

char M[256] = "_^\\XP@ACGO       &15)\"4+0$>-2'%/6;*(#,8.9=3", v;
main(c) {
  for (;
         c = getchar(), v = M[c + 208 & 255] - 32, ~c;
         putchar(v-1? c : 32))
    for (; v > 1; v /= 2) putchar(".-"[v & 1]);
}

M is a lookup table where the characters' bitpatterns correspond to dots and dashes in the morse code. Characters [0-9A-Z] are decoded to morse using this table (with a space appended after the morse code), other characters are simply passed through unchanged.

Sample run:

HELLO WORLD
.... . .-.. .-.. ---  .-- --- .-. .-.. -.. 
hello world
hello world
ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.. ----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. 
share|improve this answer

VB.net (lots)

Module Module1
 Sub Main(a$())
   For Each c In a(0)
     Dim i = "ETIANMSURWDKGOHVF L PJBXCYZQ  54 3   2       16       7   8 90".IndexOf(c)
     If c <> " " And i >= 0 Then
       Console.Write("{0} ", Morse(i))
     Else
       Console.Write(c)
     End If
   Next
End Sub

Function Morse(i) As String
  Dim b = Math.Log(i) / Math.Log(2)
  Return (From m In MorseSeq(If(Double.IsInfinity(b), 0, b)) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i < 0, {}, From n In ".-" From m In MorseSeq(i - 1).DefaultIfEmpty
                       Select n & m)
End Function
End Module

That last function is evil.

edit A couple of improvements.

Function Morse(i) As String
  Return (From m In MorseSeq(i) Order By m.Length)(i)
End Function

Function MorseSeq(i) As IEnumerable(Of String)
  Return If(i=0,{".","-"},From n In".-"From m In MorseSeq(i>>1) Select n & m)
End Function
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.