繁体   English   中英

数组中的Ruby差异包括重复项

[英]Ruby difference in array including duplicates

[1,2,3,3] - [1,2,3]产生空数组[] 是否可以保留重复项以便返回[3]

我很高兴你问。 我希望在未来的 Ruby 版本中看到这样的方法添加到类Array中,因为我发现它有很多用途:

class Array
  def difference(other)
    h = other.each_with_object(Hash.new(0)) { |e,h| h[e] += 1 }
    reject { |e| h[e] > 0 && h[e] -= 1 }
  end
end

此处提供了该方法的说明和一些应用程序的链接。

举例来说:

a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]

a - b          #=> [1]
a.difference b #=> [1,2,3,2]

Ruby v2.7 为我们提供了Enumerable#tally方法,允许我们将方法的第一行替换为

h = other.tally

据我所知,你不能用内置操作来做到这一点。 ruby 文档中也看不到任何内容。 最简单的方法是像这样扩展数组类:

class Array
    def difference(array2)
        final_array = []
        self.each do |item|
            if array2.include?(item)
                array2.delete_at(array2.find_index(item))
            else
                final_array << item
            end
        end
    end
end

据我所知,还有一种更有效的方法可以做到这一点,也

编辑:正如user2864740在问题评论中所建议的,使用Array#slice! 是一个更优雅的解决方案

def arr_sub(a,b)
    a = a.dup #if you want to preserve the original array
    b.each {|del| a.slice!(a.index(del)) if a.include?(del) }
    return a
end

信用:

我的原答案

def arr_sub(a,b)
    b = b.each_with_object(Hash.new(0)){ |v,h| h[v] += 1 }

    a = a.each_with_object([]) do |v, arr| 
        arr << v if b[v] < 1
        b[v] -= 1
    end
end

arr_sub([1,2,3,3],[1,2,3]) # a => [3]
arr_sub([1,2,3,3,4,4,4],[1,2,3,4,4]) # => [3, 4]
arr_sub([4,4,4,5,5,5,5],[4,4,5,5,5,5,6,6]) # => [4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM