Сайт компьютерных навыков

Генерирование случайных целых чисел в JavaScript в определенном диапазоне? Случайные числа Javascript math random целые числа

The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range - which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

Math.random() does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the method.

Syntax Math.random() Return value

A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

Examples

Note that as numbers in JavaScript are IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren"t exact. If extremely large bounds are chosen (2 53 or higher), it"s possible in extremely rare cases to calculate the usually-excluded upper bound.

Getting a random number between 0 (inclusive) and 1 (exclusive) function getRandom() { return Math.random(); } Getting a random number between two values

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min , and is less than (and not equal) max .

Function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }

Getting a random integer between two values

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn"t an integer), and is less than (but not equal to) max .

Function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive }

It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

Getting a random integer between two values, inclusive

While the getRandomInt() function above is inclusive at the minimum, it"s exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

Function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive }

Specifications Specification Status Comment
ECMAScript 1st Edition (ECMA-262) Standard Initial definition. JavaScript 1.0 (UNIX Only) / JavaScript 1.1 (All platforms).
ECMAScript 5.1 (ECMA-262)
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Math.random" in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of "Math.random" in that specification.
Draft
Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js random
Chrome Full support Yes Edge Full support 12 Firefox Full support 1 IE Full support Yes Opera Full support Yes Safari Full support Yes WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes nodejs Full support Yes

Есть несколько примеров:

/** * Returns a random number between min (inclusive) and max (exclusive) */ function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } /** * Returns a random integer between min (inclusive) and max (inclusive). * The value is no lower than min (or the next integer greater than min * if min isn"t an integer) and no greater than max (or the next integer * lower than max if max isn"t an integer). * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }

Здесь логика за этим. Это простое правило трех:

Math.random() возвращает Number от 0 (включительно) до 1 (исключение). Итак, у нас есть такой интервал:

Num3; num3 = num2 - num3; if (num3 < 0) { num3 += 2147483647; } num2 = this.SeedArray; } for (var j = 1; j < 5; j++) { for (var k = 1; k < 56; k++) { this.SeedArray[k] -= this.SeedArray; if (this.SeedArray[k] < 0) { this.SeedArray[k] += 2147483647; } } } this.inext = 0; this.inextp = 21; Seed = 1; } Random.prototype.milliseconds = function () { var str = new Date().valueOf().toString(); return parseInt(str.substr(str.length - 6)); }; Random.prototype.InternalSample = function () { var num = this.inext; var num2 = this.inextp; if (++num >= 56) { num = 1; } if (++num2 >= 56) { num2 = 1; } var num3 = this.SeedArray - this.SeedArray; if (num3 == 2147483647) { num3--; } if (num3 < 0) { num3 += 2147483647; } this.SeedArray = num3; this.inext = num; this.inextp = num2; return num3; }; Random.prototype.Sample = function () { return this.InternalSample() * 4.6566128752457969E-10; }; Random.prototype.GetSampleForLargeRange = function () { var num = this.InternalSample(); var flag = this.InternalSample() % 2 == 0; if (flag) { num = -num; } var num2 = num; num2 += 2147483646.0; return num2 / 4294967293.0; }; Random.prototype.Next = function (minValue, maxValue) { if (!minValue && !maxValue) return this.InternalSample(); var num = maxValue - minValue; if (num количество элементов диапазона = 247 - 78 + 1 = 170; (так как обе границы включены.

/*Mthod 1:*/ var i = 78, j = 247, k = 170, a = , b = , c, d, e, f, l = 0; for(; i 20) { bool = true; } else { bool = false; } } return number; }

Используя следующий код, вы можете генерировать массив случайных чисел без повторения в заданном диапазоне.

Function genRandomNumber(how_many_number,min,max) { // parameters // how_many_number: how many numbers you want to generate. For example it is 5. // min(inclusive) : minimum/low value of a range. it must be any positive integer but less than max. i.e 4 // max(inclusive) : maximun value of a range. it must be any positive integer. i.e 50 // return type: array var random_number = ; for (var i = 0; i < how_many_number; i++) { var gen_num = parseInt((Math.random() * (max-min+1)) + min); do { var is_exist = random_number.indexOf(gen_num); if (is_exist >= 0) { gen_num = parseInt((Math.random() * (max-min+1)) + min); } else { random_number.push(gen_num); is_exist = -2; } } while (is_exist > -1); } document.getElementById("box").innerHTML = random_number; }

Чтобы получить случайное число, скажем, между 1 и 6, сначала выполните:

0.5 + (Math.random() * ((6 - 1) + 1))

Это умножает случайное число на 6 и затем добавляет к нему 0.5. Затем округлите число до положительного целого числа, выполнив:

Math.round(0.5 + (Math.random() * ((6 - 1) + 1))

Это округляет число до ближайшего целого числа.

Или, чтобы сделать это более понятным, выполните следующее:

Var value = 0.5 + (Math.random() * ((6 - 1) + 1)) var roll = Math.round(value); return roll;

В общем случае код для этого с использованием переменных:

Var value = (Min - 0.5) + (Math.random() * ((Max - Min) + 1)) var roll = Math.round(value); return roll;

Причиной отнять 0,5 от минимального значения является то, что использование только минимального значения позволит вам получить целое число, которое было бы больше вашего максимального значения. Убрав 0,5 от минимального значения, вы по существу предотвращаете округление максимального значения.

Надеюсь, что это поможет.

Случайное целое число между самым низким и самым высоким:

Function randomRange(l,h){ var range = (h-l); var random = Math.floor(Math.random()*range); if (random === 0){random+=1;} return l+random; }

Не самое элегантное решение.. но что-то быстрое.

Function getRandomInt(lower, upper) { //to create an even sample distribution return Math.floor(lower + (Math.random() * (upper - lower + 1))); //to produce an uneven sample distribution //return Math.round(lower + (Math.random() * (upper - lower))); //to exclude the max value from the possible values //return Math.floor(lower + (Math.random() * (upper - lower))); }

Чтобы проверить эту функцию и варианты этой функции, сохраните ниже HTML/JavaScript в файл и откройте его в браузере. В коде будет показан график, показывающий распределение одного миллиона вызовов функций. Код также будет записывать случаи краев, поэтому, если функция вырабатывает значение, большее, чем max, или меньше, чем min, you.will.know.about.it.

function getRandomInt(lower, upper) { //to create an even sample distribution return Math.floor(lower + (Math.random() * (upper - lower + 1))); //to produce an uneven sample distribution //return Math.round(lower + (Math.random() * (upper - lower))); //to exclude the max value from the possible values //return Math.floor(lower + (Math.random() * (upper - lower))); } var min = -5; var max = 5; var array = new Array(); for(var i = 0; i Number.MAX_SAFE_INTEGER || min < Number.MIN_SAFE_INTEGER) { throw new Error("Arguments must be safe integers."); } else if (range > maxGeneratedValue) { throw new Error("Range of ${range} (from ${min} to ${max}) > ${maxGeneratedValue}."); } else if (max < min) { throw new Error("max (${max}) must be >= min (${min})."); } else if (min === max) { return min; } let generated; do { generated = crypto.getRandomValues(new Uint32Array(1)); } while (generated > maxUnbiased); return min + (generated % possibleResultValues); }; console.log(randomInteger(-8, 8)); // -2 console.log(randomInteger(0, 0)); // 0 console.log(randomInteger(0, 0xFFFFFFFF)); // 944450079 console.log(randomInteger(-1, 0xFFFFFFFF)); // Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295. console.log(new Array(12).fill().map(n => randomInteger(8, 12))); //

«Алгоритм» для случайной выборки значений из array без их повторения. Конкретнее, в рамках обучения JS, я использовал его для генерации классической RPG-группы персонажей (варвар, маг, вор, рыцарь, священник), без повторения классов и имен.

Принцип предельно простой, но он может быть полезен таким же новичкам в JS как и я. Привязка к RPG исключительно символическая - сейчас я активно пытаюсь сменить профиль с маркетинга на IT (понял, что душа лежит), а практиковаться в игровой форме гораздо интереснее.

1. Создаем шаблон Прежде чем генерировать группу персонажей, нужно задать шаблон для их генерации. Собственно, вот:

Function GamePlayer(n, r, l, p) { this.nick = n; this.role = r; this.level = l; this.portrait = p; }
Фактически, эта функция будет создавать персонажей из переменных, через которые она будет вызвана. Например:

Var player1 = new GamePlayer("Power Ranger","barbarian","64","img/barbarian.jpg")
Теперь в переменной player1 хранится варвар Power Ranger 64 уровня с определенным портретом; мы можем отображать любые его параметры в теле страницы используя player1.nick , player1.level и т.п.

Значения (n, r, l, p) из GamePlayer отвечают за прием и порядок приема данных в функцию. Если в примере поменять n и r местами, то в player1 сохранится могучий рейнджер Barbarian, что не совсем соответствует задаче.

2. Задаем массивы Чтобы не создавать персонажей самостоятельно, а почти случайно генерировать их (как и обещалось в заголовке), необходимы массивы из которых мы будем брать параметры этих самых персонажей. Как уже описывалось выше, параметров у нас всего 4: имя персонажа, класс, уровень и портрет.

Массив для имени:

Var playerNames = ["Rabbit Helpless", "Warm Dreaded Foal", "Desire Kit", "Angel Dusty", "Sweety Frozen", "Silver Heavy Wombat", "Lost Puma", "Vital Panda", "Rolling Sun", "Steel Runny", "Young Fox", "Needless Ruthless Volunteer", "Chipmunk Cult", "Indigo Puppy"];
Можно было бы пойти дальше, и генерировать имена из 2-3 составляющих, но алгоритм такого улучшения не содержит ничего нового (тот же рандом), а потом просто усложнил бы учебный процесс.

Массив для класса:

Var playerRoles = ["barbarian", "mage", "rogue", "knight", "priest"];
Все так же очевидно. Несколько string , из которых мы потом будем выбирать значения для отображения на странице.

Массив для уровня:

В конкретном примере, я хотел, чтобы все члены группы были от 60 до 70 уровня. Но, так как условия могут поменяться, нужны было создать массив с 0 по 80 уровень, из которого потом выбирать нужные значения. Создавал циклом:

Var playerLevels = ; for (i = 0;i

Похожие публикации