Search code examples
language-agnosticcode-golf

Finding closest match in collection of numbers


So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.


Solution

  • 11 bytes in J:

    C=:0{]/:|@-
    

    Examples:

    >> a =: 1 3 8 10 13
    >> 4 C a
    3
    >> 11 C a
    10
    >> 12 C a
    13
    

    my breakdown for the layman:

    0{         First element of
    ]          the right argument
    /:         sorted by
    |          absolute value 
    @          of
    -          subtraction