得到的阵列具有独特元素的数组 [英] get an array of arrays with unique elements
本文介绍了得到的阵列具有独特元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数组:
[1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7]
我想知道是否有得到这个方法:
I want to know if there's a method to get this:
[[1, 2, 3, 4, 5, 6, 7], [3, 4, 6], [6]]
我知道有一个 Array.uniq
但这删除重复的元素,我想留住他们。
I know there is Array.uniq
but this removes the duplicate elements, and I would like to keep them.
推荐答案
不知道有关性能,但这个作品:
Not sure about performance, but this works:
code:
$ cat foo.rb
require 'pp'
array = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7]
result = []
values = array.group_by{|e| e}.values
while !values.empty?
result << values.map{|e| e.slice!(0,1)}.flatten
values = values.reject!{|e| e.empty?}
end
pp result
输出:
$ ruby foo.rb
[[1, 2, 3, 4, 5, 6, 7], [3, 4, 6], [6]]
这篇关于得到的阵列具有独特元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文