others - ruby - 2维数组如何移除重复的值,但是保持子数组分离

我想从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!



时间:

最通用的方法是:


[[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]]



我想你要找的是


new_array = [a, b - a, c - b - a, d - c - b - a ]


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




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,这应该非常有效,因为设置查找非常快,

我没有做很多测试,但是似乎是这样的:


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 } }



...