[英]Array of random integers with fixed average in java
我需要創建一個隨機整數數組,它們的總和是1000000,這些數字的平均值是3。該數組中的數字可以重復,並且數組的長度可以是任何數字。
我能夠找到隨機整數的數組,它們的總和是1000000。
ArrayList<Integer> array = new ArrayList<Integer>();
int a = 1000000;
Random rn = new Random();
while (a >= 1)
{
int answer = rn.nextInt(a) + 1;
array.add(answer);
a -= answer;
}
但是,我不知道如何找到平均數為3的隨機數。
這在數學上是不可能的:
您正在尋找n個值,其總和為1000000,它們的平均值為3,即1000000 / n。 因為n只能取整數值,所以這是不可能的。
如果將它們限制為平均值和隨機數,則必須將它們限制為一個值范圍。 范圍為1到5(中位數為3)似乎是合理的。 同樣合理的是平滑的分布,它給出已知的總計和平均值。
這個簡單的代碼將完成所有操作:
List<Integer> numbers = new ArrayList<>(333334); // 1000000 / 3
// one instance of 5 must be omitted to make total exactly 1000000
numbers.addAll(Arrays.asList(1, 2, 3, 4));
for (int i = 0; i < 333330; i++)
numbers.add((i % 5) + 1); // add 1,2,3,4,5,1,2,3,4,5,etc
Collections.shuffle(numbers);
// Check sum is correct
numbers.stream().reduce((a,b) -> a + b).ifPresent(System.out::println);
輸出:
1000000
請注意,當總數為1000000
時,從數學1000000/3
,平均值不可能精確為 3
(因為1000000/3
的余數為1/3
),但是此代碼非常接近:
1000000/333334 => 2.999994
我將遍歷列表兩次,如果將這兩個位置的整數相加並除以2 == 3,則返回,否則,增加整數。
我認為您需要編寫一個簡單的平均函數,例如:
public double average(ArrayList<Integer> array){
long sum = 0;
int count = 0;
for (Integer item : array){
sum += item;
count++;
}
return sum/count;
}
然后在您的代碼中使用它,例如:
ArrayList<Integer> array = new ArrayList<Integer>();
int a = 1000000;
Random rn = new Random();
boolean isDone = true;
while (a >= 1)
{
int answer = rn.nextInt(a) + 1;
array.add(answer);
a -= answer;
if (average(array) % 3 != 0){
isDone = false;
break;
}
}
這個想法是,每次我們向數組添加一個新數字時,我們都會檢查平均值是否可以除以3,否則,我們會退出while循環。
為了讓我們知道算法是否運行良好,我們需要在最后檢查isDone
變量。
更有效的方法是:
ArrayList<Integer> array = new ArrayList<Integer>();
int a = 1000000;
Random rn = new Random();
boolean isDone = true;
long sum = 0;
while (a >= 1)
{
int answer = rn.nextInt(a) + 1;
array.add(answer);
a -= answer;
sum += answer;
if ((sum/array.size()) % 3 != 0){
isDone = false;
break;
}
}
正如GökerGümüş所說,在數學上不可能使平均值精確為3,而總和為100萬。
平均值=總和/元素數。 這意味着元素數=總和/平均值。
在這種情況下,它將需要1000000/3 = 333333.(3)個元素。 由於您不能擁有值為3的元素的三分之一,這意味着您的平均值或總和將需要稍微偏離目標才能與之匹配。 不太明顯需要的差異肯定是平均值,因為它只需要一個單位的百萬分之一,即3.000001,您就能使333333個元素總計為1000000
這個問題有很多答案,但是可以說我們希望隨機數最大為10(可以更改)。 我想這會給人滿意的答案。
import java.util.Random;
導入java.util.ArrayList;
公共類RandomSumAverage {
public static void main(String[] args) {
Random random = new Random();
ArrayList<Integer> arr = new ArrayList<Integer>();
double sum = 0;
double avg = 0;
int k = 1;
while (sum < 1000000) {
avg = sum / k;
if (avg < 3) {
int element = random.nextInt(10)+1;
sum += element;
arr.add(element);
k++;
} else {
int element = random.nextInt(3)+1;
sum += element;
arr.add(element);
k++;
}
}
System.out.println(arr);
System.out.println(sum);
System.out.println(avg);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.