Fellow Stranger Fellow Stranger - 1 month ago 8
Ruby Question

Remove multiple ranges of values from array

a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
a2 = [2..4, 8..11, 16..17]


Removing one range of values from an array can be done like this:

[1, 2, 3, 4, 5, 6, 7, 8, 9].slice!(2..5)


Iterating over the ranges and apply the same as above (
a2.each { |range| a1.slice!(range) }
) isn't perfect though. The ranges overlap sometimes and thus destroy the referencing index for the other ranges.

So, any suggestions on how to remove the ranges in
a2
from
a1
in the most efficient way?
a1
is normally [*0..10080] long.
a2
has about 30 ranges, each containing hundreds of values.

Answer
a1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
a2 = [2..4, 8..11, 16..17]

a1 - a2.flat_map(&:to_a)
Comments