Generowanie losowej liczby pomiędzy dwoma liczbami w JavaScript

Czy istnieje sposób na wygenerowanie liczby losowej w określonym zakresie (np. od 1 do 6: 1, 2, 3, 4, 5, lub 6) w JavaScript?

Author: vsync, 2011-02-10

17 answers

Jeśli chcesz dostać się między 1 A 6, obliczysz:

Math.floor(Math.random() * 6) + 1  

Gdzie:

  • 1 jest liczbą początkową
  • 6 to liczba możliwych wyników (1 + start (6) - end (1))
 1613
Author: khr055,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-10 09:32:54
function randomIntFromInterval(min,max) // min and max included
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

To, co robi "extra", to pozwala na losowe interwały, które nie zaczynają się od 1. Możesz więc otrzymać na przykład losową liczbę od 10 do 15. Elastyczność.

 1717
Author: Francisc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-02 11:29:51

Matematyka.losowe()

Z Mozilla Dokumentacja sieci programistów:

// Returns a random integer between min (include) and max (include)

Math.floor(Math.random() * (max - min + 1)) + min;

Przydatne przykłady:

// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
 204
Author: Lior Elrom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-06 02:18:54

Inne rozwiązania:

  • (Math.random() * 6 | 0) + 1
  • ~~(Math.random() * 6) + 1
 77
Author: Vishal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-29 17:27:56

TL; DR

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

Aby uzyskać losową liczbę generateRandomInteger(-20, 20);

WYJAŚNIENIE PONIŻEJ

Musimy uzyskać losową liczbę całkowitą, powiedzmy X pomiędzy min a max.

Prawda?

I. e min

Jeśli odejmujemy min z równania, to jest to równoważne

0

Pomnóżmy to przez losową liczbę r czyli

0

Teraz dodajmy min do równania

Min

Teraz wybierzmy funkcję, która daje r taką,że spełnia nasz zakres równań jako [min, max]. Jest to możliwe tylko wtedy, gdy 0

OK. Zakres r tj. [0,1] jest bardzo podobny do matematyki.wynik funkcji random (). Nie jest to?

Matematyka.funkcja random () zwraca zmiennoprzecinkową, pseudolosową liczba w zakresie [0, 1), czyli od 0 (włącznie) do including 1 (exclusive)

Na przykład,

Przypadek r = 0

min + 0 * (max-min) = min

Przypadek r = 1

min + 1 * (max-min) = max

Przypadek losowy z wykorzystaniem matematyki.random 0

min + r * (max-min) = X , gdzie X mA Zakres min X max

Powyższy wynik X jest liczbą losową. Jednak ze względu na matematykę.random() nasza lewa bound jest inkluzywna, a prawa bound jest wyłączna. Aby uwzględnić nasze prawo związane zwiększamy prawo związane o 1 i podnosimy wynik.

function generateRandomInteger(min, max) {
  return Math.floor(min + Math.random()*(max + 1 - min))
}

Aby uzyskać liczbę losową

generateRandomInteger(-20, 20);

 31
Author: Faiz Mohamed Haneef,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-01 13:20:57
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
 16
Author: ryebr3ad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-04 12:37:04

Lub w podkreślenie

_.random(min, max)
 16
Author: vladiim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-03 01:52:05

Jsfiddle: https://jsfiddle.net/cyGwf/477/

Losowa liczba całkowita : aby uzyskać losową liczbę całkowitą między min a max, Użyj następującego kodu

function getRandomInteger(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

Losowa liczba zmiennoprzecinkowa: aby uzyskać losową liczbę zmiennoprzecinkową między min a max, Użyj następującego kodu

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

Odniesienie: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

 16
Author: Razan Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-25 04:38:23

Matematyka nie jest moją mocną stroną, ale pracowałem nad projektem, w którym musiałem wygenerować wiele losowych liczb zarówno pozytywnych, jak i negatywnych.

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

E. g

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

Oczywiście możesz również dodać walidację, aby upewnić się, że nie robisz tego z niczym innym niż liczbami. Upewnij się również, że min jest zawsze mniejsza lub równa max.

 12
Author: Petter Thowsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-20 21:23:12

Napisałem bardziej elastyczną funkcję, która może dać liczbę losową, ale nie tylko całkowitą.

function rand(min,max,interval)
{
    if (typeof(interval)==='undefined') interval = 1;
    var r = Math.floor(Math.random()*(max-min+interval)/interval);
    return r*interval+min;
}

var a = rand(0,10); //can be 0, 1, 2 (...) 9, 10
var b = rand(4,6,0.1); //can be 4.0, 4.1, 4.2 (...) 5.9, 6.0

Wersja poprawiona.

 7
Author: ElChupacabra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-14 10:38:21

Przykład

Zwraca losową liczbę z zakresu od 1 do 10:

Math.floor((Math.random() * 10) + 1);

Wynik może być: 3

Spróbuj sam: tutaj

--

Lub używając lodash / undescore:

_.random(min, max)

Docs: - lodash - undescore

 6
Author: Sebastián Lara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-13 20:20:37

Szukałem generatora liczb losowych napisanego maszynopisem i napisałem to po przeczytaniu wszystkich odpowiedzi, mam nadzieję, że zadziała dla programistów maszynopisu.

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   
 3
Author: Erdi İzgi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-07 14:14:54

Pomimo wielu odpowiedzi i prawie tego samego wyniku. Chciałbym dodać swoją odpowiedź i wyjaśnić jej działanie. Ponieważ ważne jest, aby zrozumieć jego działanie, a nie kopiować wklejanie jednego kodu liniowego. Generowanie liczb losowych to nic innego jak prosta matematyka.

Kod:

function getR(lower, upper) {

  var percent = (Math.random() * 100);
  // this will return number between 0-99 because Math.random returns decimal number from 0-0.9929292 something like that
  //now you have a percentage, use it find out the number between your INTERVAL :upper-lower 
  var num = ((percent * (upper - lower) / 100));
  //num will now have a number that falls in your INTERVAL simple maths
  num += lower;
  //add lower to make it fall in your INTERVAL
  //but num is still in decimal
  //use Math.floor>downward to its nearest integer you won't get upper value ever
  //use Math.ceil>upward to its nearest integer upper value is possible
  //Math.round>to its nearest integer 2.4>2 2.5>3   both lower and upper value possible
  console.log(Math.floor(num), Math.ceil(num), Math.round(num));
}
 3
Author: Arun Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-15 05:44:47

Sens musisz dodać 1 do maksymalnej liczby, a następnie odjąć minimalną liczbę, aby cokolwiek z tego działało, i muszę zrobić wiele losowych liczb całkowitych, ta funkcja działa.

var random = function(max, min) {
    high++;
    return Math.floor((Math.random()) * (max - min)) + min;
};
To działa zarówno z liczbami ujemnymi, jak i dodatnimi, a ja pracuję nad dziesiętnymi dla biblioteki.
 1
Author: Travis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-01 00:15:49

Zamiast Math.random(), możesz użyć crypto.getRandomValues() do generowania równomiernie rozłożonych kryptograficznie bezpiecznych liczb losowych. Oto przykład:

function randInt(min, max) {
  var MAX_UINT32 = 0xFFFFFFFF;
  var range = max - min;

  if (!(range <= MAX_UINT32)) {
    throw new Error(
      "Range of " + range + " covering " + min + " to " + max + " is > " +
      MAX_UINT32 + ".");
  } else if (min === max) {
    return min;
  } else if (!(max > min)) {
    throw new Error("max (" + max + ") must be >= min (" + min + ").");
  }

  // We need to cut off values greater than this to avoid bias in distribution
  // over the range.
  var maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

  var rand;
  do {
    rand = crypto.getRandomValues(new Uint32Array(1))[0];
  } while (rand > maxUnbiased);

  var offset = rand % (range + 1);
  return min + offset;
}

console.log(randInt(-8, 8));          // -2
console.log(randInt(0, 0));           // 0
console.log(randInt(0, 0xFFFFFFFF));  // 944450079
console.log(randInt(-1, 0xFFFFFFFF));
// Uncaught Error: Range of 4294967296 covering -1 to 4294967295 is > 4294967295.
console.log(new Array(24).fill().map(n => randInt(8, 12)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9,
//  11, 8, 11, 8, 8, 8, 11, 9, 10, 12, 9, 11]
console.log(randInt(10, 8));
// Uncaught Error: max (8) must be >= min (10).
 0
Author: Jeremy Banks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-10 09:26:50
function random(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
 -3
Author: Sarvesh Kesharwani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-19 21:53:28

Znalazłem rozwiązanie Francisc powyżej nie zawierało liczby min lub max w wynikach, więc zmieniłem to tak:

function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-(min+1))+(min+1));
}
 -4
Author: Rastus Oxide,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-22 10:35:28