有更好的解决方案吗?

时间:2014-12-06 11:21:56

标签: javascript algorithm mathematical-optimization

我确定应该有更有创意的方法来解决这个问题......有兴趣吗?

问:根据以下代码,确定“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);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

这是所有代码:

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

因为最小值是所有randoms为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