- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 2 个范围(例如 100 到 150)之间生成总和为 N 的随机数。
到目前为止我做了什么:
function randomNumbers() {
let i, nb, min, max, totAtteindre, tot, ajout;
let resultat = new (Array);
let alea = [];
nb = document.getElementById("nbjours").value;
totAtteindre = document.getElementById("total").value;
min = Math.ceil(document.getElementById("minimum").value);
max = Math.floor(document.getElementById("maximum").value);
tot = 0;
for (i = 0; i < nb ; i++)
{
alea[i] = Math.random() * (max - min) + min;
alea[i] = alea[i].toFixed(2);
alea[i] = parseFloat(alea[i]);
tot += alea[i];
}
tot = parseFloat(tot);
if (totAtteindre > tot)
{
ajout = (totAtteindre - tot) / nb;
ajout = ajout.toFixed(2);
ajout = parseFloat(ajout);
for (i = 0; i < nb ; i++)
{
alea[i] += ajout;
tot += ajout;
}
}
else
{
ajout = (tot - totAtteindre) / nb ;
ajout = ajout.toFixed(2);
ajout = parseFloat(ajout);
for (i = 0; i < nb ; i++)
{
alea[i] -= ajout;
tot -= ajout;
}
}
let tmp = totAtteindre - tot;
tot += tmp;
alea[0] += tmp;
// Affichage en vert ou rouge pour les valeurs positives ou négatives
for (i = 0; i < nb ; i++)
{
if ((alea[i] > min) && (alea[i] < max))
{
resultat += alea[i].toFixed(2).replace('.', ',').fontcolor("green");
if (i < nb-1)
{
resultat += "<br>";
}
}
else
{
resultat += alea[i].toFixed(2).replace('.', ',').fontcolor("red");
if (i < nb-1)
{
resultat += "<br>";
}
}
}
document.getElementById("valeurs").innerHTML = resultat;
document.getElementById("totalAp").innerHTML = tot.toFixed(2);
}
<body>
<main>
<header>
<h1 style="font-size: 40px; text-align: center; margin: 20px; border: solid 2px black; font-family: 'Big Caslon'"><strong>Générateur de valeurs aléatoires</strong></h1>
</header>
<section>
<form style="display: block; margin: 20px; text-align: center;">
<h1 style="margin-bottom: 50px; font-family: 'Big Caslon';" ><u>Veuillez saisir le nombre de valeurs, les bornes inférieures/supérieures approximatives et le montant à atteindre</u><br></h1>
<fieldset>
<legend><strong>Nombre de valeurs</strong></legend>
<input id="nbjours" type="number" name ="nbj">
</fieldset>
<br>
<fieldset>
<legend><strong>Bornes journalières approximatives</strong></legend>
<input id="minimum" type="number" name="mont1">
<input id="maximum" type="number" name="mont2">
<div class="help-tip">
<p style="text-align: justify; font-size: smaller">Il est possible d'avoir un résultat dont les valeurs dépassent les bornes. <br>Dans ce cas-là, diminuez les bornes ou augmentez les.</p>
</div>
</fieldset>
<br>
<fieldset>
<legend><strong>Montant à atteindre</strong></legend>
<input id="total" type="number" name="to">
</fieldset>
</form>
<div style="display: flex; justify-content: center; margin: 20px;">
<button onclick="randomNumbers()" class="myButton">Générer</button>
</div>
</section>
<section style="display: block; text-align: center; margin-top: 10px; width: 50%; margin-left: auto; margin-right: auto">
<fieldset>
<legend style="background-color: unset;">
<button onclick="copyText('valeurs')">
Copier les valeurs
</button>
<br>
</legend>
<div id="valeurs" ></div>
</fieldset>
</section>
<section style="text-align: center; margin: 10px; width: 30%; display: block; margin-left: auto; margin-right: auto">
<fieldset>
<legend style="background-color: firebrick"><strong>Total</strong></legend>
<div id="totalAp"></div>
</fieldset>
</section>
</main>
</body>
</html>
如您所见,有时您会得到低于最小值或最大值的值。
因为我将剩余的总数除以值的数量并将它们添加到每个值。
我不知道是否有一种方法可以像方法一样严格地只获取两个范围(最小值和最大值)之间的值。我也许可以做 if 语句,不将附加值添加到那些会超过最小/最大值并划分更多的值。但我试过了,我仍然会得到一两个不在严格范围内的结果。
最佳答案
此函数有四个参数:size
、min
、max
和 sum
- 其中 size
是您要生成的数组的长度。如果您传递的 mix
/max
/size
组合是一项不可能完成的任务,则将返回 false
,这意味着要么选择每次都选择最小值仍然太高,或者每次都选择最大值仍然太低。
为了创建数组(称为 set
),我们选择 size - 1
随机数,每次从我们想要的 sum
中减去随机数>。重要的是,我们还检查每个选择,确保选择不会导致每次选择最小值仍然太高或每次选择最大值仍然太低的情况。如果我们发现是这种情况,我们的 while
循环会废弃该随机数并选择一个不同的随机数。因为我们使用这种方法永远不会为失败做好准备,所以我们只需要选择 size - 1
随机数,而 sum
变量中剩下的保证是在我们的 min
/max
范围内,并使我们的总数达到我们最初想要的总和。
这里的瓶颈是我们要求两个数字之间的随机 float ,但如果它不符合我们不可告人的动机,则拒绝它。太多的拒绝会减慢速度,所以你留下越多的填充来玩,这可能表现得越好。例如,randomSet(10, 50, 100, 500);
实际上肯定会停止(因为我们必须连续 10 次恰好选择 50.00000 - 机会有多大其中的??),而 randomSet(10, 50, 100, 750);
几乎不需要时间就可以成功完成。
function randomSet(size, min, max, sum) {
if (min * size > sum || max * size < sum) return false;
var set = [];
for (; size > 1; size--) {
var randomNumber = rando(min, max, "float");
while (min * (size - 1) > sum - randomNumber || max * (size - 1) < sum - randomNumber) {
randomNumber = rando(min, max, "float");
}
set.push(randomNumber);
sum -= randomNumber;
}
set.push(sum);
return set;
}
var myRandomSet = randomSet(30, 100, 200, 4500);
console.log(myRandomSet);
console.log("SUM: " + myRandomSet.reduce((a, b) => a + b, 0));
<script src="https://randojs.com/1.0.0.js"></script>
如果你想要四舍五入到百分之一的 float :
function randomSet(size, min, max, sum) {
if (min * size > sum || max * size < sum) return false;
var set = [];
for (; size > 1; size--) {
var randomNumber = Math.round(rando(min, max, "float") * 100) / 100;
while (min * (size - 1) > sum - randomNumber || max * (size - 1) < sum - randomNumber) {
randomNumber = Math.round(rando(min, max, "float") * 100) / 100;
}
set.push(randomNumber);
sum -= randomNumber;
}
set.push(Math.round(sum * 100) / 100);
return set;
}
var myRandomSet = randomSet(30, 100, 200, 4500);
console.log(myRandomSet);
console.log("SUM: " + myRandomSet.reduce((a, b) => a + b, 0));
<script src="https://randojs.com/1.0.0.js"></script>
此代码使用 randojs.com简化最小/最大 float 随机性,因为该算法足够复杂,而无需将常见的随机性数学混入其中。所以,如果你想使用这段代码,只需确保将它包含在你的 html 文档的 head 标签中:
<script src="https://randojs.com/1.0.0.js"></script>
关于javascript - 2 个范围(例如 100 和 150)之间的随机 30 个数字( float ),总和为 N,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60214727/
我需要修复 getLineNumberFor 方法,以便如果 lastName 的第一个字符位于 A 和 M 之间,则返回 1;如果它位于 N 和 Z 之间,则返回 2。 在我看来听起来很简单,但我不
您好,感谢您的帮助!我有这个: 0 我必须在每次点击后增加“pinli
Javascript 中是否有一种方法可以在不使用 if 语句的情况下通过 switch case 结构将一个整数与另一个整数进行比较? 例如。 switch(integer) { case
我有一列是“日期”类型的。如何在自定义选项中使用“之间”选项? 最佳答案 请注意,您有2个盒子。 between(在SQL中)包含所有内容,因此将框1设置为:DATE >= startdate,将框2
我有一个表,其中包含年、月和一些数字列 Year Month Total 2011 10 100 2011 11 150 2011 12 100 20
这个问题已经有答案了: Extract a substring between double quotes with regular expression in Java (2 个回答) how to
我有一个带有类别的边栏。正如你在这里看到的:http://kees.een-site-bouwen.nl/ url 中类别的 ID。带有 uri 段(3)当您单击其中一个类别时,例如网页设计。显示了一
这个问题在这里已经有了答案: My regex is matching too much. How do I make it stop? [duplicate] (5 个答案) 关闭 4 年前。 我
我很不会写正则表达式。 我正在尝试获取括号“()”之间的值。像下面这样的东西...... $a = "POLYGON((1 1,2 2,3 3,1 1))"; preg_match_all("/\((
我必须添加一个叠加层 (ImageView),以便它稍微移动到包含布局的左边界的左侧。 执行此操作的最佳方法是什么? 尝试了一些简单的方法,比如将 ImageView 放在布局中并使用负边距 andr
Rx 中是否有一些扩展方法来完成下面的场景? 我有一个开始泵送的值(绿色圆圈)和其他停止泵送的值(簧片圆圈),蓝色圆圈应该是预期值,我不希望这个命令被取消并重新创建(即“TakeUntil”和“Ski
我有一个看起来像这样的数据框(Dataframe X): id number found 1 5225 NA 2 2222 NA 3 3121 NA 我有另一个看起来
所以,我正在尝试制作正则表达式,它将解析存储在对象中的所有全局函数声明,例如,像这样 const a = () => {} 我做了这样的事情: /(?:const|let|var)\s*([A-z0-
我正在尝试从 Intellivision 重新创建 Astro-Smash,我想让桶保持在两个 Angular 之间。我只是想不出在哪里以及如何让这个东西停留在两者之间。 我已经以各种方式交换了函数,
到处检查但找不到答案。 我有这个页面,我使用 INNER JOIN 将两个表连接在一起,获取它们的值并显示它们。我有这个表格,用来获取变量(例如开始日期、结束日期和卡号),这些变量将作为从表中调用值的
我陷入了两个不同的问题/错误之间,无法想出一个合适的解决方案。任何帮助将不胜感激 上下文、FFI 和调用大量 C 函数,并将 C 类型包装在 rust 结构中。 第一个问题是ICE: this pat
我在 MySQL 中有一个用户列表,在订阅时,时间戳是使用 CURRENT_TIMESTAMP 在数据库中设置的。 现在我想从此表中选择订阅日期介于第 X 天和第 Y 天之间的表我尝试了几个查询,但不
我的输入是开始日期和结束日期。我想检查它是在 12 月 1 日到 3 月 31 日之间。(年份可以更改,并且只有在此期间内或之外的日期)。 到目前为止,我还没有找到任何关于 Joda-time 的解决
我正在努力了解线程与 CPU 使用率的关系。有很多关于线程与多处理的讨论(一个很好的概述是 this answer )所以我决定通过在运行 Windows 10、Python 3.4 的 8 CPU
我正在尝试编写 PHP 代码来循环遍历数组以创建 HTML 表格。我一直在尝试做类似的事情: fetchAll(PDO::FETCH_ASSOC); ?>
我是一名优秀的程序员,十分优秀!