본문 바로가기

카테고리 없음

javascript 난수 생성

기본 원리

 

Math.random()

0~1 사이의 부동소수점 난수를 생성

0~0.9999...사이의 난수 생성

 

0에서 10사이의 난수 생성?

Math.random()*10 

-> 0~9.9999999 난수 생성

-> Math.floor(Math.random() *10)

-> 정수 0~9 사이의 난수 생성

 

응용

범위 지정 난수 생성 방법

min <= number <= max ( max 값 포함, min 값 포함)

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

 

min <= number < max (max 값 불포함, min값 포함)

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

 

main < number <= max (max값 포함, min 값 불포함)

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

 

main <= number < mat (max값 불포함, min 값 불포함)

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

 

ex) 

2에서 50까지의 난수 생성? 

50-2+1 = 49

Math.floor(Math.random() *49) + 2;