随机数生成算法

时间:2018-10-16 10:46:54

标签: node.js algorithm

我不知道应该使用哪种算法。如有必要,平台为Node.js

Volume = 100; Range = 5...15; N = 10.

我需要从Range生成N个数字,这些数字加起来将得出Volume。最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

这是一个快速,幼稚的实现。

可能有一个数字技巧可以使此过程更快,但这可以起作用。 :)

请注意,当然可以传入参数组合以使此功能永远不会完成,但是对于total = 100, min = 5, max = 15, n = 10,它确实可以找到解决方案,例如

[ 14, 5, 11, 6, 10, 13, 9, 13, 14, 5 ]
[ 15, 13, 14, 10, 9, 8, 10, 8, 6, 7 ]
[ 8, 11, 11, 9, 12, 15, 5, 9, 6, 14 ]
[ 9, 12, 11, 6, 14, 12, 10, 7, 11, 8 ]
[ 9, 8, 9, 10, 11, 10, 12, 7, 14, 10 ]
[ 9, 9, 5, 14, 10, 13, 11, 13, 9, 7 ]

function generateNumbers(total, min, max, n) {
  while (true) {
    const numbers = [];
    let sum = 0;
    while (true) {
      let num;
      if (numbers.length === n - 1) {
        // Fill in the last number with the remainder to satisfy the problem
        num = total - sum;
        if (num < min || num === 0 || num > max) {
          // Out of bounds, this solution is invalid
          break; // Try again.
        }
      } else {
        num = Math.floor(min + Math.random() * (max + 1 - min));
      }
      numbers.push(num);
      sum += num;
      if (numbers.length === n && sum === total) {
        // Solution found.
        return numbers;
      }
      if (sum > total) {
        // Overshot, retry.
        break;
      }
    }
  }
}

console.log(generateNumbers(100, 5, 15, 10));
相关问题