Find minimum difference between numbers in array

  • STDIN: Array of integers



    STDOUT: Smallest difference (the difference between the closest two numbers in the array).



    Rules: Given an array of positive integers find the difference between the closest two numbers in the array. Performance should be taken into consideration.



    Example:



    STDIN: [55, 99, 6, 29, 1, 523, 3]



    STDOUT: 2 (e.g. 3-1)



    Scoring: Although somewhat informal, the shortest, most efficient (performance wise) will win. Creativity will also be taken into consideration.


    While [tag:fastest-algorithm] questions are allowed, the scoring for this question appears that combined with a subjective metric of "creativity", making this challenge lack an objective winning criterion.

    To close voters: this should not be closed as "needs details or clarity", but instead "does not have an objective winning criteria", as although the spec is bare-bones and could do with some explanation (and updating to modern rules), the main issue is with the missing winning criteria

    Indeed. Sorry, I misclicked and used the wrong close reason.

  • Tommy

    Tommy Correct answer

    10 years ago

    The R language



    23 characters, O(n log n)



    min(diff(sort(scan())))


    Example:



    > min(diff(sort(scan())))
    1: 55 99 6
    4: 29 1 523 3
    8:
    Read 7 items
    [1] 2


    ...The [1] 2 shows the result 2. (the [1] is to keep track of where in the result vector your are since in R all values are vectors - in this case of length 1)


    well done, although not very creative! :p useful functions though.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM