# \[SOLUTION\] Morse Code (#121)

**URL:** <https://www.ruby-forum.com/t/solution-morse-code-121/92947>\
**Category:** Ruby\
**Created:** [April 25, 2007, 11:43pm UTC](https://www.ruby-forum.com/t/solution-morse-code-121/92947 "2007-04-25T23:43:34Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Brian\_Krahmer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/8dc957/32.png) [@Brian\_Krahmer](https://www.ruby-forum.com/u/Brian_Krahmer)\
**Post date:** [April 25, 2007, 11:43pm UTC](https://www.ruby-forum.com/t/solution-morse-code-121/92947/1 "2007-04-25T23:43:34Z")

</div>

Here is my solution to the morse code problem. The meat of is only  
about 10 lines, and I think it’s pretty readable, so hopefully it will  
be viewed as a good solution. I used the dictionary installed on my  
ubuntu system to display a \* after words found in it. BTW, this is my  
first submission.

brian

require ‘singleton’

class Word  
LETTERS = [[’.-’, ‘A’], [’-.’, ‘N’], [’-…’, ‘B’], [’—’, ‘O’],  
[’-.-.’, ‘C’], [’.–.’, ‘P’], [’-…’, ‘D’], [’–.-’, ‘Q’], [’.’,  
‘E’],  
[’.-.’, ‘R’], [’…-.’, ‘F’], [’…’, ‘S’], [’–.’, ‘G’], [’-’, ‘T’],  
[’…’, ‘H’], [’…-’, ‘U’], [’…’, ‘I’], [’…-’, ‘V’], [’.—’,  
‘J’],  
[’.–’, ‘W’], [’-.-’, ‘K’], [’-…-’, ‘X’], [’.-…’, ‘L’], [’-.–’,  
‘Y’],  
[’–’, ‘M’], [’–…’, ‘Z’] ]

def initialize(word)  
@morse = word  
end

def parse  
check\_match(0, [], 0)  
end

def check\_match(word\_offset, found\_letters, found\_letters\_length)  
if found\_letters\_length == @morse.size  
word = found\_letters.join(’’)  
print word  
print ’ \*’ if Dictionary.instance.has\_word?(word)  
puts  
return  
end  
0.upto(LETTERS.size-1) do |index|  
morse\_letter = LETTERS[index][0]  
next if word\_offset + morse\_letter.size \> @morse.size  
if @morse[word\_offset…(word\_offset + morse\_letter.size - 1)] ==  
morse\_letter  
check\_match(word\_offset + morse\_letter.size,  
found\_letters.clone.push(LETTERS[index][1]),  
found\_letters\_length + morse\_letter.size)  
end  
end  
end

end

class Dictionary  
include Singleton

def load  
@entries = {}  
File.open(’/usr/share/dict/words’) do |file|  
file.each\_line do |line|  
@entries[line.chomp.upcase] = 1  
end  
end  
end

def has\_word?(word)  
@entries[word]  
end

end

Dictionary.instance.load

until $stdin.eof?  
Word.new($stdin.gets.chomp).parse  
end
