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

B

Brian Krahmer

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top