在随机集中找到最接近的数字 [英] Finding the closest number in a random set

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

问题描述

假设我有一组 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

以及如何将其转换为代码?(javascript 什么的)

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

推荐答案

如果 set 是有序的,则进行二分搜索以找到最接近的值(或 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天全站免登陆