有没有更好的解决方案

Is there a better solution for this?

本文关键字:解决方案 更好 有没有      更新时间:2023-09-26

我相信应该有一种更有创意的方法来解决这个问题......有人感兴趣吗?

问:给定以下代码,确定"a"的可能值范围:

  x = random_int(1,6)
  y = random_int(1,6)
  z = random_int(1,6)
  a = x + y + z

我的回答:

var x, y, z, a;
var range = [];
for (var i = 0; i < 1000; i++) {
  x = Math.floor(Math.random() * 6) + 1;
  y = Math.floor(Math.random() * 6) + 1;
  z = Math.floor(Math.random() * 6) + 1;
  a = x + y + z;
  range.push(a);
}
var min = Math.min.apply(null, range),
    max = Math.max.apply(null, range);
document.write("The range is between " + min + " and " + max);

这是所有代码:

document.write("The range is between 3 and 18");

因为最小值是当所有随机数均为 1 时,所以它将是

x = min(random_int(1,6)) = 1
y = min(random_int(1,6)) = 1
z = min(random_int(1,6)) = 1

所以

a = 1 + 1 + 1 = 3

最大值将是这样的:

x = max(random_int(1,6)) = 6
y = max(random_int(1,6)) = 6
z = max(random_int(1,6)) = 6

所以

a = 6 + 6 + 6 = 18