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 }

现在,我们都很好.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...