Month: April 2014

Anagram?

Given: Two arrays of words in lowercase
Result: Print “True” if the pair of words in the same index is anagram, else print “False”

Example:
words_A = [“shots”, “name”, “app”, “lure”, “melon”]
words_B = [“hosts”, “mean”, “paa”, “rule”, “lemons”]
Result = true, true, false, true, false

When I first started coding the method, it was a huge mess…

def anagrams(first_words, second_words)
  
  first_words.each_with_index do |f, i|
    puts "#{f} vs #{second_words[i]}"
    f_size = f.size
    s_size = second_words[i].size
  
    #if the two words have different length, then for sure they're not anagrams
    if f_size != s_size
      puts false
      next
    end
    
    # compare the number of letters vs the number of letters in the other
    first_letters = f.scan(/[a-z]/).uniq
    second_letters = second_words[i].scan(/[a-z]/).uniq

    #key: letter, value: the amount of times the letter shows up in the word
    first_count = {}
    second_count = {}
    
    first_letters.each do |l|
      v = f.count l
      first_count[l] = v
    end
    
    second_letters.each do |l|
      v = second_words[i].count l
      second_count[l] = v
    end
    
    first_letters.each do |l|
      if first_count[l] != second_count[l]
        puts false
        break 
      end
    end
    
    puts true
  end
end

The silver lining of this is I learn the differences between break and next:
next: Jumps to next iteration of the most internal loop
break: Terminates the most internal loop.

Now after a few hours, I revisted the task, and reconquered it.

def anagrams_ii(first_words, second_words)
  first_word.each_with_index do |word, i|
    puts "#{word} vs #{second_word[i]}"
    first_sorted = word.split('').sort
    second_sorted = second_word[i].split('').sort
    unless first_sorted == second_sorted
      puts false
      next
    end
    puts true
  end
end

Sorting and then comparing, much cleaner.

Both prints out the following results:
shots vs hosts
true
name vs mean
true
app vs paa
false
lure vs rule
true
melon vs lemons
false

Advertisements