从嵌套数组中删除重复项 [英] Remove duplicates from nested array
问题描述
$ b $例如:
nums = [[10,6,14],[6],[10,6,9],[10,13,6],[10,13,6,9, 16],[10,13]]
nums [0]包含[10,6,14],所以随后提及的10,6,14应该从链中的其他数组,意思是nums [2]应该有10,6个删除,只有9个应该保留。
我无法使用嵌套循环,任何Ruby向导都可以帮助吗?
应该这样做:
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 - 看到
看到+ = new
new
end
#=>输出是[[10,6,14],[],[9],[13],[16],[]]
如果要删除输出中的空列表,只需
output.reject!( &:empty?)
I have an Array of Arrays that contains numbers in a particular order. I want to remove the duplicates out of the nested arrays, but there is a hierarchy: If a number occurs in a lower-index of the array, remove all duplicates down 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 the other arrays in the chain, meaning nums[2] should have 10,6 removed and only 9 should remain.
I'm having trouble doing this with nested loops, can any Ruby wizards help please?
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], []]
If you want to remove the empty lists in the output, simply
output.reject!(&:empty?)
这篇关于从嵌套数组中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!