前段时间在工作中遇到了一个这样的问题,硬件设备会不停给后台一个返回byte数组数据,后台经过封装将byte数组转成double类型的数组。之后需要通过这个数组的数据100到500之间分成20份后,double数组里的数据在每个区间出现的次数。
举个例子:
int[] arr = {3,5,7,8,10,15,17,20,28,35,40,45,48};
按以上要求,把数组从1到50分成5份;求出arr里面的数据在:1-10、11-20、21-30、31-40、41-50的数据。
对应的答案应该为[5,3,1,2,2].
大概就是上面的例子,通过改进抽成了以下方法,如果遇到类似还可过来改改😀
/**
* @author zxw
* @version 1.0
* @description 测试
* @data: 2020/2/18 17:15
*/
public class Base {
public static void main(String[] args) {
List<Double> list = Arrays.asList(10.5, 10.7, 11d, 12d, 15d, 24d, 27.5, 29d, 36d, 37.8, 40.5, 42d, 46d, 48.7, 50d);
String numCount = getNumCount(list, 10d, 60d, 5);
System.out.println(numCount);
}
/**
* 求出集合数据在规定范围区间内出现的次数
* @param list 存有数据的集合
* @param start 区间的起始值
* @param end 区间的结尾
* @param count 区间分为多少份
* @return 数组
*/
private static String getNumCount(List<Double> list, Double start, Double end, int count) {
int[] arr = new int[count];
for (Double everyNum : list) {
//求出该值相对数组的角标,需要向下取整
int floor = (int) Math.floor((everyNum - start) / (end - start) * count);
//进行验证,防止角标越界
floor = Math.max(floor, 0);
floor = Math.min(floor, count - 1);
//对应位置的数据增加
arr[floor]++;
}
return Arrays.toString(arr);
}
}