user7055375
user7055375

Reputation:

How do I find gaps in my array?

I'm using Ruby 2.4. If I have an ordered array of numbers, say

[1, 2, 4, 7, 8, 9]

How do I find the numerical elements that aren't present in my array, between the smallest and greatest values in the array? For instance in the above, the missing values are

[3, 5, 6]

If my array were

[2, 7]

the missing values I'd be looking for would be

[3, 4, 5, 6]

Upvotes: 3

Views: 1124

Answers (2)

Stefan
Stefan

Reputation: 114158

If you prefer complicated solutions:

[1, 2, 4, 7, 8, 9].chunk_while { |a, b| a + 1 == b }
                  .each_cons(2)
                  .flat_map { |x, y| (x.last + 1).upto(y.first - 1).to_a }
#=> [3, 5, 6]

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36101

Remove the existing numbers from the expected range of numbers:

(numbers.first..numbers.last).to_a - numbers

Upvotes: 10

Related Questions