diff --git a/examples/dictionary_scan.rb b/examples/dictionary_scan.rb index 1b6ad20..1732b18 100644 --- a/examples/dictionary_scan.rb +++ b/examples/dictionary_scan.rb @@ -1,30 +1,41 @@ require_relative '../lib/wordplay' +# Determine the longest words in the supplied group. +# +# words - Array +# +# Returns an Array. +def longest_words(words) + words.sort_by { |w| w.size }.tap do |sorted| + longest = sorted.last.size + sorted.delete_if { |w| w.size < longest } + end.sort +end + SOURCE = '/usr/share/dict/words' raise "Dictionary not available!" unless File.exists?(SOURCE) -match_count = 0 full_count = 0 -longest_words = [""] +ordered_words = [] +palindromes = [] # Loop the source file for words to check File.foreach(SOURCE, "\n") do |word| word.strip! # remove the linefeeds if word.size > 1 # exclude one-character words - if Wordplay.new(word).ordered_letters? - puts word - match_count += 1 - longest_words << word if word.size >= longest_words.last.size - end + wordplay = Wordplay.new(word) + + ordered_words << word if wordplay.ordered_letters? + palindromes << word if wordplay.palindrome? full_count += 1 end end -longest = longest_words.last.size -longest_words.delete_if { |w| w.size < longest } +longest_ordered_words = longest_words(ordered_words) +longest_palindromes = longest_words(palindromes) -puts "\nMatching words: #{match_count} out of #{full_count}" -puts "Longest words: #{longest_words.join(', ')}" +puts "Ordered words (#{ordered_words.size} of #{full_count}), longest: #{longest_ordered_words.join(', ')}" +puts "Palindromes (#{palindromes.size} of #{full_count}), longest: #{longest_palindromes.join(', ')}"