Finding the closest number in a random set

前端 未结 6 1998
长情又很酷
长情又很酷 2021-01-01 05:23

Say I got a set of 10 random numbers between 0 and 100.

An operator gives me also a random number between 0 and 100. Then I got to find the number in the set that is

6条回答
  •  悲哀的现实
    2021-01-01 05:34

    Someone tagged this question Mathematica, so here's a Mathematica answer:

    set = {1,10,34,39,69,89,94,96,98,100};
    
    opno = 45;
    
    set[[Flatten[
      Position[set - opno, i_ /; Abs[i] == Min[Abs[set - opno]]]]]]
    

    It works when there are multiple elements of set equally distant from the operator number.

提交回复
热议问题