- 오늘의 학습 키워드
-> 자바로 난수생성
- 공부한 내용 본인의 언어로 정리하기
1. Math.random 개념
개념
자바에서 난수를 만드는 방법은 2가지가 있습니다.
- Random 클래스 사용
- Math.random()
차이점
1. Random 클래스는 int, long, float, double, boolean type의 난수를 얻을 수 있지만 Math.random()은 0.0에서 1사이의 난수를 얻습니다.
2. Random 클래스는 seed를 설정 할 수 있지만 Math.random()은 현재시간으로 seed가 고정되어있습니다.
- seed란 난수를 만드는 알고리즘에 사용되는 값으로 seed가 같으면 같은 난수를 생성합니다.
1. Random 클래스 사용
import java.util.Random;
이 문장을 import 해줍니다.
Random random = new Random();
random 객체를 생성해줍니다.
random.setSeed(System.currentTimeMillis());
만약 시드값 설정을 하고싶으면 시드값 설정을 해주어도됩니다.
random.nextInt(4); // 0 ~ 3 까지의 무작위 int 값 리턴
random.nextInt(10); // 0 ~ 9 까지의 무작위 int 값 리턴
random.nextInt(100); // 0 ~ 99 까지의 무작위 int 값 리턴
random.nextInt(4)+1; // 1 ~ 4 까지의 무작위 int 값 리턴
random.nextInt(4)+100; // 100 ~ 103 까지의 무작위 int 값 리턴
nextInt를 사용하면 무작위 int 값을 반환합니다.
nextInt(n)은 n미만의 랜던 정수를 리턴합니다.
만약 범위를 정해주고싶으면 뒤에 +를 사용하여 원하는 범위로 맞춰줍니다.
random.nextLong() // 무작위 long 값
random.nextFloat() //무작위 float 값
random.nextDouble() //무작위 double 값
random.nextBoolean() // 무작위 boolean 값
random.nextGaussian() //무작위 정규 분포의 난수 값
int, long, float, double, boolean type의 난수도 얻을 수 있습니다.
2. Math.random()
Math.random();
0.0 ~ 1.0 사이의 난수가 1개 발생합니다.
이것을 사용해서 특정 범위 안에 있는 난수를 만들 수 있습니다.
(int)(Math.random()*10); //0 ~ 10 사이
(int)(Math.random()*100); // 0 ~ 100 사이
(int)(Math.random()*10+10)); //10 ~ 20 사이
예제
1. 로또번호 1~45 중의 숫자중 랜덤하게 6개를 중복 없이 얻어내서 콘솔창에 출력
//랜덤한 숫자를 얻어낼 객체
Random ran=new Random();
//랜덤한 숫자를 저장할 객체
Set<Integer> lottoSet=new HashSet<>();
while(true) {
//1 ~ 45 사이의 랜덤한 숫자 얻어내기
int ranNum=ran.nextInt(45)+1;
//얻어낸 숫자를 Set 에 저장하기
lottoSet.add(ranNum);
//만일 lottoSet 의 size 가 6 이면 반복문 탈출
if(lottoSet.size() == 6) {
break;
}
}
Iterator<Integer> it=lottoSet.iterator();
while(it.hasNext()) {
int num=it.next();
System.out.print(num+" ");
}
2. 3개의 문자열이 같은 것이 나오게 하는 게임 만들기
/*
* 1. cherry, apple, banana, melon, 7
* 5개의 문자열 중에서 1개가 랜덤으로 출력되게 해보세요.
*
* 2. 5개의 문자열 중에서 3개가 한줄에 한번에 랜덤으로 출력되게 해보세요.
*
*/
String[] items= {"cherry","apple","banana","melon","7"};
Random random=new Random();
int[] nums=new int[3];
for(int i=0; i<nums.length; i++) {
nums[i]=random.nextInt(5);
}
String result = items[nums[0]]+"|"+items[nums[1]]+"|"+items[nums[2]];
System.out.println(result);
int[] point = {10,20,30,40,1000};
if(nums[0]==nums[1] && nums[0]==nums[2]) {
for(int n=0; n<point.length; n++) {
if(nums[0]==n) {
System.out.println(point[n]+"점 입니다.");
}
}
}else {
System.out.println("0점 입니다.");
}
- 어떤 문제가 있었고, 나는 어떤 시도를 했는지
2. 로또 번호 생성하기
public class Lotto {
public static void main(String[] args) {
// TODO Auto-generated method stub
int lotto[] = new int[6]; // 로또 번호를 입력받을 배열을 선언해준다.
System.out.print("로또 번호 : ");
for(int i = 0; i < lotto.length; i++) {
int num = (int)(Math.random() * 45) + 1; // 1~46까지의 임의의 수를 받는다.
lotto[i] = num;
for(int j = 0; j < i; j++) { // 중복된 번호가 있으면 이전 포문으로 돌아가 다시 시행한다.
if(lotto[i] == lotto[j]) {
i--;
break;
}
}
System.out.print(lotto[i] + " "); // 로또번호를 출력한다.
}
}
}
0~45 라서 +1을 해야함
- 내일 학습할 것은 무엇인지
-> java 알고리즘 개념
'Study > 코딩스터디_TIL' 카테고리의 다른 글
[JAVA 스터디] 250121 해시 알고리즘 (0) | 2025.01.21 |
---|---|
[JAVA 스터디] 250120 hash 함수 (1) | 2025.01.20 |
[JAVA 스터디] 250116 BufferedReader (1) | 2025.01.16 |
[JAVA 스터디] 250115 Scanner (0) | 2025.01.15 |
[JAVA 스터디] 250114 Buffered Reader - 문자열 출력 (1) | 2025.01.15 |