Code golf: Morse code translator

I don’t think Morse code has any application in bioinformatics, but I though I would share this anyway.

The private beta for StackExchange’s Code Golf & Programming Puzzles Q&A site just launched yesterday and, having committed to this forum previously, I was invited to participate (I actually posted the first answer on the site!). The idea behind code golf is to try to solve a programming problem using as little code as possible. I think this is a great way to keep programming and analytical thinking skills sharp, whatever your work or research interests are. I must admit that I’m more interested in solving puzzles than I am about getting the shortest code possible.

Anyway, one of the puzzle challenges posted today was to write code to convert alphanumeric characters to Morse code. Here is my solution in Perl. I’ve added line breaks so it will fit in the page, but it’s intended to be all on one line.

%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"$_"}}}

This can be executed directly from the command line without having to create any source code files.

$ echo 'HERE IS SOME ENGLISH' | perl -e '%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"$_"}}}'
.... . .-. .  .. ...  ... --- -- .  . -. --. .-.. .. ... ....
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s