Ruby 在字符串数组中对字谜进行分组的方法 [英] Ruby way to group anagrams in string array
问题描述
我实现了一个函数来对字谜进行分组.简而言之:
输入:['cars'、'for'、'potatoes'、'racs'、'four'、'scar'、'creams'、scream']
输出:[["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]]>
我想知道是否有更好的方法来做到这一点.我真的觉得我用了太多重复语句:until
、select
、delete_if
.有没有办法结合 select
和 delete_if
语句?那意思是,可以自动删除所选项目吗?
代码:
def group_anagrams(words)数组 = []直到words.empty?word = words.firstarray.push( words.select { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )words.delete_if { |匹配|word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join) }结尾大批结尾
提前致谢,
像这样:
a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']a.group_by { |元素|element.downcase.chars.sort }.values
输出为:
[["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
如果你愿意,你当然可以把这个单行变成一种方法.
I implemented a function to group anagrams. In a nutshell:
input: ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', scream']
output: [["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]]
I would like to know if there is a better way to do this.
I really think I used too much repetition statements: until
, select
,
delete_if
.
Is there any way to combine the select
and delete_if
statement? That
means, can selected items be automatically deleted?
Code:
def group_anagrams(words)
array = []
until words.empty?
word = words.first
array.push( words.select { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )
words.delete_if { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) }
end
array
end
Thanks in advance,
Like that:
a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']
a.group_by { |element| element.downcase.chars.sort }.values
Output is:
[["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
If you want to you can turn this one-liner to a method of course.
这篇关于Ruby 在字符串数组中对字谜进行分组的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!