我需要生成9个随机数,其总数为15 ......并且随机数必须为1或2或3 ......
前:
[1,2,1,1,3,1,2,1,3] 1+2+1+1+3+1+2+1+3 = 15 (9 Numbers Between 1-3 and sum is 15)
通过程序我需要这些不同的列表...
我搜索了很多节目,但没有达到我的要求......
谢谢
答案 0 :(得分:1)
生成9个数字并将它们存储在一个数组中。总结一下。
浏览数组以获得所需的总和。
对于每个数字,如果当前总和大于期望的减少数量(如果它> 1),如果它增加数量(如果它<3)以实现期望的总数则少。
答案 1 :(得分:0)
function generateRandomNumber() {
Generate a number between 1 and 3
while that number plus the total of the other numbers is less than 15, go to next random number,
while that number plus total of other numbers is more than 15, pick a new number
if that number plus other numbers equals 15 , then
if there are 9 numbers, return the list, otherwise
start at the beginning of the list and generate new numbers until there are 8 numbers adding up to a value within 3 of 15, then add the remainder
}
答案 2 :(得分:0)
我通过
解决了上述问题 i . Add 9 1's to a list
和
ii . pick a number from list randomly
和iii . If the number is less than 3 and sum of all numbers in list is less than 15 then increase the number by 1
以及iv . Repeat this check until the total of the list is 15
...
List<Integer> randomNumbersList = new ArrayList();
//Add 9 1's to the list
for(int i=0;i<count;i++)
{
randomNumber = generateRandomNumberInRange(0, 8);
number = randomNumbersList.get(randomNumber);
if(number < 3 && getTotal(randomNumbersList) < 15)
{
number += 1;
randomNumbersList.set(randomNumber, number);
}
}
public int getTotal(List<Integer> list)
{
//Code to get total of the numbers in the list
}