简体   繁体   English

如何生成限制在给定范围内的给定数字的随机倍数?

[英]How to generate a random multiple of a given number bounded to a given range?

How can I generate a random number which is a multiple of a given number while also making sure the number is also within a specified range?如何生成一个给定数字的倍数的随机数,同时确保该数字也在指定范围内? If there are no such multiples, it should return NaN .如果没有这样的倍数,它应该返回NaN

const generateMultiple = (multipleOf, min, max) => {
    //how to implement?
}

generateMultiple(4, -8, 5)
//should return either -8, -4, 0, 4

generateMultiple(2.1, 1, 5)
//should return either 2.1, 4.2

generateMultiple(7, 1, 5)
//should return NaN

You can normalize the range by dividing the endpoints by the number, generate a number in that range, and then multiply by the number to generate the multiple.您可以通过将端点除以数字来标准化范围,在该范围内生成一个数字,然后乘以该数字以生成倍数。

const generateMultiple = (multipleOf, min, max) => {
    const low = Math.ceil(min / multipleOf), high = Math.floor(max / multipleOf);
    return low <= high ? 
       (Math.floor(Math.random() * (high - low + 1)) + low) * multipleOf 
       : NaN;
}

Below function will do that.. function generateMultiple(multipleOf, min, max) { return Math.floor(Math.random() * (max-min) + min) ) * multipleOf; }下面 function 会这样做function generateMultiple(multipleOf, min, max) { return Math.floor(Math.random() * (max-min) + min) ) * multipleOf; } function generateMultiple(multipleOf, min, max) { return Math.floor(Math.random() * (max-min) + min) ) * multipleOf; }

declare your min, max, multiple numbers like this像这样声明你的最小值,最大值,多个数字

const multiple = 2;
const min = 1;
const max = 25;

use the below code to generate in a funtion and call when needed使用下面的代码在函数中生成并在需要时调用

(Math.floor(((Math.random()/multiple) * max) + min)) * multiple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM