Ruby中的规范数组差异示例如下:
[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]
获得以下行为的最好方法是什么?
[ 1, 1, 2, 2, 3, 3, 4, 5 ].subtract_once([ 1, 2, 4 ]) #=> [ 1, 2, 3, 3, 5 ]
也就是说,只有第二个数组中每个匹配项的第一个实例从第一个数组中移除。
发布于 2010-10-04 13:28:36
class Array
def subtract_once(b)
h = b.inject({}) {|memo, v|
memo[v] ||= 0; memo[v] += 1; memo
}
reject { |e| h.include?(e) && (h[e] -= 1) >= 0 }
end
end
我相信这就是我想要的。非常感谢@glebm
发布于 2010-10-04 12:16:15
到目前为止,我能想到的就是这些:
[1, 2, 4].each { |x| ary.delete_at ary.index(x) }
发布于 2014-02-13 03:00:05
与@Jeremy Ruten的答案类似,但考虑到一些元素可能不存在的事实:
# remove each element of y from x exactly once
def array_difference(x, y)
ret = x.dup
y.each do |element|
if index = ret.index(element)
ret.delete_at(index)
end
end
ret
end
此答案也不会在操作时修改原始数组,因此:
x = [1,2,3]
y = [3,4,5]
z = array_difference(x, y) # => [1,2]
x == [1,2,3] # => [1,2,3]
https://stackoverflow.com/questions/3852755
复制相似问题