gpt4 book ai didi

Java:在 ArrayList 中生成值的分布

转载 作者:行者123 更新时间:2023-11-30 09:50:20 25 4
gpt4 key购买 nike

我有一个排序的 ArrayList 值。我想获得值的分布。例如:

  • 假设我有 500 个值,范围从 1 到 100。
  • 我想将它们分成几组,比如 10 组:值 1-10、11-20、21-30 等...
  • 我想要属于每个类别的 500 个值中每个值的计数。例如,500 人中有 5 人的值(value)在 1-10 之间,20 人在 11-20 之间,等等......
  • 但是,我不知道我的 ArrayList 中值的范围,它可能在 1-30 或 1-200 之间,但我想将它分成例如 10 个组。

有人知道怎么做吗?

最佳答案

使用 Guava让你在那个方向走得很远。下面是一些让您入门的代码:

// initialize the List with 500 random values between 1 and 200
// you'll probably supply your existing lists instead
final Random rand = new Random();
final List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 500; i++){
list.add(rand.nextInt(200)+1);
}

// create a multiset
final Multiset<Integer> multiset = TreeMultiset.create(list);

// create 10 partitions of entries
// (each element value may appear multiple times in the multiset
// but only once per partition)
final Iterable<List<Integer>> partitions =
Iterables.partition(
multiset.elementSet(),
// other than aioobe, I create the partition size from
// the number of unique entries, accounting for gaps in the list
multiset.elementSet().size() / 9
);

int partitionIndex = 0;
for(final List<Integer> partition : partitions){

// count the items in this partition
int count = 0;
for(final Integer item : partition){
count += multiset.count(item);
}
System.out.println("Partition " + ++partitionIndex + " contains "
+ count + " items (" + partition.size() + " unique) from "
+ partition.get(0) + " to "
+ partition.get(partition.size() - 1));
}

输出:

Partition 1 contains 53 items (20 unique) from 1 to 21
Partition 2 contains 49 items (20 unique) from 22 to 42
Partition 3 contains 58 items (20 unique) from 43 to 63
Partition 4 contains 60 items (20 unique) from 64 to 84
Partition 5 contains 58 items (20 unique) from 85 to 104
Partition 6 contains 44 items (20 unique) from 105 to 126
Partition 7 contains 46 items (20 unique) from 127 to 146
Partition 8 contains 54 items (20 unique) from 147 to 170
Partition 9 contains 50 items (20 unique) from 171 to 191
Partition 10 contains 28 items (8 unique) from 192 to 200

引用:

关于Java:在 ArrayList 中生成值的分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com