This is another in a series of Ruby programming challenges that we do to keep the tech skills strong on our test team.
This challenge starts with some existing code. This script was written to find the longest word that can be written using only the letters in the top of keys on a keyboard. The script opens a web site with Scrabble words and reads in all the words and then processes against an algorithm (BTW, the algorithm can be written more efficiently).
Here is the challenge: Based on the existing code, enhance it (or scrap it completely) so that it useful as a Scrabble utility. 1. Given a list of characters (“ASFAGJS”, for example), determine the longest Scrabble word that can be created (Scrabble rules: each character can be used only once). 2. Also, given the same list of characters, determine what word scores highest (http://en.wikipedia.org/wiki/Scrabble_letter_distributions#English).
BTW, depending on how you run this script, there is an inefficiency that you may want to solve. Each time the existing code runs, it goes to the internet to get the word list. If your script runs for more than one set of characters, it would be efficient if you get the list of words only once.
While working on this challenge, I expect you will need to be comfortable with ruby arrays and hashes. If the solution comes easy for you, feel free to enhance things further – be creative!
Here is the existing code:
require 'open-uri'
def restrict(html, starting_regexp, stopping_regexp)
start = html.index(starting_regexp)
stop = html.index(stopping_regexp, start)
html[start...stop]
end
url = 'http://homepage.ntlworld.com/adam.bozon/Dictionary.htm'
page = open(url)
text = page.read; nil
words = restrict(text, /AA/, /ZYZZYVAS/)
array_words = words.split
@longest_word = ''
letters = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P']
array_words.each do |word|
@all_okay = true
word.each_char.each do |character|
if (letters.include? character).to_s == 'false' then
@all_okay = false
break
end
end
if @all_okay then
puts word
if word.size > @longest_word.size then
@longest_word = word
end
end
end
puts @longest_word
def restrict(html, starting_regexp, stopping_regexp)
start = html.index(starting_regexp)
stop = html.index(stopping_regexp, start)
html[start...stop]
end
url = 'http://homepage.ntlworld.com/adam.bozon/Dictionary.htm'
page = open(url)
text = page.read; nil
words = restrict(text, /AA/, /ZYZZYVAS/)
array_words = words.split
@longest_word = ''
letters = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P']
array_words.each do |word|
@all_okay = true
word.each_char.each do |character|
if (letters.include? character).to_s == 'false' then
@all_okay = false
break
end
end
if @all_okay then
puts word
if word.size > @longest_word.size then
@longest_word = word
end
end
end
puts @longest_word