Ruby Quiz <james@grayproductions.net> writes:
This week's quiz is to write program that displays all possible translations for
ambiguous words provided in code.Your program will be passed a word of Morse code on STDIN. Your program should
print all possible translations of the code to STDOUT, one translation per line.
Your code should print gibberish translations in case they have some meaning for
the reader, but indicating which translations are in the dictionary could be a
nice added feature.
This is my solution with the Morse code passed as argument; you can
enable a directory by passing -d.
It uses simple recursion.
#!ruby -s
$morse = Hash[*%w{
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 --..
}].invert
if $d
words = {}
File.readlines("/usr/share/dict/words").each { |word|
words[word.downcase.chomp] = true
}
end
def allmorse(s, t="", &b)
if s.empty?
yield t
else
1.upto(s.size) { |n|
$morse[s[0,n]] && allmorse(s[n..-1], t+$morse[s[0,n]], &b)
}
end
end
allmorse (ARGV[0] || ".-...--...-.--").delete("^.-") do |word|
puts word if !$d || words.include?(word.downcase)
end
__END__
Example:
$ ruby quiz121.rb
ETEEETTEEETETT
ETEEETTEEETEM
ETEEETTEEETAT
ETEEETTEEETW
ETEEETTEEENTT
: : : :
LPUW
LPFTT
LPFM
$ ruby quiz121.rb -d
RUBY
$ ruby quiz121.rb -d ...././.-../.-../---
HELLO
···
--
Christian Neukirchen <chneukirchen@gmail.com> http://chneukirchen.org