본문 바로가기
혼자서 개발새발

Java로 로또 당첨 번호와 확률 구하기!

by 휴일이 2022. 9. 28.

학원에서 마지막 2시간은 자유 시간을 줘서

내 뒷자리 분이 로또 당첨 만들고 있길래 나도 도전!

 

 

조건)

1부터 45까지의 랜덤한 숫자를 6개 생성

중복되는 수는 없어야 한다

 

 

 

배운 걸 써먹어야지 하고

배열을 써보기로 했다

 

XXX첫 도전이라 틀렸음XXX 작동 안 돼요 XXXX

 

package javaqna;

import java.util.ArrayList;
import java.util.Arrays;

public class Lotto {

	public static void main(String[] args) {
		//1부터 45까지의 숫자중 랜덤으로 6개가 생성되어야 한다
		//중복되는 수는 없어야 한다
		int lotto[] = new int[6];
		int num[] = new int[6];
		int per = 0;
		
		ArrayList<Integer> arrayList = new ArrayList<>();
		
		for(int i=0;i<lotto.length;i++) {
			lotto[i] = (int)(Math.random()*45)+1;
			num[i] = (int)(Math.random()*45)+1;
			
			for(int j=0;j<num.length;j++) { 
				if(arrayList.contains(lotto[i])||arrayList.contains(num[i])) { 
					--i;
					
			}if(!Arrays.equals(lotto, num)) {
				per++;
				lottoRun();
				
			
		} else {
			System.out.println("당첨");
			System.out.print(lotto[i]+" ");
			System.out.print(num[i]+" ");
			System.out.println("당첨 확률"+(double)per*100);
			break;
			
				}
			}
		}
	}
	
		

		



	public static void lottoRun() {
		int lotto[] = new int[6];
		int num[] = new int[6];
		int per = 0;
		
		ArrayList<Integer> arrayList = new ArrayList<>();
		
		for(int i=0;i<lotto.length;i++) {
			lotto[i] = (int)(Math.random()*45)+1;
			num[i] = (int)(Math.random()*45)+1;
			
			for(int j=0;j<num.length;j++) { 
				if(arrayList.contains(lotto[i])||arrayList.contains(num[i])) { 
					--i;
					
			}if(!Arrays.equals(lotto, num)) {
				per++;
				lottoRun();
				
			
		} else {
			System.out.println("당첨");
			System.out.print(lotto[i]+" ");
			System.out.print(num[i]+" ");
			System.out.println("당첨 확률"+(double)per*100);
			break;
			
				}
			}
		}
	}
}

 

XXXX작동 안 됨XXXX

 

배열에 숫자 하나만 같아도 당첨이라고 뜨는 오류가 발생했다

저대로 고치려고 해봤다

 

int[] a = {1,2,3,4,5,6};

int[] b = {6,5,4,3,2,1};

이 둘이 같다는 걸 증명할 수 있을까?

할 수는 있으나

배열끼리 같음을 구하려면 하나하나 자리수에 맞춰 대입해야 한다.

 

예) a[0]을 b[0],[1],[2],[3]...과 하나하나 대입해서

맞으면 ㅇㅋ 틀리면ㄴㄴ 해야함 ㅠㅠ

 

 

 

메소드?객체?를 써보기로 했다(아직 안 배움)

 

열심히 구글링 한 결과

HashSet 이라는 놈을 사용해보기로 했다

HashSet의 특징은

중복된 수는 과감히 버려줌

순서대로 들어가는 게 아니라 차례로 정렬해줌

 

 

숫자가 들어가는 순서는 달라도

숫자만 같으면 OK! 라서

HashSet을 쓰기가 좋을 거 같았다

 

로직도 좀 더 간결하게 바꿨다

 

 

package javaqna;

import java.util.HashSet;

public class Lotto01 {

	public static void main(String[] args) {
		HashSet lotto = new HashSet();
		HashSet num = new HashSet();
		
		long per = 0; //몇 번 돌렸는지 기록하기 위한 변수
		
		while(true) {
			lotto.add((int)(Math.random()*45)+1); //1부터 45까지의 정수를 부여
			num.add((int)(Math.random()*45)+1);
		
			if(lotto.size() ==6) {  //객체에 저장된 수가 6개라면, 발동이 된다
				if(lotto.equals(num)) { //객체 비교해서 둘이 같다면 출력
					System.out.println(num);
					System.out.println(lotto);
					System.out.println("님 이만큼 씀"+per); //1등이 되기까지 몇 번 돌렸나
					System.out.println("당첨입니다!");
					break;
				} else {
					per++; //1번 돌아갈 때마다 수를 세준다
					lotto.clear(); //lotto와 num은 당첨이 안 되면 초기화한다
					num.clear();
			    }
			}	
		}
		
		
	
	}
}

 

HashSet을 사용하면

보다 편리하게 비교가 가능하고

변수를 하나 지정해서

한 번 돌릴 때마다 1씩 증가하게 해주면

1등이 당첨될 때 까지 몇 번 돌아가야 하는지도 알려준다!

 

 

그리고 이 코드를 응용하여

2등, 3등 당첨도 손쉽게 알아낼 수 있다(아주 쉽다)

 

package javaqna;

import java.util.HashSet;

public class Lotto02 {

	public static void main(String[] args) {
		HashSet lotto = new HashSet();
		HashSet num = new HashSet();
		
		long per = 0;
		
		while(true) {
			lotto.add((int)(Math.random()*45)+1);
			num.add((int)(Math.random()*45)+1);
		
			if(lotto.size() ==4) { // 6번 돌리던 걸 4번만 돌려주면 된다
				if(lotto.equals(num)) {
					System.out.println(num);
					System.out.println(lotto);
					System.out.println("님 이만큼 씀"+per);
					System.out.println("3등 당첨입니다!");
					break;
				} else {
					per++;
					lotto.clear();
					num.clear();
			    }
			}	
		}
		//다시 while문을 사용해서 5번 돌아갈 수 있도록 한다
		while(true) {
			lotto.add((int)(Math.random()*45)+1);
			num.add((int)(Math.random()*45)+1);
		
			if(lotto.size() ==5) {
				if(lotto.equals(num)) {
					System.out.println(num);
					System.out.println(lotto);
					System.out.println("님 이만큼 씀"+per);
					System.out.println("2등 당첨입니다!");
					break;
				} else {
					per++;
					lotto.clear();
					num.clear();
			    }
			}	
		}
		//1등 당첨을 마지막으로 종료해주면 된다
		while(true) {
			lotto.add((int)(Math.random()*45)+1);
			num.add((int)(Math.random()*45)+1);
		
			if(lotto.size() ==6) {
				if(lotto.equals(num)) {
					System.out.println(num);
					System.out.println(lotto);
					System.out.println("님 이만큼 씀"+per);
					System.out.println("1등 당첨입니다!");
					break;
				} else {
					per++;
					lotto.clear();
					num.clear();
			    }
			}	
		}
		
		
	
	}
}

 

ㅋㅋ안해...로또 안사..

 

어렵게 생각하면 어렵고

쉽게 생각하면 쉬운 코드였다(휴)

 

 

반복문은 어렵고도 어렵구나...

 

 

728x90