Générer des nombres aléatoires entre deux nombres en JavaScript

Est-il un moyen pour générer un nombre aléatoire dans une plage spécifiée (par exemple de 1 à 6: 1, 2, 3, 4, 5, ou 6) en JavaScript?

1315
demandé sur vsync 2011-02-10 19:41:22

17 réponses

si vous vouliez obtenir entre 1 et 6, Vous calculeriez:

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

où:

  • 1 est le nombre de départ
  • 6 est le nombre de résultats possibles (1 + Début (6) - fin (1) )
1613
répondu khr055 2016-04-10 09:32:54
function randomIntFromInterval(min,max) // min and max included
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

Ce qu'il fait "extra" est-il permet à des intervalles aléatoires qui ne commencent pas avec 1. Ainsi, vous pouvez obtenir un nombre aléatoire de 10 à 15 par exemple. Flexibilité.

1717
répondu Francisc 2018-10-02 11:29:51

"151930920 des Mathématiques".random()

From the Mozilla Developer Network documentation:

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

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

exemples utiles:

// 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
répondu Lior Elrom 2018-06-06 02:18:54

autres solutions:

  • (Math.random() * 6 | 0) + 1
  • ~~(Math.random() * 6) + 1
77
répondu Vishal 2012-10-29 17:27:56

TL; DR

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

Pour obtenir le nombre aléatoire generateRandomInteger(-20, 20);

EXPLICATION CI-DESSOUS

nous avons besoin d'obtenir un entier aléatoire, dire X entre min et max.

C'est ça?

I. e min < = X < = max

si nous soustrayons min de la l'équation, c'est l'équivalent de

0 <= (X-min) < = (max-min)

maintenant, permet de multiplier ceci avec un nombre aléatoire r qui est

0 <= (X-min) * r < = (max-min) * r

maintenant, ajoutons min à l'équation

min < = min + (X-min) * r <= min + (max-min) * r

maintenant, nous permet de choisir une fonction qui résulte en r tel qu'il satisfait notre gamme d'équation comme [min,max]. Cela n'est possible que si 0< = r <=1

OK. Maintenant, la gamme de r I. e [0,1] est très similaire aux mathématiques.random() résultat de la fonction. N'est-ce pas?

Les Maths.random() renvoie un point flottant, pseudo-aléatoire nombre dans l'intervalle [0, 1); c'est, entre 0 (inclus) jusqu'à y compris 1 (exclusif)

par exemple,

Cas r = 0

min + 0 * ( max - min ) = min

Cas r = 1

min + 1 * ( max - min ) = max. 1519150920"

cas aléatoire utilisant les mathématiques.aléatoire 0 <= r < 1

min + r * ( max - min ) = X , où X a une portée de min < = X < max

le résultat ci-dessus X est un chiffre aléatoire. Mais à cause des maths.random() notre limite gauche est inclusive, et la droite lié est exclusif. Notre droit lié nous augmentons le droit lié par le 1er étage et le résultat.

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

pour obtenir le nombre aléatoire

generateRandomInteger(-20, 20) ;

31
répondu Faiz Mohamed Haneef 2018-10-01 13:20:57
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;
16
répondu ryebr3ad 2012-12-04 12:37:04

, Ou, trait de Soulignement

_.random(min, max)
16
répondu vladiim 2014-10-03 01:52:05

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

nombre entier aléatoire : pour obtenir un nombre entier aléatoire entre min et max , utilisez le code suivant

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

nombre aléatoire de virgule flottante : pour obtenir un nombre aléatoire de virgule flottante entre min et max , utilisez le code suivant

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

référence: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

16
répondu Razan Paul 2017-01-25 04:38:23

mathématiques n'est pas mon point fort, mais j'ai travaillé sur un projet où j'avais besoin de générer beaucoup de nombres aléatoires entre positif et négatif.

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)

bien sûr, vous pouvez aussi ajouter une validation pour vous assurer que vous ne faites pas cela avec autre chose que des nombres. Assurez-vous également que min est toujours inférieur ou égal à max.

12
répondu Petter Thowsen 2013-03-20 21:23:12

j'ai écrit une fonction plus flexible qui peut vous donner un nombre aléatoire mais pas seulement entier.

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

version fixe.

7
répondu ElChupacabra 2015-09-14 10:38:21

exemple

retourner un nombre aléatoire entre 1 et 10:

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

Le résultat pourrait être: 3

Essayez vous-même: ici

--

ou en utilisant lodash / undescore:

_.random(min, max)

Docs: - lodash - undescore

6
répondu Sebastián Lara 2016-12-13 20:20:37

j'étais en train de chercher le générateur de nombres aléatoires écrit à la machine à écrire et j'ai écrit ceci après avoir lu toutes les réponses, j'espère que cela fonctionnerait pour les codeurs de caractères.

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   
3
répondu Erdi İzgi 2014-09-07 14:14:54

en dépit de nombreuses réponses et presque le même résultat. Je voudrais ajouter ma réponse et expliquer son travail. Parce qu'il est important de comprendre son fonctionnement plutôt que de copier coller un code de ligne. Générer des nombres aléatoires n'est rien d'autre que des maths simples.

CODE:

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
répondu Arun Sharma 2017-01-15 05:44:47

Sens vous avez besoin pour ajouter 1 au nombre maximum, puis soustraire le nombre minimum pour tout ce travail, et j'ai besoin de faire beaucoup d'Entiers aléatoires, cette fonction fonctionne.

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

cela fonctionne avec des nombres négatifs et positifs, et je travaille sur des décimales pour une bibliothèque.

1
répondu Travis 2015-02-01 00:15:49

au lieu de Math.random() , vous pouvez utiliser crypto.getRandomValues() pour générer des nombres aléatoires uniformément répartis et protégés par cryptographie. Voici un exemple:

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
répondu Jeremy Banks 2016-04-10 09:26:50
function random(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
-3
répondu Sarvesh Kesharwani 2017-08-19 21:53:28

j'ai trouvé la solution de Francisc ci-dessus n'a pas inclus le nombre min ou max dans les résultats, donc je l'ai modifié comme ceci:

function randomInt(min,max)
{
    return Math.floor(Math.random()*(max-(min+1))+(min+1));
}
-4
répondu Rastus Oxide 2014-02-22 10:35:28