栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

根据差异,将数组过滤为每十个倍数的一行?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

根据差异,将数组过滤为每十个倍数的一行?

我认为您应该以不同的方式来考虑。您想要做的是找到每行十的倍数的距离。

十进制的最接近倍数由表达式给出

double mult = 10d * Math.round(v / 10d)

与十的倍数的距离由表达式给出
double delta = Math.abs(v - mult)

对于的任何值mult,您要的行都是最小的行delta。
因此,您只需要迭代行一次。

  1. beam_value
    连续获取并找到
    mult
    delta
  2. 如果行的delta比以前发现的任何接近
    delta
    mult
    ,然后再登录该行为mult,否则忽略它。
  3. 重复直到没有更多行。
    还要注意,这种方法将防止记录一行超过十的整数倍,而其他方法很难防止这种情况。

通过示例(由于我没有您的SQL查询,所以我伪造了数据)。输入数据:

`0.5, 12.10, 13.00, 16.01, 21.52`

给出下面的输出,它是正确的(索引110比索引2更近,索引420比索引3更近):

   10x  row value     0 0 0.5000    10 1 12.1000    20 4 21.5200

与代码:

public static void findClosestRowsToMultiplesOfTen() {    // fake row values    double[] vals = new double[]{ 0.5, 12.10, 13.00, 16.01, 21.52 };    //  get the max value, and its multiple of ten to get the number of buckets    double max = Double.MIN_VALUE;    for (double v : vals) max = Math.max(max, v);    int bucketCount = 1 + (int)(max/10);    //  initialise the buckets array to store the closest values    double[][] buckets = new double[bucketCount][3];    for (int i = 0; i < bucketCount; i++){        // store the current smallest delta in the first element        buckets[i][0] = Double.MAX_VALUE;         // store the current "closest" index in the second element        buckets[i][1] = -1d;        // store the current "closest" value in the third element        buckets[i][2] = Double.MAX_VALUE;    }    //  iterate the rows    for (int i = 0; i < vals.length; i++)    {        //  get the value from the row        double v = vals[i];        //  get the closest multiple of ten to v        double mult = getMultipleOfTen(v);        //  get the absolute distance of v from the multiple of ten        double delta = Math.abs(mult - v);        //  get the bucket index based on the value of `mult`        int bIdx = (int)(mult / 10d);        //    test the last known "smallest delta" for this bucket        if (buckets[bIdx][0] > delta)        { //  this is closer than the last known "smallest delta" buckets[bIdx][0] = delta; buckets[bIdx][1] = i; buckets[bIdx][2] = v;        }    }    //   print out the result    System.out.format("    10x row value%n");    for (int i = 0; i < buckets.length; i++)    {        double[] bucket = buckets[i];        int multipleOfTen = i * 10;        double rowIndex = bucket[1];        double rowValue = bucket[2];        System.out.format("    %,2d %,4.0f %.4f%n",multipleOfTen, rowIndex, rowValue);    }}public static double getMultipleOfTen(double v){    return 10d * Math.round(v / 10d);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号