【问题标题】:Generate 9 Random Numbers among 1, 2,3 whose sum is 15在1、2、3中生成9个随机数,总和为15
【发布时间】:2014-12-04 04:56:50
【问题描述】:

我需要生成 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)

我需要这些不同的列表通过一个程序...

我搜索了很多程序,但没有满足我的要求...

谢谢

【问题讨论】:

  • 你有没有尝试写任何东西?不要指望我们会为你写完整的东西。
  • 你的代码在哪里?此外,如果数字是随机的,则无法保证它们的总和为 15。您是否会一直生成组合,直到找到总和为 15 的组合?
  • 我使用randomNumber = minNumber + (int)(Math.random()*(maxNumber - minNumber)); 生成一个介于 1 和 3 之间的随机数,其中 minNumber 为 1,maxnumber 为 3 ...但我无法获得如何获取数字的逻辑以便总和是 15

标签: java random numbers


【解决方案1】:

生成 9 个数字并将它们存储在一个数组中。总结他们。

遍历数组以获得所需的总和。

对于每个数字,如果当前总和大于所需的数字,则减少数字(如果大于 1),如果小于则增加数字(如果小于 3)以达到所需的总数。

【讨论】:

  • 有趣的是,您的方法存在偏差。结果更有可能有 3 个 1 和 6 个 2,而不是 6 个 1 和 3 个 3。从数学上可以证明这两个结果应该具有相同的概率。
  • @user515430 可以修改为从数组的随机索引开始多次通过数组递增/递减 1。
  • 我就是这么做的。它仍然显示出偏见。重复 1,554,000 次,我得到前者的 87707 次,后者的 78333 次。两者的预期值为 84000。这里还有一些运行,87514、78374 和 87854、78770。我使用 Mersenne Twister 作为我的 rng。以真正随机值播种。我没有解释为什么。
【解决方案2】:
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
}

【讨论】:

    【解决方案3】:

    我得到了解决上述问题的方法

    i . Add 9 1's to a listii . pick a number from list randomlyiii . If the number is less than 3 and sum of all numbers in list is less than 15 then increase the number by 1iv . 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2013-12-11
      • 2012-10-12
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      相关资源
      最近更新 更多