본문 바로가기
Project

로또 번호 추출기 3탄(자바)

by DuncanKim 2022. 7. 3.
728x90

로또 번호 추출기 3탄(자바)

 

 

인간의 욕심은 끝이 없고 무한한 성능 향상을 꿈꾼다.

자바의 문법들을 다시 상기하고, 메모리 구조에 대한 것들을 하나씩 배우는 요즘, 공부를 하다가 잠깐 쉬고 싶어서 딴 짓을 하고 싶어졌다.

 

현재 그냥 무난하게 장난 치면서 가지고 놀 수 있는 것은 로또 추출기다...

python에서 루프의 횟수가 1억번인 것을 10억번으로 늘려서 해보기로 했다. '더 빠르지 않을까...?'라는 생각에

 

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

public class Lotto {
    public static void main(String[] args) {
        System.out.println("==금주의 행운의 번호==");
        for (int i = 0; i < 5; i++) {
            int[] randomArray = new int[45];
            int loop = 1000000000;
            int j = 0;
            while (j < loop) {
                int a = (int) (Math.random() * 45);
                randomArray[a] += 1;
                j++;
            }

            // Collection.max()를 쓰기 위해서 배열(randomArray)을 ArrayList(randomList)로 변환.
            ArrayList<Integer> randomList = new ArrayList<>();
            for (Integer temp : randomArray) {
                randomList.add(temp);
            }

            // 추천번호 6개 뽑기 : randomList에서 가장 큰 값을 가지고 있는 인덱스를 찾고
            // 그 인덱스를 recommendArray에 원소로 집어넣고 기존의 randomList에 있는 값은 0으로 바꿈
            // (그 다음 큰 값을 가지고 있는 인덱스를 찾는데 방해가 되지 않게 하기 위해서)
            int[] recommendArray = new int[6];
            for (int k = 0; k < 6; k++) {
                int b = Collections.max(randomList);
                recommendArray[k] = randomList.indexOf(b) + 1;
                randomList.set(randomList.indexOf(b), 0);
            }

            // 번호 오름차순 정렬 후 출력
            Arrays.sort(recommendArray);
            for (int l = 0; l < 6; l++) {
                if (l == 0) {
                    System.out.printf("[%d, ", recommendArray[l]);
                    continue;
                }else if (l == 5) {
                    System.out.printf("%d]\n", recommendArray[l]);
                    continue;
                }
                System.out.printf("%d, ", recommendArray[l]);
            }
        }
    }
}

 

==금주의 행운의 번호==
[2, 17, 26, 29, 33, 39]
[12, 16, 19, 33, 34, 41]
[1, 5, 6, 7, 13, 33]
[11, 13, 19, 21, 34, 41]
[1, 4, 10, 30, 31, 37]

 

파이썬 루프 1억회를 돌린 것과 비슷하게 시간이 나온다.

자바가 설계만 잘해준다면 훨씬 빠르다는 것을 알 수 있다.

728x90

댓글