我们在这里有一系列的单词:
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
我对此程序的工作方式感到困惑,例如设置了
result[key].push(word)
的部分以及说result[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', 'm', '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
但是,这种将值保持为数组的方法存在一个问题。如果您的单词数组中有重复的单词,则 key 中将包含重复的数据。只需更改数组即可解决问题:
require 'set'
result = Hash.new{|h, k| h[k] = Set.new }
现在,我们都很好。
关于Ruby-字谜代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39869703/