您的位置:首页 > Web前端

Is it possible to get the difference from two dynamic arrays regardless of their order?

2014-06-14 16:27 525 查看
        If I have two arrays and I try to find their difference..
[1, 2, 3, 2, 6, 7] - [2, 1]
I get :
[3, 6, 7]
But if I flip those arrays around
[2, 1] - [1, 2, 3, 2, 6, 7]
I get :
[]
My question is, being that my two arrays are dynamic, I need to know if there is a difference in between both arrays regardless of their order. What's the simplest expression to find that?
----------------------------------------------------------------------------------------------------------
require 'set'
([2, 1].to_set ^ [1, 2, 3, 2, 6, 7]).to_a
# => [3, 6, 7]
([1, 2, 3, 2, 6, 7].to_set ^ [2, 1]).to_a
# => [3, 6, 7]
According to the documentation

Set#^
returns a new set containing elements exclusive between the set and the given enumerable object.

----------------------------------------------------------------------------------------------------------------------------------------------------------------

You can define it:
class Array

def diff(o)

(o - self) + (self - o) # alternatively: (o + self) - (o & self)

end

end


[2, 1].diff [1, 2, 3, 2, 6, 7] # [3, 6, 7]

[1, 2, 3, 2, 6, 7].diff [2, 1] # [3, 6, 7]

[2, 3, 3, 1].diff [2, 4, 5] # [4, 5, 3, 3, 1]

[2, 4, 5].diff [2, 3, 3, 1] # [3, 3, 1, 4, 5]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐