2D数组-如何删除重复值,但保持子数组分离

时间:2019-06-03 14:44:25

标签: ruby multidimensional-array filter duplicates

我想从2d数组中删除重复项,但我需要单独保留子数组。

数组:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
d = [4,5,6,7]

newarray = [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]

想要得到以下结果:

newarraynoduplicates = [[1,2,3,4], [5], [6], [7]]

我尝试了以下操作

[a|b|c|d] => [[1, 2, 3, 4, 5, 6, 7]]
[a|b|c|d] =>  [1, 2, 3, 4, 5, 6, 7]

也尝试过

newarray.uniq! => nil!

4 个答案:

答案 0 :(得分:8)

最通用的方法是:

[[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]].
  each_with_object([]) { |a, acc| acc << a - acc.flatten } 
#⇒ [[1, 2, 3, 4], [5], [6], [7]]

[[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]].
  reduce([]) { |acc, a| acc << a - acc.flatten }
#⇒ [[1, 2, 3, 4], [5], [6], [7]]

答案 1 :(得分:3)

我认为您正在寻找:

new_array = [a, b - a, c - b - a, d - c - b - a ]
#=> [[1,2,3,4], [5], [6], [7]]

答案 2 :(得分:1)

require 'set'

def doit(arr)
  s = Set.new
  arr.map { |a| a.select { |e| s.add?(e) } }
end

doit [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]
  #=> [[1, 2, 3, 4], [5], [6], [7]] 
doit [[1,2,2,3,4], [2,3,4,5,3], [3,4,5,6], [4,5,6,7]]
  #=> [[1, 2, 3, 4], [5], [6], [7]]

请参见Set#add?。因为设置查找非常快,所以这应该非常有效。

答案 3 :(得分:0)

我没有做很多测试,但是似乎可以工作:

newarray = [[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]

newarray.map.with_index { |e, i| (e - newarray.reverse[newarray.size - i..].flatten).uniq }
#=> [[1, 2, 3, 4], [5], [6], [7]]

或者,为避免在每个循环中反转:

newarray.reverse.then{ |ary| newarray.map.with_index { |e, i| (e - ary[newarray.size - i..].flatten).uniq } }