加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby – Anagram代码

发布时间:2020-12-17 02:56:42 所属栏目:百科 来源:网络整理
导读:我们这里有一系列文字: words = ['demo','none','tied','evil','dome','mode','live','fowl','veil','wolf','diet','vile','edit','tide','flow','neon'] 我的老师写了一个程序,打印出一组字样的字谜.字谜是单词中具有相同字母但按不同顺序排列的单词.输出
我们这里有一系列文字:

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 }

现在,我们都很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读