Search code examples
arraysrubyalgorithmcomplexity-theory

Find missing random amount of numbers in array with duplicates


I should have a complete array of numeric identifiers like this one:

a = [3, 4, 5, 6, 7, 8, 9, 10]

But instead, I have a a messed up array in random order, with duplicates and missing numbers like this one:

b = [4, 9, 7, 7, 3, 3]

Is there a more optimal way to find out which numbers are missing apart from substract the array without duplicates?

a - b.uniq

Solution

  • Ruby 2.6 introduced Array#difference which seems perfect here:

    a = [3, 4, 5, 6, 7, 8, 9, 10]
    b = [4, 9, 7, 7, 3, 3]
    
    a.difference(b)
    # => [5, 6, 8, 10]
    

    Seems handy for this, with the added benefit of being very readable.