微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ruby – Anagram代码

我们这里有一系列文字

words =  ['demo','none','tied','evil','dome','mode','live','fowl','veil','wolf','diet','vile','edit','tide','flow','neon']

我的老师写了一个程序,打印出一组字样的字谜.字谜是单词中具有相同字母但按不同顺序排列的单词.输出应该如下所示:

["demo","dome","mode"]
["neon","none"]
(etc)

这是我的老师向我们展示的解决方案:

result = {}

words.each do |word|
  key = word.split('').sort.join
  if result.has_key?(key)
    result[key].push(word)
  else
    result[key] = [word]
  end
end

result.each do |k,v|
  puts "------"
  p v
end

我有点困惑这个程序是如何工作的,例如当这个部分被设置时结果[key] .push(word)和它所说的部分[key] = [word]我知道这可能是一个关闭问题但是任何人都可以在一个外行人的术语中逐行解释解决方案,或者像我这样的假人会理解.

PS.对不起新手在这里.

解决方法

请参阅内联评论说明:

words.each do |word| #=>  iterate each word in words array. "word" variable will have value at a particular iteration
  key = word
  .split('') #=> splits word,if word is 'demo' on iteration then it will be: `['d','e','m','o']`
  .sort #=> sorts the splitted array,i.e. the array above will be: `['e','d','o']`
  .join #=> joins the array sorted in above operation,it will be: 'edmo'. Since this is last operation,it will be returned and saved in `key` variable
  if result.has_key?(key) #=> Check whether result(Hash) already has key: `edmo`,returns true if present
    result[key].push(word) #=> result['edmo'] will give an array value,which can push word in that array
  else #=> false when key is not present in result Hash.
    result[key] = [word] #=> then add key with an array such as: `result['edmo] = ['demo']`
  end
end

但是,你可以用惯用的方式做同样的事情:

result = Hash.new{|h,k| h[k] =[] } #=> if key does not exist then the default value will be an array.

那么,上面的代码将成为:

words.each do |word|
  key = word.split('').sort.join
  result[key] << word # no need to validate whether we have key in Hash or not
end

但是,这种将值保持为数组的方法存在问题.如果我们的单词数组中有重复的单词,您的密钥中将有重复的数据.只需将数组更改为set即可解决问题:

require 'set'
result = Hash.new{|h,k| h[k] = Set.new }

现在,我们都很好.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐