数组按照要求分段,并求出每段的所占比例

前段时间项目中有一个这样的需要,0到360.这些角度要以0-4、2-6、4-8…350-354、352-356、354-358这样的规律之下分段,并且求出哪一段出现的比重最多,并求出最多那块的平均值。也许写法比较low,欢迎大家来指正。

/**
     * 0~360以0到4,2到6,6到10一直到356到360,358到362这样分成120个区间
     * 一个装有若干个数据的集合,算出该集合中数据在各个区间分布的次数情况
     * 求出最多区间的平均值
     */
    private static void countTest() {
        List<Double> angleList = Arrays.asList(10.1, 10.2, 10.2, 12.4, 13.4, 13.4, 15.6, 20.5, 20.6);
        //区间集合
        List<int[]> sectionList = new LinkedList<>();
        for (int i = 2; i < 362; i += 2) {
            int[] temp = {i - 2, i + 2};
            sectionList.add(temp);
        }
        //存放哪个区间(key)和对应区间(value)的数据
        Map<Integer, List<Double>> countMap = new HashMap<>(sectionList.size());
        //初始化数据
        for (int i = 0; i < sectionList.size(); i++) {
            countMap.put(i, new LinkedList<>());
        }
        //存放每个区间次数的数组
        int[] sectionCountArr = new int[sectionList.size()];
        //设置累加次数的数组(因为对应每一个区间的累加次数,所以一个技术器不行)
        int[] countArr = new int[sectionList.size()];
        //循环数据集合,进行对比符合哪个集合
        for (Double azimuth : angleList) {
            for (int j = 0; j < sectionList.size(); j++) {
                int start = sectionList.get(j)[0];
                int end = sectionList.get(j)[1];
                if (azimuth >= start && azimuth < end) {
                    //符合要求,进行区间次数的累加
                    sectionCountArr[j] = ++countArr[j];
                    //将对应区间和对应区间数据放入map中
                    List<Double> azimuthList = countMap.get(j);
                    azimuthList.add(azimuth);
                    countMap.put(j, azimuthList);
                }
            }
        }
        //区间哪个区间的值数据最多(如果有两个区间次数相同,则取其中一个)
        int maxValue = Arrays.stream(countArr).distinct().max().getAsInt();
        int maxIndex = ArrayUtil.indexOf(countArr, maxValue);
        //取出最大区间的数据,求和再求平均
        List<Double> maxCountList = countMap.get(maxIndex);
        double sum = maxCountList.stream().mapToDouble(every -> every).sum();
        System.out.println("最大区间的平均值为:" + sum / maxCountList.size());
    }

执行结果就不贴出了,如果以后有类似需求可以回来复习!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值