'LinkedList'에 해당되는 글 1건

  1. 2013.03.27 HashSet 를 이용한 로또번호 만들기
2013. 3. 27. 14:09

자바에서 Set 쓰는 이유는 LinkedList는 입력값에 순서가 있지만, 

순서없이 그냥 값만 입력하고 그것만 체크하면 더 빠르게 체크하고 그 값만 인식할수있다.


import java.util.*;


public class Lottery {

    public static final int pickNum = 6;

    public static final int maxNum = 40;


    public static void main(String[] args) {

   

        Set<Integer> winningNumbers = generateWinningNumbers();

        //System.out.println("Test Winning Num " +  winningNumbers);

        Set<Integer> ticket = getTicket();

        System.out.println();


        Set<Integer> checkNum = new TreeSet<Integer>(ticket);

        checkNum.retainAll(winningNumbers);

        

 

        System.out.println("Your numbers are " + ticket);

        System.out.println("The winning numbers are " +  winningNumbers);

        

        if (checkNum.size() > 0) {

        System.out.println("You had " + checkNum.size() + " matching numbers.");

            int prize = 250*checkNum.size();

            System.out.println("The matched numbers are " + checkNum);

            System.out.println("Your prize is $" + prize);

        }else {

        System.out.println("Sorry, You lost. There are no matching numbers.");

        }

    }

    

    // make Winning Number.

    public static Set<Integer> generateWinningNumbers() {

        Set<Integer> winningNumbers = new TreeSet<Integer>();

        Random r = new Random();

        while (winningNumbers.size() < pickNum) {

            int number = r.nextInt(maxNum) + 1;

            winningNumbers.add(number);

        }

        return winningNumbers;

    }

    

    // get player Numbers.

    public static Set<Integer> getTicket() {

        Set<Integer> ticket = new TreeSet<Integer>();

        Scanner console = new Scanner(System.in);

        System.out.println("  ***** Play Lotto ***** ");

        System.out.print("Please Enter 6 lotto numbers between 1 and 40 : ");

        while (ticket.size() < pickNum) {

            int number = console.nextInt();

            ticket.add(number);

        }

        return ticket;

    }

}


/* OutPut

 ***** Play Lotto ***** 

Please Enter 6 lotto numbers between 1 and 40 : 1 2 3 4 5 6


Your numbers are [1, 2, 3, 4, 5, 6]

The winning numbers are [11, 13, 14, 15, 38, 39]

Sorry, You lost. There are no matching numbers.

-------------------------------------------------

Test Winning Num [4, 15, 18, 29, 34, 35]

  ***** Play Lotto ***** 

Please Enter 6 lotto numbers between 1 and 40 : 4 15 18 29 30 31


Your numbers are [4, 15, 18, 29, 30, 31]

The winning numbers are [4, 15, 18, 29, 34, 35]

You had 4 matching numbers.

The matched numbers are [4, 15, 18, 29]

Your prize is $1000


*/


'컴퓨터 > Java' 카테고리의 다른 글

jstl에서 따옴표 처리 (문자열 이스케이프 처리)  (0) 2018.05.24
Posted by Tyson