source

JavaScript에서 두 숫자 사이의 난수 생성

factcode 2022. 9. 12. 11:35
반응형

JavaScript에서 두 숫자 사이의 난수 생성

JavaScript를 사용하여 지정된 범위의 난수를 생성하는 방법이 있습니까?

를 들어, 1~6지정 범위는, 난수 1, 2, 3, 4, 5, 또는 6 의 어느쪽인가지정할 수 있습니다.

function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min)
}

const rndInt = randomIntFromInterval(1, 6)
console.log(rndInt)

추가 기능은 1로 시작하지 않는 랜덤 간격을 허용하는 것입니다.예를 들어, 10에서 15까지의 임의의 숫자를 얻을 수 있습니다.유연성

중요한

The following code works only if the minimum value is `1`. It does not work for minimum values other than `1`.

1과 6 사이의 랜덤 정수를 얻으려면 다음과 같이 계산합니다.

    const rndInt = Math.floor(Math.random() * 6) + 1
    console.log(rndInt)

장소:

  • 1은 시작 번호입니다.
  • 6은 가능한 결과의 수(1 + 시작(6) - 끝(1)입니다.

Math.random()

min(포함)과 max(포함) 사이의 정수 난수를 반환합니다.

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

또는 최소값(포함)과 최대값(포함되지 않음) 사이의 임의의 난수:

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

유용한 예(정수):

// 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;

** 그리고 항상 상기시켜줘 (모질라) :

Math.random()은 암호학적으로 안전한 난수를 제공하지 않습니다.보안과 관련된 용도로 사용하지 마십시오.대신 Web Crypto API, 보다 정확하게는 window.crypto.getRandomValues() 메서드를 사용합니다.

기타 솔루션:

  • (Math.random() * 6 | 0) + 1
  • ~~(Math.random() * 6) + 1

온라인으로 시험해 보다

TL;DR

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

generateRandomInteger(-20, 20);

아래 설명

integer - A number which is not a fraction; a whole number

우리는 최소값과 최대값 사이의 임의의 숫자를 얻을 필요가 있다. X, min and max are all integers

즉, 최소 <= X <= 최대

방정식에서 min을 빼면 다음과 같습니다.

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

이제, 여기에 난수 r을 곱해봅시다.

0 <= (X - min) * r <= (최대 - min) * r

이제 방정식에 min을 더합시다.

min <= min + (X - min) * r <= min + (최대 - min) * r

임의의 X에 대해서, 위의 방정식은 r의 범위가 [0,1]만 만족하고, r의 다른 값에 대해서는 위의 방정식이 만족되지 않는다.

[x,y] 또는 (x,y) 범위에 대한 자세한 내용은 여기를 참조하십시오.

다음 단계는 항상 [0,1] 범위의 값이 되는 함수를 찾는 것입니다.

r, 즉 [0,1]의 범위는 Javascript의 Math.random() 함수와 매우 유사합니다.아니니?

Math.random() 함수는 [0, 1) 범위의 부동 소수점 의사 난수를 반환합니다. 즉, 0(포함)부터 1(포함)까지입니다.

Math.random() 0 <= r < 1을 사용한 랜덤 함수

Math.random()은 Math.random(), Math.random()은 Math.random(), Math.random()은 Math.random(), Math.은 ①을 의미합니다.min + (max - min) * r에서는 의 합니다.[min, max)

를 들면 「 」( 「 」)입니다.[min,max]오른쪽 바운드를 1만큼 늘리고 결과를 플로어링합니다.

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

난수를 얻으려면

generateRandomInteger(-20, 20);

또는 언더스코어

_.random(min, max)
var x = 6; // can be any number
var rand = Math.floor(Math.random()*x) + 1;

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

Random Integer: 다음 사이의 임의의 정수를 가져옵니다.min ★★★★★★★★★★★★★★★★★」max 다음

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

랜덤 부동소수점 번호: 다음 사이의 랜덤 부동소수점 번호를 가져옵니다.min ★★★★★★★★★★★★★★★★★」max 다음

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

참고 자료: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

수학은 내 강점은 아니지만, 양수와 음수 사이에서 많은 난수를 생성해야 하는 프로젝트를 진행해왔다.

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

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

물론 숫자 이외의 다른 방법으로 이 작업을 수행하지 않도록 유효성 검사를 추가할 수도 있습니다.또한 min이 항상 max보다 작거나 같은지 확인하십시오.

0에서 400 사이의 임의의 정수를 가져옵니다.

let rand = Math.round(Math.random() * 400)

document.write(rand)

200에서 1500 사이의 임의의 정수를 가져옵니다.

let range = {min: 200, max: 1500}
let delta = range.max - range.min

const rand = Math.round(range.min + Math.random() * delta)

document.write(rand)

기능 사용

function randBetween(min, max){
  let delta = max - min
  return Math.round(min + Math.random() * delta)
}

document.write(randBetween(10, 15));

// JavaScript ES6 arrow function

const randBetween = (min, max) => {
  let delta = max - min
  return Math.round(min + Math.random() * delta)
}

document.write(randBetween(10, 20))

ES6 / Arrow 기능 버전은 Francis의 코드를 기반으로 합니다(상위 답변).

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

정수뿐만 아니라 난수를 줄 수 있는 보다 유연한 함수를 작성했습니다.

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

고정 버전

1에서 10 사이의 난수를 반환합니다.

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

는 다음과 3

직접 사용해 보세요: 여기

--

또는 lodash/unescore를 사용합니다.

_.random(min, max)

문서: - lodash - unescore

저는 TypeScript로 작성된 난수 생성기를 검색하다가 모든 답을 읽고 이 글을 썼습니다.TypeScript 코더에 해당되기를 바랍니다.

    Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }   

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

작업: 1에서 6 사이의 난수를 생성합니다.

Math.random() 1(0.0. 등, 「0~1」은 「(0.344717274374」는 「0.99123」입니다.Math.floor(Math.random() * 6) + 1는 몇 퍼센트의 6(최대: 5, 최소: 0)을 반환하고 1을 추가합니다.작성자는 운이 좋게도 하한치가 1. 왜냐하면 백분율 바닥이 6개씩 작은 반환 5를 "최대" 반환하고 하한치 1이 추가되기 때문입니다.

이 문제는 하한값이 1보다 클 때 발생합니다.를 들어 작업: 2에서 6 사이의 랜덤 생성입니다.

(작성자의 논리) Math.floor(Math.random() * 6) + 2여기서 5를 얻으면 ->Math.random() * 6그리고 2를 더하면 원하는 경계인 6을 넘는 7이 됩니다.

또 다른 예로는 태스크: 10에서 12 사이의 랜덤 생성입니다.

(작성자의 논리) Math.floor(Math.random() * 12) + 10(반복해서 죄송합니다) 숫자 '12'의 0%~99%를 얻을 수 있습니다.이는 바람직한 경계인 12를 훨씬 넘어설 것입니다.

따라서 올바른 논리는 하한 덧셈 1과 상한 덧셈 1의 차이를 취한 다음 바닥으로 이동시키는 것입니다(부분 절1로 이동).Math.random()는 0 ~ 0.99를 반환하기 때문에 완전한 상한을 얻을 수 없습니다.따라서 상한에 1을 더하면 최대 99%(상한 + 1)를 얻을 수 있으며, 초과를 제거하기 위해 플로어링합니다.플로어 백분율(차이 + 1)을 얻으면 하위 경계를 추가하여 2개의 숫자 사이에서 원하는 난수를 얻을 수 있습니다.

이에 대한 논리식은 다음과 같습니다.Math.floor(Math.random() * ((up_boundary - low_boundary) + 1)) + 10.

P.s. 최고 등급의 답변 아래에 있는 코멘트조차 틀렸습니다.차이1을 더하는 것을 잊어버렸기 때문입니다.즉, 업 바운더는 결코 얻을 수 없습니다(그렇습니다만, 전혀 취득하고 싶지 않은 경우는, 상한을 포함시키는 것이 요구되었습니다).

많은 답변과 거의 동일한 결과를 얻을 수 있습니다.제 답변을 덧붙이고 작동에 대해 설명하겠습니다.한 줄의 코드를 복사하여 붙여넣는 것보다 그 기능을 이해하는 것이 중요하기 때문입니다.난수를 생성하는 것은 단순한 수학일 뿐이다.

코드:

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));
}

Math.random()는 빠르고 다양한 목적에 적합하지만 암호적으로 안전한 값(안전하지 않음)이 필요한 경우 또는 완전히 균일한 치우침이 없는 분포의 정수가 필요한 경우(다른 응답에 사용되는 곱셈 접근법에 의해 특정 값이 다른 응답보다 약간 더 자주 생성됩니다).

이런 경우에는crypto.getRandomValues()안전한 정수를 생성하고 생성된 값을 대상 범위에 균일하게 매핑할 수 없습니다.이 작업은 더 느리지만 매우 많은 수의 값을 생성하지 않는 한 중요하지 않습니다.

편향된 분포에 대한 우려를 명확히 하기 위해 1과 5 사이의 값을 생성하려고 하지만 1과 16 사이의 값을 생성하는 난수 생성기가 있는 경우를 고려해 보십시오(4비트 값).각 출력 값에 동일한 수의 생성 값을 매핑하고 싶지만 16은 5로 균등하게 나누지 않고 나머지 1이 남습니다.따라서 가능한 생성 값 중 1개를 거부하고 목표 범위에 균일하게 매핑할 수 있는 15개의 작은 값 중 하나를 얻었을 때만 계속 진행해야 합니다.동작은 다음과 같은 유사 코드일 수 있습니다.

Generate a 4-bit integer in the range 1-16.
If we generated  1,  6, or 11 then output 1.
If we generated  2,  7, or 12 then output 2.
If we generated  3,  8, or 13 then output 3.
If we generated  4,  9, or 14 then output 4.
If we generated  5, 10, or 15 then output 5.
If we generated 16 then reject it and try again.

다음 코드는 유사한 논리를 사용하지만 대신 32비트 정수를 생성합니다. 왜냐하면 이 정수는 JavaScript 표준으로 나타낼 수 있는 가장 큰 공통 정수 크기이기 때문입니다.numbertype. (이것에 의해,BigInt를 참조해 주세요).선택한 범위에 관계없이 거부되는 생성된 값의 비율은 항상 0.5보다 작기 때문에 예상되는 거부 수는 항상 1.0보다 작으며 일반적으로 0.0에 가깝기 때문에 루핑에 대해 영원히 걱정할 필요가 없습니다.

const randomInteger = (min, max) => {
  const range = max - min;
  const maxGeneratedValue = 0xFFFFFFFF;
  const possibleResultValues = range + 1;
  const possibleGeneratedValues = maxGeneratedValue + 1;
  const remainder = possibleGeneratedValues % possibleResultValues;
  const maxUnbiased = maxGeneratedValue - remainder;

  if (!Number.isInteger(min) || !Number.isInteger(max) ||
       max > 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))[0];
  } 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)));
// [11, 8, 8, 11, 10, 8, 8, 12, 12, 12, 9, 9]

1-6을 주사위처럼 돌려주는 거죠

return Math.round(Math.random() * 5 + 1);

추가 중float에 기반한 고정 정밀도 버전int@Francisc의 답변 버전:

function randomFloatFromInterval (min, max, fractionDigits) {
  const fractionMultiplier = Math.pow(10, fractionDigits)
  return Math.round(
    (Math.random() * (max - min) + min) * fractionMultiplier,
  ) / fractionMultiplier
}

따라서:

randomFloatFromInterval(1,3,4) // => 2.2679, 1.509, 1.8863, 2.9741, ...

그리고 int 답변은

randomFloatFromInterval(1,3,0) // => 1, 2, 3

이 함수는 최소값과 최대값 사이의 임의의 정수값을 생성할 수 있습니다.

function randomNumber(min, max) {
  if (min > max) {
    let temp = max;
    max = min;
    min = temp;
  }

  if (min <= 0) {
    return Math.floor(Math.random() * (max + Math.abs(min) + 1)) + min;
  } else {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }
}

예:

randomNumber(-2, 3); // can be -2, -1, 0, 1, 2 and 3
randomNumber(-5, -2); // can be -5, -4, -3 and -2
randomNumber(0, 4); // can be 0, 1, 2, 3 and 4
randomNumber(4, 0); // can be 0, 1, 2, 3 and 4

랜덤 함수를 사용하여 재사용할 수 있습니다.

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

이 조작은 유효합니다.

const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min

[a,b] 범위의 암호 스트롱 랜덤 정수(전제:a < b )

let rand= (a,b)=> a+(b-a+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0

console.log( rand(1,6) );

이것은 9년 정도 늦었지만, randojs.com는 이것을 간단한 한 줄거리로 만들고 있다.

rando(1, 6)

이것을 html 문서의 선두에 추가하면 랜덤으로 원하는 것을 쉽게 할 수 있습니다.배열, 랜덤 jquery 요소, 객체의 랜덤 속성 및 필요한 경우 반복을 방지합니다.

<script src="https://randojs.com/1.0.0.js"></script>

사용 방법:

function random(min, max) {
   return Math.round((Math.random() *( Math.abs(max - min))) + min);
}
console.log(random(1, 6));

(1-6) 예시와 같이 시작 번호가 1인 경우 Math.floor() 대신 Math.ceil() 메서드를 사용할 수 있습니다.

Math.ceil(Math.random() * 6)

대신

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

다른 유용한 수학 방법을 잊지 말자.

ES6 디폴트 파라미터를 사용하여 이를 실현하는 새로운 방법을 찾았습니다.이것은 하나의 인수 또는 두 개의 인수를 허용하기 때문에 매우 적합합니다.여기 있습니다.

function random(n, b = 0) {
    return Math.random() * (b-n) + n;
}

이것은 나에게 효과가 있고 Python의 random.randint 표준 라이브러리 함수와 같은 값을 생성합니다.


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

console.log("Random integer: " + randint(-5, 5));

단답:심플한 어레이로 실현 가능.

배열 요소 에서 교대로 사용할 수 있습니다.

솔루션은 값이 연속되지 않더라도 작동합니다.가치don't even have to be a number.

let array = [1, 2, 3, 4, 5, 6];
const randomValue = array[Math.floor(Math.random() * array.length)];

큰 숫자에 대해서요.

var min_num = 900;
var max_num = 1000;
while(true){
    
    let num_random = Math.random()* max_num;
    console.log('input : '+num_random);
    if(num_random >= min_num){
        console.log(Math.floor(num_random));
       break; 
    } else {
        console.log(':::'+Math.floor(num_random));
    }
}

언급URL : https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript

반응형