2

http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf

Trying to part 3 of this assignment. The following code does not seem to work, namely for the parameter ['HeLLo', 'hello'], returning [["hello"], ["HeLLo"]] instead of [["HeLLo", "hello"]]

def combine_anagrams(words)
    #iterate through words, make hashmap with the sorted version
    hash = {}
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] = []
    end

    #iterate through words, access hashmap and append curr to array
    words.each do |x|
        hash[x.chars.sort.join.downcase.gsub /\W/, ""] << x
    end

    hash.values #return array of values
end

Any help would be appreciated. (I'm new to Ruby)

Rishi
  • 945
  • 2
  • 15
  • 23

1 Answers1

1

You could easily do it like this:

def combine_anagrams(words)
  anagrams={}
      words.each do |word|
        anagrams[word.downcase.split('').sort.join] ||=[]
        anagrams[word.downcase.split('').sort.join] << word 
      end
      anagrams.values
end
Zippie
  • 6,018
  • 6
  • 31
  • 46
  • 1
    check the duplicated question to see a better way: http://stackoverflow.com/questions/9646995/ruby-way-to-do-this – tokland Apr 06 '13 at 20:55
  • +1, was just looking for the group_by option to correct my self :) i am gonna leave this here, i don't wanna copy other peoples code although i did want to do something with `group_by`. Everyone looking for a better option check @toklands link. thnx @tokland – Zippie Apr 06 '13 at 20:57