newguy newguy - 6 months ago 19
Ruby Question

Find elements missing from an array of ordered numbers

I have an array

array
of numbers ordered. I define a number
e
to be missing from
array
if:


  • For some element
    v
    of
    array
    ,
    e
    is either
    v
    ,
    v + 1
    , or
    v - 1
    ,

  • e
    is not an element of
    array
    , and

  • e
    is not smaller than
    0
    .



For example, the elements missing from:

array = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]


are:

[3, 7, 8, 11, 14, 16, 18]


How can I find the elements missing from a given array
array
?

Answer

It looks like you want something like:

array = [0, 1, 2, 4, 5, 6, 9, 10, 12, 13, 17]
possible_missing = array.flat_map {|e| [e-1, e+1]}.uniq
#=> [1, 0, 2, 3, 5, 4, 6, 7, 8, 10, 9, 11, 13, 12, 14, 16, 18]
diff = (possible_missing - array).select {|e| e >= 0}
#=> [3, 7, 8, 11, 14, 16, 18]
Comments