Check if two arrays have the same contents (in any order)

前端 未结 9 1691
我在风中等你
我在风中等你 2020-12-24 04:13

I\'m using Ruby 1.8.6 with Rails 1.2.3, and need to determine whether two arrays have the same elements, regardless of whether or not they\'re in the same order. One of the

相关标签:
9条回答
  • 2020-12-24 05:00

    for two arrays A and B: A and B have same contents if: (A-B).blank? and (B-A).blank?

    or you can just check for: ((A-B) + (B-A)).blank?

    Also as suggested by @cort3z this solution als0 works for polymorphic arrays i.e

     A = [1 , "string", [1,2,3]]
     B = [[1,2,3] , "string", 1]
     (A-B).blank? and (B-A).blank? => true
     # while A.uniq.sort == B.uniq.sort will throw error `ArgumentError: comparison of Fixnum with String failed` 
    

    ::::::::::: EDIT :::::::::::::

    As suggested in the comments, above solution fails for duplicates.Although as per the question that is not even required since the asker is not interested in duplicates(he is converting his arrays to set before checking and that masks duplicates and even if you look at the accepeted answer he is using a .uniq operator before checking and that too masks duplicates.). But still if duplicates interests you ,Just adding a check of count will fix the same(as per the question only one array can contain duplicates). So the final solution will be: A.size == B.size and ((A-B) + (B-A)).blank?

    0 讨论(0)
  • 2020-12-24 05:01

    Ruby 2.6+

    Ruby's introduced difference in 2.6.

    This gives a very fast, very readable solution here, as follows:

    a = [1, 2, 3, 4, 5, 6]
    b = [1, 2, 3, 4, 5, 6]
    
    a.difference(b).any?
    # => false
    a.difference(b.reverse).any?
    # => false
    
    a = [1, 2, 3, 4, 5, 6]
    b = [1, 2, 3]
    a.difference(b).any?
    # => true
    

    Running the benchmarks:

    a = Array.new(1000) { rand(100) }
    b = Array.new(1000) { rand(100) }
    
    Benchmark.ips do |x|
      x.report('sort')   { a.sort == b.sort }  
      x.report('sort!')  { a.sort! == b.sort! }  
      x.report('to_set') { a.to_set == b.to_set }  
      x.report('minus')  { ((a - b) + (b - a)).empty? }  
      x.report('difference') { a.difference(b).any? }
    end
    
          sort     13.908k (± 2.6%) i/s -     69.513k in   5.001443s
         sort!     14.656k (± 3.0%) i/s -     73.736k in   5.035744s
        to_set     5.125k  (± 2.9%) i/s -     26.023k in   5.082083s
         minus     16.398k (± 2.2%) i/s -     83.181k in   5.074938s
    difference     27.839k (± 5.2%) i/s -    141.048k in   5.080706s
    

    Hope that helps someone!

    0 讨论(0)
  • 2020-12-24 05:03

    When the elements of a and b are Comparable,

    a.sort == b.sort
    

    Correction of @mori's answer based on @steenslag's comment

    0 讨论(0)
提交回复
热议问题