【发布时间】:2023-03-09 15:26:01
【问题描述】:
http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf
尝试完成此作业的第 3 部分。下面的代码好像不行,即对于参数['HeLLo', 'hello'],返回[["hello"], ["HeLLo"]]而不是[["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
任何帮助将不胜感激。 (我是 Ruby 新手)
【问题讨论】:
-
给我们输入字符串和预期的输出。
-
前几天有人问过这个问题,搜索一下。另外,如果你想分组,也许
group_by方法是你应该看的。 -
试试这个
hash.values.flatten(1).reverse.each_cons(2) {|x| p [x]}
标签: ruby arrays string hash anagram