자바 math.random 정수 - jaba math.random jeongsu

랜덤 숫자 (난수 중에서 정수)를 만드는 방법은 크게 두 가지가 있다. 


1. Random 객체 이용하기

// 랜덤숫자 만들기 - random 객체, setseed 함수 이용
// 범위  : 1 ~ 100
Random randomNum1 = new Random();
randomNum1.setSeed(System.currentTimeMillis());
System.out.print(randomNum1.nextInt(100) + 1);

2. Math.random 함수 이용하기 

// 랜덤숫자 만들기 - Math.random() 함수 이용
// 범위 : 1 ~ 100
int randomNum2 = (int)(Math.random() * 99 ) + 1;
System.out.println(randomNum2);
  • 실제로는 2번 방법을 주로 사용 했었는데, 1번 방법도 알게 되었음. 
  • 잘 외워둬야지. 

1. 1부터 10 사이의 임의의 수

Math 클래스의 random() 을 사용하여 1과 10 사이의 임의의 수를 구하는 코드는 다음과 같다.

int score = (int)(Math.random() * 10)+1;

cs

이제 위의 코드를 조금 더 풀어서 설명해보도록 하겠다.

우선 Math 클래스의 random() 함수는 0.0과 1.0 사이의 범위에 속하는 하나의 double 값을 반환한다.

0.0 <= Math.random() < 1.0

여기에 10을 각각 곱하면 다음과 같다.

0.0 * 10 <= Math.random() * 10 < 1.0 * 10

0.0 <= Math.random() * 10 < 10.0

이것을 int형으로 변환시켜주면 다음과 같다.

0 <= (int)(Math.random() * 10) < 10

여기에 1을 더해주면 다음과 같다.

1 이상 11 미만이므로 정수로 1과 10 사이의 정수가 출력된다.

0+1 <= (int)(Math.random() * 10)+1 < 10+1

1 <= (int)(Math.random() * 10)+1 < 11

2. 임의의 주사위 수

위의 코드를 이용하여 임의의 주사위 숫자를 구하는 것도 다음과 같이 할 수 있다.

주사위는 1부터 6까지의 수이므로 다음과 같은 코드로 구현이 가능하다.

int player = (int)(Math.random() * 6)+1;

cs

3. 임의의 문자

임의의 문자가 ascii 코드 상에서 연속적으로 존재한다는 특징을 이용한 것이다.

만약 영문의 대문자 중 한 문자를 얻고자 한다면 다음과 같은 코드로 구현할 수 있다.

char Upper = (char)(Math.random()*26+65);

cs

간단하게 설명하자면 영문자가 총 26개이므로 26을 곱해준 것이고 대문자 ascii 코드가 65부터 시작하기 때문에 65를 더해준다.

여기서 위와 다른 점은 char형으로 형변환하기 전에 +65를 해주었다는 점이다.

만약 위와 같이 (char)(Math.random()*26)+65; 를 하였다면 +65를 할 때 int형으로 변환되므로 에러가 발생된다.

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

Min + (int)(Math.random() * ((Max - Min) + 1))

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

Min + (Math.random() * (Max - Min))

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

5 + (Math.random() * (10 - 5))

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

Min + (int)(Math.random() * ((Max - Min) + 1))

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))