开发者

How to remove objects that have duplicates in an array [duplicate]

This question already has answers here: 开发者_高级运维 Closed 11 years ago.

Possible Duplicate:

Remove from the array elements that are repeated. in Ruby

I would like to do this:

my_array = [1, 1, 2, 2, 3]
my_array_without_duplicates = [3]

calling my_array.uniq will give me [1, 2, 3], which is not the result I want. Is there an efficient way of doing this? What I am doing right now is too ugly to post.


my_array.group_by{|e| e}.select{|k,v| v.count == 1}.keys

or

my_array.select{|e| my_array.count(e) == 1}

BTW, you probably meant my_array = [1, 1, 2, 2, 3] (with brackets, not braces).


I'd get first the histogram of the input (see Enumerable#frequency or write your own) and then do the select:

require 'facets'
xs = [1, 1, 2, 2, 3]
fs = xs.frequency # {1=>2, 2=>2, 3=>1}
ys = xs.select { |x| fs[x] == 1 } # [3]

Ruby 1.9 keeps order in hashes, so this would probably suffice:

xs.frequency.select { |x, count| count == 1 }.keys # [3]

Which can be written in one step if you use the Enumerable#map_select abstraction (and assuming you have no nils in the input), like this:

xs.frequency.map_select { |x, count| x if count == 1 } # [3]


I believe this has well balance of simplicity and efficiency. Just that it looks long because the variable names are long.

my_array_without_duplicate = my_array.dup
my_array_without_duplicate.each_with_index {|e, i|
    my_array_without_duplicate.delete(e) if my_array_without_dupliate.index(e, i+1)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜