Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Statement Devise a function that gets one parameter 'w' and returns all the
- # anagrams for 'w' from the file wl.txt. The file wl.txt contains a huge list of
- # valid words and the idea is to find the anagrams of ‘w’ included in such a
- # list.
- #
- # "Anagram": An anagram is a type of word play, the result of rearranging the
- # letters of a word or phrase to produce a new word or phrase, using all the
- # original letters exactly once; for example orchestra can be rearranged into
- # carthorse.
- #
- # anagrams("horse") should return: ['heros', 'horse', 'shore']
- #
- # You can assume the absolute/relative path to wl.txt to be fixed and, therefore
- # hardcore in the code, or you can also change the firm of the method to for
- # example anagrams("horse", ./wl.txt).
- #
- class AnagramCalculator
- attr_reader :database_file
- def initialize(database_file:)
- @database_file = database_file
- end
- def call(input)
- database
- .select { |w| w.length == input.length }
- .select { |w| anagram?(input, w) }
- end
- private
- def database
- @database ||= File.read(database_file).split("\n")
- end
- def anagram?(word1, word2)
- word2_bytes = word2.bytes
- word1.bytes.select do |b|
- word2_bytes.delete(b).nil?
- end.empty?
- end
- end
- database_file = '/Users/dpereira/Downloads/wl.txt'
- puts AnagramCalculator
- .new(database_file: database_file)
- .call('esroh')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement