寻找最接近的号码中随机设置 [英] Finding the closest number in a random set

查看:140
本文介绍了寻找最接近的号码中随机设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我得到了一组10个随机数字0和100之间。

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

这是运营商给我也介于0和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 the closest from the number the operator gave me.

设置= {1,10,34,39,69,89,94,96,98,100}

set = {1,10,34,39,69,89,94,96,98,100}

运营商数量= 45

收益率= 39

和如何转化为code呢? (Jav​​aScript或东西)

And how do translate this into code? (javascript or something)

推荐答案

如果集是有序的,做一个二进制搜索找到该值,(或者2的值)是最接近。然后区分其中2个是最接近的...减法?

if set is ordered, do a binary search to find the value, (or the 2 values) that are closest. Then distinguish which of 2 is closest by ... subtracting?

如果集不排序,只是遍历集合,(排序会本身需要一个以上的传递),并为每个成员,检查,看看是否不同的是比你所看到的迄今为止最小的差异较小,如果是,它记录作为新的最小差,并且该号码作为新的候选回答。 。

If set is not ordered, just iterate through the set, (Sorting it would itself take more than one pass), and for each member, check to see if the difference is smaller than the smallest difference you have seen so far, and if it is, record it as the new smallest difference, and that number as the new candidate answer. .

  public int FindClosest(int targetVal, int[] set)
  {
      int dif = 100, cand = 0;
      foreach(int x in set)
          if (Math.Abs(x-targetVal) < dif)
          {
              dif = Math.Abs(x-targetVal);
              cand = x;
          }
      return cand;
  }

这篇关于寻找最接近的号码中随机设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆