Remove duplicates from nested array

I have an array of arrays that contains numbers in a specific order. I want to remove duplicates from nested arrays, but there is a hierarchy: if the number appears in the lower index of the array, delete all duplicates in the Array chain.

Example: nums = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13] ]

nums [0] contains [10,6,14], so any subsequent mention of 10,6,14 should be removed from other arrays in the chain, that is, nums [2] should have 10,6 deleted and only 9 should remain.

I'm having problems with nested loops, can any Ruby wizards help?

+3
source share
4 answers

This should do it:

input = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]
seen = []
output = input.map do |numbers|
  new = numbers.uniq - seen
  seen += new
  new
end
# => output is [[10, 6, 14], [], [9], [13], [16], []]

,

output.reject!(&:empty?)
+10
require 'set'

nums = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]
found = Set.new
new_nums = []

for subarray in nums do
    sub_new = []
    for i in subarray do
        if not found.member? i
            sub_new << i
        end
        found << i
    end
    new_nums << sub_new
end

puts(nums.inspect)
puts(new_nums.inspect)
+3

. :

require 'set'
nums = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]
nums2 = nums.inject([[], Set.new]) do |(output, seen), ary|  
  [output << ary.reject { |a| seen.include?(a) }, seen.union(ary)]
end[0]
p nums2
# [[10, 6, 14], [], [9], [13], [16], []]
+1

? [6] ?

nums = [[10, 6, 14], [6], [10, 6, 9], [10, 13, 6], [10, 13, 6, 9, 16], [10, 13]]

def remove_duplicate_numbers( array )
  seen = []
  array.map{ |sub_array|
    result = sub_array - seen
    seen += sub_array
    result
  }
end

p remove_duplicate_numbers( nums )
#=> [[10, 6, 14], [], [9], [13], [16], []]

If this is not what you need, send the actual result expected for your array.

0
source

Source: https://habr.com/ru/post/1782947/


All Articles