gpt4 book ai didi

java - Java 中的收缩数组保持数字分布

转载 作者:行者123 更新时间:2023-12-02 00:44:24 26 4
gpt4 key购买 nike

我有一个函数,它构建一个包含 N 个元素的数组,分布为 0 到 100 。例如:

int[] a = {100,80, 50,20, 0};

我想调整这个数组的大小以填充一个大小为 N = 10 的新数组,但保留前一个数组的数量分布。我认为通过一些概率分布,我可以实现这一点,但不知道该怎么做。

有人可以帮忙吗?

最佳答案

如果我对问题的理解正确,目标是将source数组中的数字重新分配到新数组中,将数字按10放入容器中。因此,如果数字为0它应该转到索引 0 处的新数组(因为它在 [0, 10] 范围内),如果数字是 20 -它应该转到索引 1 (因为它在 [11, 20] 范围内),依此类推。

如果假设正确,那么这是一种方法:

import java.util.Arrays;

public class ReDistribution {

public static void main(String[] args) {
int[] distribution = {100, 80, 50, 20, 0};
System.out.println(Arrays.toString(reDistribute(distribution)));
// prints: [0, 20, 0, 0, 50, 0, 0, 80, 0, 100]
}

/**
* Assuming source array contains only integers in range [0, 100], redistributes into array
* index 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
* range [0, 10], [11, 20], [21, 30], [31, 40], [41, 50], [51, 60], [61, 70], [71, 80], [81, 90], [91, 100]
*/
private static int[] reDistribute(int[] source) {
int[] target = new int[10];
for (int num : source) {
target[(num - 1) / 10] = num;
}
return target;
}
}

关于java - Java 中的收缩数组保持数字分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57910372/

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