Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.40 KB | None | 0 0
  1. # Statement Devise a function that gets one parameter 'w' and returns all the
  2. # anagrams for 'w' from the file wl.txt. The file wl.txt contains a huge list of
  3. # valid words and the idea is to find the anagrams of ‘w’ included in such a
  4. # list.
  5. #
  6. #   "Anagram": An anagram is a type of word play, the result of rearranging the
  7. # letters of a word or phrase to produce a new word or phrase, using all the
  8. # original letters exactly once; for example orchestra can be rearranged into
  9. # carthorse.
  10. #
  11. #   anagrams("horse") should return: ['heros', 'horse', 'shore']
  12. #
  13. # You can assume the absolute/relative path to wl.txt to be fixed and, therefore
  14. # hardcore in the code, or you can also change the firm of the method to for
  15. # example anagrams("horse", ./wl.txt).
  16. #
  17. class AnagramCalculator
  18.   attr_reader :database_file
  19.  
  20.   def initialize(database_file:)
  21.     @database_file = database_file
  22.   end
  23.  
  24.   def call(input)
  25.     database
  26.       .select { |w| w.length == input.length }
  27.       .select { |w| anagram?(input, w) }
  28.   end
  29.  
  30.   private
  31.  
  32.   def database
  33.     @database ||= File.read(database_file).split("\n")
  34.   end
  35.  
  36.   def anagram?(word1, word2)
  37.     word2_bytes = word2.bytes
  38.  
  39.     word1.bytes.select do |b|
  40.       word2_bytes.delete(b).nil?
  41.     end.empty?
  42.   end
  43. end
  44.  
  45. database_file = '/Users/dpereira/Downloads/wl.txt'
  46. puts AnagramCalculator
  47.   .new(database_file: database_file)
  48.   .call('esroh')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement