공지: 기존 사이트는 old.codingdojang.com에서 확인할 수 있으며, 2026년 8월 3일 종료됩니다.
이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

로또(lotto) 를 만들어보자!

난이도:(보통)

현우의 여동생은 로또에당첨되서 부자가된사람들에관한 기사를읽엇다.

그러고는 말하였다.

-오빠.. 나도 로또사줘로또!

하지만 현우는 아직 청소년이여서 로또를구매할수없었다.

어쩔수없이 현우는 동생을위해 로또 프로그램을만들어 동생에게주기로했다.

이걸로 동생이 만족할진모르겠지만...우리의 딱한현우를위해 좀만도와주자...

문제!

렌덤으로 1부터 45 까지의 무작위로섞인 6개의숫자와1개의보너스숫자를 당첨번호를생성해저장한뒤

로또를 몇개살지 입력받고 입력된번호의수 에따라 렌덤으로뽑힌 번호를 당첨번호와비교!

한뒤 당첨이되면 당첨된 번호와 축하의말을 출력 해주자

예시 : 로또를 몇개 구매하시겠습니까? : 5

 현재 당첨번호는 43,2,35,16,4,6 보너스번호는 11 입니다.

 구매하신 추첨번호는 43,2,41,18,19,21 보너스번호는 8입니다.

 구매하신 추첨번호는 28,20,1,4,32,5 보너스번호는 8입니다

 구매하신 추첨번호.... 11,4,35,2,43,16 보너스번호 6 ..1등이다!! 아싸 오늘저녁은 치킨이닭!!

 break

(난이도 up.ver :

            위에 대한코드를 만들어도 현우의운으로는 당첨될확률이 거의없다고봐도될수준..

            하지만 1등은못하더라도 2 3 등은할수있지않을까?

            7가지의 숫자가다 맞으면 1등

            6가지의 숫자가 맞으면 2등

            5가지 숫자가 맞으면 3등

            4가지는 4등 5등...(3등까지만만들자 귀찮으니..)

            을 출력해라!

2018/07/21 23:09

leak

아..구매할땐 보너스번호를안적는군요.........몰랐습니다.. - leak, 2018/07/22 20:52

26개의 풀이가 있습니다.

from random import *
import time, os

class lotto:
    cnt = 0
    def __init__(self):
        lotto.cnt += 1
        self.mylotto = []
        for i in range(int(input('로또를 몇개 구매하시겠습니까?: '))):
            self.mylotto.append(self.__lotto_pop()[:6])
        print('\n- {}회 차 로또 구매 내역 -'.format(lotto.cnt))
        for i in self.mylotto:
            print('\t{:2} {:2} {:2} {:2} {:2} {:2}'.format(*i))
        print()

    def lucky(self):
        self.lucky_number = self.__lotto_pop()
        print('- {}회 차 로또 당첨 번호 -'.format(lotto.cnt))
        print('\t{:2} {:2} {:2} {:2} {:2} {:2}, 보너스 번호: {:2}'.format(*self.lucky_number[:6],self.lucky_number[-1]))
        self.__match_lucky()

    def __match_lucky(self):
        print('\n- {}회 차 로또 당첨 확인 -'.format(lotto.cnt))
        self.rank = [0,0,0,0,0]

        for i in self.mylotto:
            num_match = len(set(i)&set(self.lucky_number[:6]))

            if num_match == 6:
                print('\t{:2} {:2} {:2} {:2} {:2} {:2}'.format(*i[:6]),end=' >>> ')
                print('1등 당첨 축하드립니다. 일생의 운을 다 쓰셨습니다.')
                self.rank[0] += 1
            elif num_match == 5 and self.lucky_number[-1] in i:
                print('\t{:2} {:2} {:2} {:2} {:2} {:2}'.format(*i[:6]),end=' >>> ')
                print('2등 당첨 축하드립니다. 콩라인에 오신걸 환영합니다.')
                self.rank[1] += 1
            elif num_match >= 3:
                print('\t{:2} {:2} {:2} {:2} {:2} {:2}'.format(*i[:6]),end=' >>> ')
                print('{}등 당첨 축하드립니다.'.format(8 - num_match))
                self.rank[8-num_match-1] += 1
        print()
        if self.rank == [0]*5: print('\t모두 꽝입니다. 호갱님')
        for i in range(5):
            if self.rank[i] != 0: print('\t{}등 당첨: {}개'.format(i+1,self.rank[i]))

    @staticmethod
    def __lotto_pop():
        return sample(range(1,46),7)

if __name__ == '__main__':
    while 1:
        os.system('cls')

        buy_lotto = lotto()
        for i in reversed(range(3)):
            print('.'*(i+1),'{}'.format(i+1))
            time.sleep(1)
        print()
        buy_lotto.lucky()
        if input('\n계속하시겠습니까? y/n: ') == 'n': break

로또를 몇개 구매하시겠습니까?: 10

- 6회 차 로또 구매 내역 -
        21 42 43  7 31 34
        35 45 41  5 17 27
        22  4 36 37 34  5
        31 33  1  3 34  9
         6 12 23  8 31 34
        41 31  1  8 32 37
         8  9 15 22 17 14
        22 27 10  5  7 41
         4 40 45 31 13 30
        16 15 10  7  3  1

... 3
.. 2
. 1

- 6회 차 로또 당첨 번호 -
        34 21 23 43 18 12, 보너스 번호: 25

- 6회 차 로또 당첨 확인 -
        21 42 43  7 31 34 >>> 5등 당첨 축하드립니다.
         6 12 23  8 31 34 >>> 5등 당첨 축하드립니다.

        5등 당첨: 2개

문제의 로또 시스템이 아니라
실제 로또 등수 시스템으로 만들었습니다

5등 당첨도 힘드네요;;

2018/07/22 17:39

Creator

와 이걸구현 하시넹 - leak, 2018/07/22 18:36
총100만개구매했는데 하나도당첨이안되네요 2등하나에 3등19개... - leak, 2018/07/22 20:40
800만개 사서 1등 하나 당첨 됐습니다 ㅎㅎ...그 와중에 2등은 없더군요;; - Creator, 2018/07/23 21:23
format(*i[:6]) --> 이부분이 어떤 의미인가요? *i 특히 이부분이 무슨 의미인가요? 곱하기도 아니고 와일드 카드인가요? - Shin gil sang, 2018/09/19 16:32
i[:6] 리스트의 원소를 언패킹 합니다 format(*i[:6]) ====> format(i[0], i[1], ... , i[5]) - Creator, 2018/09/19 17:40

파이썬의 random의 pop 기능을 사용해서 중복되지 않는 7개의 숫자를 추첨했고, set을 사용한 집합연산을 통해 중복되는 요소가 어떤 것이 있는지 확인했습니다.


import random

def random_pick(n=7):
    b = []
    for i in range(n):
        a = list(range(1,46))
        random.shuffle(a)
        b.append(a.pop())
    return b

n = input("로또를 몇 개 구매하시겠습니까? : ")
right = random_pick()
print("현재 담첨번호는 {} 보너스번호는 {}입니다.".format(sorted(right[:-1]), right[-1]))
right = set(right)

for i in range(int(n)):
    a1 = random_pick()
    print("구매하신 추첨번호는 {} 보너스번호는 {}입니다.".format(sorted(a1[:-1]), a1[-1]))
    a2 = 8 - len(set(a1) & right)
    if a2 < 4:
        print("{}등이다!".format(a2))


2018/07/23 10:22

재즐보프

python 3.6.5

import random as rd

c=[i for i in range(1,46)]
rd.shuffle(c)
loto=[]
for i in range(7):loto.append(c.pop(i))
yy='현재 당첨번호는 {}입니다.보나스번호는 {}입니다.'.format(loto[0:6],loto[6])
print(yy)
loto.sort()
i=int(input('렌럼 로또번호추출 :'))
while i>0:
    a=[i for i in range(1,46)]
    rd.shuffle(a)
    loto_3=[]
    for j in range(7):loto_3.append(a.pop(j))
    print('추첨번호는 {} 이고 보너스번호는 {} 입니다.'.format(loto_3[0:6],loto_3[6]))
    i-=1
    loto_3.sort()
    if loto == loto_3:
        print('헐 설마? 헉 당첨 이다!!! 당첨번호는 ',loto_3)
        break
print(yy)

요즘변수명을 막짓는거같네요;; 이런습관안좋은데...

2018/07/21 23:11

leak

import random as rd

buy_num = int(input("How many lotto? : "))

bingo = [ rd.randint(1,45) for _ in range(7) ]

l = []
for x in range(buy_num):
    l.append( [ rd.randint(1,45) for _ in range(7) ] )

for i in range(len(l)):
    if bingo == l[i]:
         print("{} : Bingo. {} : {}".format(i+1, bingo[:6], bingo[-1]) )
         break
    else:
         print("{} : Sorry. {} : {}".format(i+1, l[i][:6], l[i][-1]) )

2018/07/22 18:39

구름과비

from random import *

n = int(input("로또를 몇개 구매하시겠습니까?"))

def Lotto(n):
     ans = []
     lotto = list(map(lambda x : str(x) , list(range(1,47))))
     shuffle(lotto)
     for x in range(n):
          ans.append(input('\n번호를 입력하시오').split())
     print('현재 당첨번호는 %s 이며 보너스 번호는 %s 입니다.' %(','.join(lotto[0:6]),lotto[6]))
     for x in range(n):
          print('구매하신 추첨번호는 %s 이며 보너스 번호는 %s 입니다.' %(','.join(ans[x]),randint(1,47)))
          s = same(ans[x*6-6:x*6+1],lotto[0:6])
          if s == 7:
               print('1등!!!! 당첨금 %s억을 받으셨습니다.\n' %(randint(500,1000)))
          elif s == 6:
               print('2등!!! 당첨금 %s억을 받으셨습니다.\n' %(randint(100,500)))
          elif s == 5:
               print('3등!! 당첨금 %s억을 받으셨습니다.\n' %(randint(50,100)))
          elif s == 4:
               print('4등! 당첨금 %s억을 받으셨습니다.\n' %(randint(1,50)))
          else:
               print('다음기회에...')

def same(a,b):
     ans = 0
     for x in a:
          if x in b:
               ans += 1
     return ans
Lotto(n)

약간의 상상력을 넣어보았습니다.

2018/07/22 22:09

김영성

1등이 나와본적이 없네요 ㅠ

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        ArrayList<Byte> lotto = ranNum();
        ArrayList<Boolean> result = new ArrayList<>();
        Scanner scn = new Scanner(System.in);

        try {
            System.out.println("몇 장 사시겠습니까? : ");
            byte temp = scn.nextByte();

            //10장제한 딱히 없어도 됨
            if(temp > 10){
                System.out.println("복권은 1인당 1회 10장까지입니다.");
                return;
            }

            ArrayList<Byte> yourNum[] = new ArrayList[temp];

            System.out.println("로또 당첨번호는  " + lotto.get(0) + ", " + lotto.get(1) + ", " + lotto.get(2) + ", " + 
                                            lotto.get(3) + ", " + lotto.get(4) + ", " + lotto.get(5) + " 보너스 번호는 " + 
                                            lotto.get(6) + "입니다.\r\n");

            for (int i = 0; i < temp; i++) {
                yourNum[i] = ranNum();
                System.out.println("구매하신 추첨번호는 " + yourNum[i].get(0) + ", " + yourNum[i].get(1) + ", "
                        + yourNum[i].get(2) + ", " + yourNum[i].get(3) + ", " + yourNum[i].get(4) + ", "
                        + yourNum[i].get(5) + " 보너스 번호는 " + yourNum[i].get(6) + "입니다.");
            }

            System.out.println("");

            for(int i = 0; i < yourNum.length; i++){
                result = check(lotto, yourNum[i]);
                switch (result.size()) {
                case 3:
                    System.out.println("5등 당첨!");
                    break;
                case 4:
                    System.out.println("4등 당첨!");
                    break;
                case 5:
                    System.out.println("3등 당첨!");
                    break;
                case 6:
                    System.out.println("2등 당첨!");
                    break;
                case 7:
                    System.out.println("1등 당첨!");
                    break;
                default:
                    System.out.println("5등미만이네요...");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("ERR");
        }
    }

    private static ArrayList<Byte> ranNum() {
        ArrayList<Byte> result = new ArrayList<>();
        ;
        Random ran = new Random();

        for (int i = 0; i < 7; i++) {
            result.add((byte) (ran.nextInt(44) + 1));
            for (int j = 0; j < result.size() - 1; j++) {
                if (result.get(j) == 0 || result.get(i) == result.get(j)) {
                    result.set(i, (byte) (ran.nextInt(44) + 1));
                    j = 0;
                }
            }
        }

        return result;
    }

    private static ArrayList<Boolean> check(ArrayList<Byte> lotto, ArrayList<Byte> num){
        ArrayList<Boolean> result = new ArrayList<>();

        for(int i = 0; i < num.size(); i++){
            for(int j = 0; j < lotto.size(); j++){
                if(num.get(i) == lotto.get(j)){
                    result.add(true);
                }
            }
        }

        return result;
    }
}


2018/07/23 14:44

PuTa

public class practice {

    static int n, cnt;
    static Set<Integer> rotto = new HashSet<>();
    static List<Integer> rottos = new ArrayList<>();
    static Set<Integer> user = new HashSet<>();
    static boolean flag = true;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(rotto.size() <= 7) {
            int num = (int)(Math.random() *45+1);
            rotto.add(num);
        }
        Integer[] nums = rotto.toArray(new Integer[0]);
        rottos.addAll(rotto);
        System.out.println("로또를 몇 개 구입하시겠습니까? \n");
        n = sc.nextInt();




        for (int i=0; i<n; i++) {

            cnt = 0;
            for (int j=0; j<6; j++) {
                int num = sc.nextInt();
                user.add(num);
                if (rottos.contains(num))
                    cnt++;
            }

            while (user.size()<=7) { // 보너스 번호 추가
                int num = (int)(Math.random() *45+1);
                user.add(num);
                if (rottos.contains(num))
                    cnt++;
            }

            if (flag) {
                System.out.print("현재 당첨번호는 ");
                for (int j=0; j<6; j++)
                    System.out.print(j != 5 ? nums[j] + "," : nums[j]);
                System.out.print(" 보너스 번호는 " + nums[6] + "입니다 \n");
            }
            flag = false;


            Integer[] numbers = user.toArray(new Integer[0]);
            System.out.print("구매하신 추첨번호는 ");
            for (int j=0; j<6; j++)
                System.out.print(j != 5 ? numbers[j] + "," : numbers[j]);
            System.out.print(" 보너스 번호는 " + numbers[6] + "입니다");
            System.out.println("cnt : " + cnt);
            switch(cnt){
            case 7: System.out.println("1등"); break;
            case 6: System.out.println("2등"); break;
            case 5: System.out.println("3등"); break;
            case 4: System.out.println("4등"); break;
            case 3: System.out.println("5등"); break;
            }

        }

        sc.close();
    }


}

2018/07/23 15:40

정몽준

Python

def gen():
    nums = list(range(1, 46))
    shuffle(nums)
    return nums[:7]

def comp(winnum, mynum):
    return len(set(winnum) - set(mynum)) + 1

winnum = gen()
print("현재 당첨번호는", winnum[:-1], "보너스 번호는", winnum[-1], "입니다.")

n_lotto = int(input('구매할 로또 개수: '))
for i in range(n_lotto):
    mynum = gen()
    result = comp(winnum, mynum)
    print("구매하신 추첨번호는", mynum[:-1], "보너스 번호는", mynum[-1], "입니다.", end=" ")
    print(str(result) + " 등 당첨!" if result <= 3 else "")

zip, count 썼다가 컨닝해서 set으로 수정.

2018/07/25 19:10

Noname

import random
buy = int(input("로또 몇장을 구매하시겠습니까? : "))



def pick_number():
    lotto_list = []
    x = random.randint(1,46)
    lotto_list.append(x)
    i = 0

    while (i < 6):
        j  = random.randint(1,46)
        if j not in lotto_list:
            lotto_list.append(j)
            i += 1
    return lotto_list

lotto_number = pick_number()
print("현재 당첨번호는 {},{},{},{},{},{} 보너스 번호는 {} 입니다".format(lotto_number[0],
     lotto_number[1],lotto_number[2],lotto_number[3],lotto_number[4],lotto_number[5],lotto_number[6]))

for i in range(buy):
    mynumber = pick_number()
    print("구매하신 추첨번호는  {},{},{},{},{},{} 입니다".format(mynumber[0],
    mynumber[1],mynumber[2],mynumber[3],mynumber[4],mynumber[5]))

2018/07/25 22:08

keunji yoo

import numpy as np

T = int(input("로또를 몇개 구매하시겠습니까? :"))
dangchum = np.random.random_integers(1, 46, 6)
print("현재 당첨번호는"+",".join([str(x) for x in dangchum[:5].tolist()]) + " 보너스번호는 %d 입니다." % dangchum[5])
d = sorted(dangchum.tolist())
w1, w2, w3 = 0, 0, 0
for i in range(T):
    cur = np.random.random_integers(1, 46, 6)
    print("구매하신 추첨번호는 "+",".join([str(x) for x in cur[:5].tolist()])+" 보너스번호는 %d입니다." % cur[5])
    count = 0
    c = sorted(cur.tolist())
    for _ in c :
        if _ in d :count += 1
    if count == 6 :
        print("1등")
        w1 += 1
    elif count == 5:
        print("2등")
        w2 += 2
    elif count == 4 :
        print("3등")
        w3 += 3
print("총 %d 시도해서 1등 %d번, 2등 %d번, 3등 %d번 했습니다." % (T, w1, w2, w3))

2018/07/26 16:05

Sukeoul Jang

#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

void LottoWorld()
{
    cout << "*****************************************************************" <<endl;
    cout << "**************************로또 추첨기****************************" <<endl;
    cout << "*****************************************************************" << endl;
    cout << endl;
    cout << "******************로또 추천 번호를 입력하시오********************" << endl;

}

int Numver_Compare(int a[], int b[], int size)
{
    int count = 0;

    for (int i = 0; i < size; i++)
    {
        for (int j = 0; j < size; j++)
        {
            if (a[i] == b[j])
                count++;
        }
    }

    if (count >= 5)
        return true;
    else
        return false;
}
void Result(bool flag,int Lotto_Number[],int My_Number[])
{

    if (flag)
    {
        int count = 0;

        cout << "현재 당첨번호는 ";
        for (int i = 0; i < 6; i++)
            cout << Lotto_Number[i] << ',';
        cout << " 보너스 번호는 " << Lotto_Number[6] << " 입니다." << endl << endl;

        cout << "구매하신 추첨번호는 ";
        for (int i = 0; i < 6; i++)
            cout << My_Number[i] << ',';
        cout << " 보너스 번호는 " << My_Number[6] << " 입니다.." << endl;
        for (int i = 0; i < 7; i++)
        {
            for (int j = 0; j < 7; j++)
            {
                if (Lotto_Number[i] == My_Number[j])
                    count++;
            }
        }
        cout << 7 - count + 1 <<"등 입니다." << endl;
    }
    else
    {
        cout << "현재 당첨번호는 ";
        for (int i = 0; i < 6; i++)
            cout << Lotto_Number[i] << ',';
        cout << " 보너스 번호는 " << Lotto_Number[6] << " 입니다." << endl << endl;

        cout << "구매하신 추첨번호는 ";
        for (int i = 0; i < 6; i++)
            cout << My_Number[i] << ',';
        cout << " 보너스 번호는 " << My_Number[6] << " 입니다.... 다음기회를.... " << endl;
    }
}

int *Lotto()
{
    static int Lotto_Number[7];

    srand((unsigned int)time(0));

    for (int i = 0; i < 7; i++)
        Lotto_Number[i] = rand() % 45 + 1;

    return Lotto_Number;
}


int main()
{
    int My_Number[7];

    LottoWorld();

    for (int i = 0; i < 7; i++)
    {
        cout << " " << i + 1 << " 번째 번호>> ";
        cin >> My_Number[i];
    }

    Result(Numver_Compare(Lotto(), My_Number,7), Lotto(), My_Number);

}

2018/07/26 17:12

Jun ki Kim

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Lotto
{
    class Program
    {
        static int[] LottoNumber = new int[5];
        static int[] LotOkNumber = new int[6];
        static int bonusNumber = 0;

        static void Main(string[] args)
        {
            int nCnt = int.Parse(Console.ReadLine());
            Lotto(nCnt);
        }

        static void Lotto(int nCnt)
        {
            for (int k = 0; k < nCnt + 1; k++)
            {
                Random ran = new Random();

                for (int i = 0; i < LottoNumber.Length; i++)
                {
                    int LottoBall = ran.Next(1, 46);

                    if (isNonexist(i, LottoBall))
                    {
                        LottoNumber[i] = LottoBall;

                        if (k == 0)
                        {
                            LotOkNumber[i] = LottoBall;
                        }
                    }
                    else
                    {
                        i--;
                    }
                }
                Thread.Sleep(50);

                string Lotto = string.Empty;

                var Sort = from n in LottoNumber orderby n select n;

                foreach (int Lottoval in Sort)
                {
                    Lotto += Lottoval + " ";
                }

                for (int i = 0; i < 1; i++)
                {
                    int bonusBall = ran.Next(1, 46);

                    if (isNonexist(LottoNumber.Length, bonusBall))
                    {
                        bonusNumber = bonusBall;

                        if (k == 0)
                            LotOkNumber[5] = bonusBall;
                    }
                    else
                    {
                        i--;
                    }
                }

                string Ment = string.Empty;
                if (k == 0)
                {
                    Ment = String.Format("현재 당첨번호는 {0}이며, 보너스 번호는 {1}입니다.\n", Lotto, bonusNumber);
                    Console.WriteLine(Ment);
                }
                else
                {
                    Ment = String.Format("구매한 추첨번호는 {0}이며, 보너스 번호는 {1}입니다.", Lotto, bonusNumber);
                    Console.WriteLine(Ment);
                    LottoCompare(LottoNumber, bonusNumber);
                }
            }
        }

        static bool isNonexist(int IndexSize, int LottoValue)
        {
            for (int i = 0; i < IndexSize; i++)
            {
                if (LottoNumber[i] == LottoValue)
                {
                    return false;
                }
            }
            return true;
        }

        static void LottoCompare(int[] LottoNumber, int bonusNumber)
        {
            int cnt = 0;

            for (int i = 0; i < LotOkNumber.Length; i++)
            {
                for (int j = 0; j < LottoNumber.Length; j++)
                {
                    if (LotOkNumber[i] == LottoNumber[j])
                        cnt++;

                    if (j == LottoNumber.Length - 1)
                        if (LotOkNumber[i] == bonusNumber)
                            cnt++;
                }
            }
            switch (cnt)
            {
                case 7: Console.WriteLine("1등이다!! 아싸 오늘저녁은 치킨이닭!!"); break;
                case 6: Console.WriteLine("2등이다!!"); break;
                case 5: Console.WriteLine("3등이다!!"); break;
                case 4: Console.WriteLine("4등이다!!"); break;
                case 3: Console.WriteLine("5등이다!!"); break;
                case 2: Console.WriteLine("6등이다!!"); break;
            }
        }
    }
}

2018/07/27 01:24

정태식

function lottoBuy(n){
    var lottoWinNumArray = []; //당첨 번호 생성할 array
    var lottoWinNumIndex = 0; //당첨 번호 배열 순서
    var lottoWinNum = ""; //로또번호 생성 숫자
    while(lottoWinNumArray.length < 7){
        lottoWinNum = Math.floor(Math.random()*(45)) + 1; //1~45 숫자 랜덤 생성
        if(lottoWinNumArray.indexOf(lottoWinNum) == -1){ //당첨 번호에 없으면 당첨 번호 추가
            lottoWinNumArray[lottoWinNumIndex] = lottoWinNum;
            lottoWinNumIndex++;
        }
    }
    console.log("1등 로또 번호는 " + lottoWinNumArray[0] +","+lottoWinNumArray[1] +","+lottoWinNumArray[2] +","+lottoWinNumArray[3] +","+lottoWinNumArray[4] +","+lottoWinNumArray[5]+" 보너스 번호는 " +lottoWinNumArray[6] +" 입니다.");

    var lottoBuyNumArray = []; //구매 번호 생성할 array
    var lottoBuyNumIndex = 0; //구매 번호 배열 순서
    var lottoBuyNum = ""; //로또번호 생성 숫자
    var pickCnt = 0; //당첨 개수
    var bonusFlag = false;
    for(var i =0; i < n; i++){ //구매한 개수만큼 반복
        while(lottoBuyNumArray.length < 6){
            lottoBuyNum = Math.floor(Math.random()*(45)) + 1; //1~45 숫자 랜덤 생성
            if(lottoBuyNumArray.indexOf(lottoBuyNum) == -1){ //구매 번호에 없으면 구매 번호 추가
                lottoBuyNumArray[lottoBuyNumIndex] = lottoBuyNum;
                lottoBuyNumIndex++;
            }
        }
        console.log("구매하신 로또 번호는 " + lottoBuyNumArray[0] +","+lottoBuyNumArray[1] +","+lottoBuyNumArray[2] +","+lottoBuyNumArray[3] +","+lottoBuyNumArray[4] +"," +lottoBuyNumArray[5] +" 입니다.");
        //당첨값과 비교
        for(var j=0; j < 7; j++){
            for(var k=0; k <6; k++){
                if(lottoWinNumArray[j] == lottoBuyNumArray[k]){
                    if(j == 6){
                        bonusFlag = true;
                    }
                    else{
                        pickCnt++;
                    }
                }
            }
        }
        console.log("동일 개수 ::" + pickCnt +" :: 보너스 체크 ::" +  bonusFlag);

        if(pickCnt == 6){
            console.log("1등입니다");
        }
        else if(pickCnt == 5){
            if(bonusFlag){
                console.log("2등입니다");
            }
            else{
                console.log("3등입니다");
            }
        }
        else if(pickCnt == 4){
            console.log("4등입니다");
        }
        else{
            console.log("꽝 다음 기회에");
        }
    }
}

console.log(lottoBuy(6));

2018/08/09 15:43

쪼렙

import random
import time


class lotto:
    def __init__(self):
        self.numbers = random.sample(range(1, 46), 6)
        self.match_count = 0
        self.rank = None


if __name__ == "__main__":
    temp = random.sample(range(1, 46), 7)
    won_number = {"numbers": temp[0:6], "bonus_number": temp[6]}

    lotto_count = int(input("로또를 몇개 구매하시겠습니까? : "))
    rank_num = int(input("몇등 짜리 번호? : "))
    start_time = time.time()
    win_person = 0
    numbers_list = [lotto() for i in range(lotto_count)]

    for obj in numbers_list:
        for number in obj.numbers:
            if number in won_number["numbers"]:
                obj.match_count += 1

        if obj.match_count == 3:
            obj.rank = 5
        elif obj.match_count == 4:
            obj.rank = 4
        elif obj.match_count == 5:
            for number in obj.numbers:
                if number is won_number["bonus_number"]:
                    obj.match_count += 1
                    obj.rank = 2
                else:
                    obj.rank = 3
        elif obj.match_count == 6:
            obj.rank = 1
        else:
            obj.rank = None

    print("당첨 번호: ", won_number["numbers"], "+", won_number["bonus_number"])
    print("\n===========추첨 번호===========\n")
    for obj in numbers_list:
        if obj.rank is rank_num:
            print(obj.numbers)
            print("일치 갯수: ", obj.match_count)
            print("Rank: ", obj.rank, "\n")
            win_person += 1
    print("당첨자 수 : ", win_person)
    print("--- %.2f seconds ---" % (time.time() - start_time))
로또를 몇개 구매하시겠습니까? : 10000000
몇등 짜리 번호? : 1
당첨 번호:  [16, 39, 3, 12, 21, 15] + 17

===========추첨 번호===========

[39, 3, 16, 12, 21, 15]
일치 갯수:  6
Rank:  1

[15, 3, 12, 16, 21, 39]
일치 갯수:  6
Rank:  1

당첨자 수 :  2
--- 126.68 seconds ---

실제 로또 추첨방식을 기준으로 구현 해봤습니다.

2018/11/27 03:17

GyuHo Han

#Lotto
import random
n=int(input('Lotto 구매량: '))

#당첨번호
ls=[]
for i in range(0,7):
    ls.append(random.randrange(1,46))
#중복제거
for j in range(1,7):
    if ls[j] in ls[0:j]:
        del(ls[j])
        ls.insert(j,random.randrange(1,46))

#추첨번호
for j  in range(1,n+1):
    count=0
    k=0
    while k<7:
        print(k+1,'번째\t')
        m=int(input('번호입력: '))
        if m>45 or m<=0: 
            print('1~45까지의 수 입력')
            k+=0
        else:
            #당첨번호와 일치한 경우
            if m==ls[k]:
                count+=1
            k+=1
    #결과발표    
    if count==7:
        print('1등 당첨을 축하한다')
    else:
        print('결과: ',8-count,'등')
print('현재 당첨번호: ',ls[0:6],'보너스번호: ',ls[6])

2019/01/19 17:21

GammaKnight

import random as r

def lotto(num):
    # 뽑기 함수 생성
    def rand_num(num):
        numb=[i for i in range(1,46)]
        r.shuffle(numb)
        list = []
        for i in range(int(num)):
            list.append(numb[i])    
        return list

    #당첨 번호 뽑기
    ans = rand_num(7)
    print("당첨번호 : %s . 보너스번호 : %s "%(ans[0:6],ans[6]))

    # 내번호 뽑기
    for i in range(int(num)):
        temp=rand_num(6)
        print("내 번호 : %s "%(temp[0:6])  )

        #당첨 확인
        count=0
        for t in temp:
            if t in ans:
                count+=1

        if count == 6: print("1등입니다!")
        elif count == 5 : print("2등입니다!")
        elif count == 4: print("3등입니다!")
        elif count == 3: print("4등입니다!")
        else: print (" 꽝 다음기회에...")

lotto(input())

2019/02/28 20:01

얀차

number=int(input("몇 번 하실?: "))



number1=0
number2=0
number3=0
from random import randint

a=[]

while len(a) <=5:
    word=randint(1,45)
    b=1
    for i in range(len(a)):
        if word==a[i]:
            b=2
    if b==1:
        a.append(word)


c=[]

while True:
    word2=randint(1,45)
    d=1
    for i in range(len(a)):
        if word2==a[i]:
            d=2
    if d==1:
        c.append(word2)
        break

list1=a+c



print("현재 당첨번호는 %s 보너스 번호는 %s 입니다." %(a, c))

for i in range(number):
    e=[]

    while len(e) <=5:
        word=randint(1,45)
        f=1
        for i in range(len(e)):
            if word==e[i]:
                f=2
        if f==1:
            e.append(word)


    g=[]

    while True:
        word2=randint(1,45)
        h=1
        for i in range(len(a)-1):
            if word2==e[i]:
                h=2
        if h==1:
            g.append(word2)
            break
    list2=e+g

    correct=0

    for i in range(len(list1)-1):
        for j in range(len(list2)-1):
            if list1[i]== list2[j]:
                correct+=1


    print("구매하신 추첨번호는 %s 보너스 번호는 %s입니다. " %(e,g))

    if correct==7:
        print("1등")


    elif correct==6:
        print("2등")

    elif correct==5:
        print("3등")

    elif correct==4:
        print("4등")    

    elif correct==3:
        print("5등")
        number1+=1
    elif correct==2:
        print("6등")
        number2+=1

    else:
        print("운 없다.")
        number3+=1

print("5등은 %s, 6등은 %s, 7등은 %s" %(number1, number2, number3))               








2019/05/29 16:46

se Mu

def lotto():
    n= int(input("로또를 몇개 구매하시겠습니까? :"))
    k = []
    for i in range(7):
        num=random.randrange(1,46)
        k.append(num)
    for r in range(7):
        if k[r] in k[0:r]:
            del (k[r])
            k.insert(r, random.randrange(1, 46))

    bonus=k[6]
    print("현재 당첨번호는",k[:6],"입니다." "보너스 번호는 %d입니다"%bonus)
    s = 0
    while True:
        asd=[]
        js=0
        for o in range(7):
            num = random.randrange(1, 46)
            asd.append(num)
        for t in range(7):
            if asd[t] in asd[0:t]:
                del (asd[t])
                asd.insert(t, random.randrange(1, 46))
        bonus = asd[6]
        for u in range(7):
            for y in range(7):
                if asd[u]==k[y]:
                    js+=1
        if js==6:
            print("구매하신 추첨번호는", asd[:6], "입니다." "보너스 번호는 %d입니다..2등이다!" % bonus)
        elif js==5:
            print("구매하신 추첨번호는", asd[:6], "입니다." "보너스 번호는 %d입니다..3등이다!" % bonus)
        elif js==7:
            print("구매하신 추첨번호는", asd[:6], "입니다." "보너스 번호는 %d입니다..1등이다!! 아싸 오늘저녁은 치킨이닭!!" % bonus)
        else:
             print("구매하신 추첨번호는", asd[:6], "입니다." "보너스 번호는 %d입니다" % bonus)
        s += 1
        if s==n:
            break

lotto()

2019/07/04 13:50

문기훈

import java.util.ArrayList; import java.util.List; import java.util.Scanner;

public class sol180 {

static List<Integer> answer = new ArrayList<Integer>();
static List<List<Integer>> chances = new ArrayList<>();


public static void main(String[] args) throws Exception {

    Scanner sc = new Scanner(System.in);

    // 복권 정답 insert
    for(int i=0; i<7; i++) {
        answer.add(sc.nextInt());
    }

    // 산 복권 갯수
    int bought = sc.nextInt();

    // 각 복권의 번호 입력
    for(int i=0; i<bought; i++) {

        List<Integer> chance = new ArrayList<>();

        for(int j=0; j<7; j++) {
            chance.add(sc.nextInt());
        }

        chances.add(chance);
    }

    // 각복권을 훑어 정답과 비교
    for(int i=0; i<chances.size(); i++) {

        int count = 0;
        List target = chances.get(i);
        List compare = new ArrayList(answer); // 비교하기 위한 answer의 복사본

        for(int j=0; j<target.size(); j++) {
            for(int k=0; k<compare.size(); k++) {

                if(target.get(j) == compare.get(k)) {
                    compare.remove(k);
                    count++;
                    break;
                }
            }
        }

        System.out.print("#" + i + " : ");

        switch(count) {
        case 5:
            System.out.println("3등");
            break;
        case 6:
            System.out.println("2등");
            break;
        case 7:
            System.out.println("1등");
            break;
        default:
            System.out.println("망");
            break;
        }


    }


}

}

2019/07/30 09:19

이병호

자바로 제멋대로 구현해봤습니다.

메인있는 클래스에서 Lotto lotto=new Lotto(); lotto.StartLotto();

로 실행시키면 됩니다.(물론 1등은 안나오더군요.)

public class Lotto {

int[] lotto=new int[7];
int[] myLotto=new int[7];

//시작하는 메소드
public void StartLotto() {
    Scanner scan=new Scanner(System.in);
    System.out.print("로또를 몇개 구매하시겠습니까? ");
    int n=scan.nextInt();

    GetLottoNumber(false);
    printLotto(false);

    for(int i=0;i<n;i++) {
        GetLottoNumber(true);
        printLotto(true);
    }
}
//로또를 구매하는 메소드 인자값에따라 당첨번호를 세팅하고 아니면 로또를 구매함. 
private void GetLottoNumber(boolean isMy) {
    Random random=new Random();
    Map<Integer, Integer> lottoMap=new HashMap<Integer,Integer>();
    while(true) {
        int number=random.nextInt(44)+1;
        lottoMap.put(number, number);

        if(lottoMap.size()==7)
            break;
    }

    Collection<Integer> numbers=lottoMap.values();

    Iterator<Integer> iter=numbers.iterator();

    int index=0;
    while(iter.hasNext())
    {
        if(isMy)
            myLotto[index]=iter.next();
        else
            lotto[index]=iter.next();

        index++;
    }

}

//로또를 출력하기 위한 메소드. 인자값에 따라 구매한번호를 출력할지 내가산로또를 출력할지 정함.
private void printLotto(boolean isMy) {
    if(isMy) {
        System.out.print("구매하신 추첨번호는 ");
        for(int i=0;i<6;i++) {
            System.out.print(myLotto[i]);
            if(!(i==5))
                System.out.print(", ");
        }
        System.out.print(" 보너스번호는 "+myLotto[6]+" 입니다 ");
        CompareLotto();
    }else {
        System.out.print("현재 당첨번호는 ");
        for(int i=0;i<6;i++) {
            System.out.print(lotto[i]);
            if(!(i==5))
                System.out.print(", ");
        }
        System.out.print(" 보너스번호는 "+lotto[6]+" 입니다\n");
    }

}

//로또를 비교하기 위한 메소드
private void CompareLotto() {
    int count=0;
    for(int i=0;i<7;i++) {
        for(int j=0;j<7;j++) {
            if(myLotto[i]==lotto[j]) {
                count++;
            }
        }
    }
    switch(count){
    case 7:
        System.out.print("..1등이다! 아싸 오늘저녁은 치킨이닭!!\n");
        break;
    case 6:
        System.out.println("2등이다!\n");
        break;
    case 5:
        System.out.println("3등이다!\n");
        break;
    case 4:
        System.out.println("4등이다!\n");
        break;
    case 3:
        System.out.println("5등이다!\n");
        break;
    default:
        System.out.println("에이 꽝이다..\n");
    }
}

}

2019/10/29 10:02

채희범

import random
ws=set() #현재 당첨번호 설정
while len(ws)<7:
    numbers=random.randint(1,45)
    ws.add(numbers)
print("현재 당첨번호는",",".join(list(map(str,ws))[0:6]),"보너스 번호는",list(ws)[6],"입니다.")

num=int(input("로또를 몇 개 뽑으시겠습니까? "))
n=0
while n<num:
    s=set()
    while len(s)<7:
        numbers=random.randint(1,45)
        s.add(numbers)
    print("구매하신 추첨번호는",",".join(list(map(str,s))[0:6]),"보너스 번호는",list(s)[6],"입니다.")
    if sorted(list(ws))==sorted(list(s)):
        print("*******축하합니다! 1등입니다.*******")
    if len(ws&s)==6:
        print("******축하합니다! 2등입니다.******")
    if len(ws&s)==5:
        print("*****축하합니다! 3등입니다.*****")
    n+=1

2020/01/02 18:49

박시원

10만 번 뽑았는데 3등 2번인가 나오네요 ㅎ... - 박시원, 2020/01/02 18:50
#파이썬

#랜덤으로 할경우 5개이상 당첨되기가 어려워 문제와 조금 다르게 변형을 하였습니다
#10000개의 로또를 샀다고 가정했을때 3등 이상만 번호와 등수를 출력하며,
#마지막에 3등이상 당첨 확률을 출력합니다
#로또는 할것이 못되는 군요 ㅠㅠㅠㅠ

from random import *

def ran_num():          #랜덤 숫자를 생성하는 함수
    x=[]
    for i in range (0,7):  
        a=randint(1,45)   
        while (1):
            if a in x:
                a=randint(1,45)
            else:
                x.append(a)
                break
    return (x)

def print_num(z):
    print ('\n구매하신 추첨번호는 ',end='')
    for j in range (0,6): 
        print(z[j],' ',end='')
    print ('보너스 번호는',z[6],'입니다')


d=ran_num()             #당첨 번호를 저장하는 리스트
print('\n========================================')
print ('당첨번호 : ',d)
print ('로또 1만개를 구입합니다')
print('========================================')
nn=0
for i in range (0,10000):
    g=ran_num()         # 자동 생성으로 구매된 번호 리스트

    k=0
    for j in range (0,7): 
        if g[j] in d:
            k+=1
    if k>=5:
        print_num(g)
        nn+=1
        if k==5:
            print('3등입니다.')  
        elif k==6:
            print('2등입니다.')
        elif k==7:
            print('1등입니다.')

print ('\n3등이상 당첨될 확률은',nn/10000*100,'%')



2020/04/29 11:09

Buckshot

======================================== 당첨번호 : [16, 6, 41, 42, 39, 19, 31] 로또 1만개를 구입합니다 ======================================== 구매하신 추첨번호는 45 16 39 19 17 42 보너스 번호는 6 입니다 3등입니다. 구매하신 추첨번호는 19 8 7 6 42 31 보너스 번호는 39 입니다 3등입니다. 3등이상 당첨될 확률은 0.02 % ======================================== 당첨번호 : [3, 39, 26, 19, 37, 43, 28] 로또 1만개를 구입합니다 ======================================== 구매하신 추첨번호는 39 4 28 19 43 3 보너스 번호는 40 입니다 3등입니다. 3등이상 당첨될 확률은 0.01 % - Buckshot, 2020/04/29 11:11

java(배운지 6일 됬네요...)

import java.util.Arrays;
import java.util.Scanner;

public class Lotto {
    public static void main(String[] args) {

        int lotto[] = new int [6];
        Scanner sc = new Scanner(System.in);
        System.out.print("로또를 몇개 구매하시겠습니까? : ");
        int buy = sc.nextInt();
        System.out.print("\n===============================\n\n로또 당첨번호 : ");

        int lottoNum[] = new int [7];
        for(int i=0; i<7; i++) {
            lottoNum[i] = (int)(Math.random() * 45) + 1;
            for(int j=0; j<i; j++) {
                if(lottoNum[i] == lottoNum[j]) {
                    i--;
                    break;
                }
            }
        }//7개를 생성해서 마지막 번호는 보너스번호로 사용
        System.out.print(Arrays.toString(lottoNum));
        System.out.println("\n보너스 번호는 [ " + lottoNum[6] + " ]");

        System.out.print("\n===============================\n\n당신의 로또 번호 : ");

        for (int a = 0; a < buy; a++) {
            for(int i=0; i<6; i++) {
                lotto[i] = (int)(Math.random() * 45) + 1;
                for(int j=0; j<i; j++) {
                    if(lotto[i] == lotto[j]) {
                        i--;
                        break;
                    }
                }
            }
            System.out.println("");
            System.out.print(Arrays.toString(lotto));
            System.out.println("\n당신의 로또 응모 결과");
            int cont = 0;
            for (int i = 0; i < 6; i++) {
                for (int z = 0; z < 7; z++) {
                    if(lotto[i] == lottoNum[z]) {
                        cont++;
                    }
                }
            }
            int cont2 = 0;
            for (int i = 0; i < 6; i++) {
                for (int z = 0; z < 6; z++) {
                    if(lotto[i] == lottoNum[z]) {
                        cont2++;
                    }
                }
            }
            System.out.println("당첨된 번호 개수는 : " + cont + "개 입니다.");
            switch (cont2) {
            case 0:
            case 1:
                System.out.println("낙첨되었습니다.");
                break;
            case 2:
                if(lottoNum[6] == lotto[0] || lottoNum[6] == lotto[1] ||  lottoNum[6] == lotto[2] || lottoNum[6] == lotto[3] || 
                lottoNum[6] == lotto[4] || lottoNum[6] == lotto[5]) {
                    System.out.println("축하합니다. 5등입니다.");
                } else {
                    System.out.println("낙첨되었습니다.");
                }
                break;
            case 3:
                if(lottoNum[6] == lotto[0] || lottoNum[6] == lotto[1] ||  lottoNum[6] == lotto[2] || lottoNum[6] == lotto[3] || 
                lottoNum[6] == lotto[4] || lottoNum[6] == lotto[5]) {
                    System.out.println("축하합니다. 4등입니다.");
                } else {
                    System.out.println("축하합니다. 5등입니다.");
                }
                break;
            case 4:
                if(lottoNum[6] == lotto[0] || lottoNum[6] == lotto[1] ||  lottoNum[6] == lotto[2] || lottoNum[6] == lotto[3] || 
                lottoNum[6] == lotto[4] || lottoNum[6] == lotto[5]) {
                    System.out.println("축하합니다. 3등입니다.");
                } else {
                    System.out.println("축하합니다. 4등입니다.");
                }
                break;
            case 5:
                if(lottoNum[6] == lotto[0] || lottoNum[6] == lotto[1] ||  lottoNum[6] == lotto[2] || lottoNum[6] == lotto[3] || 
                    lottoNum[6] == lotto[4] || lottoNum[6] == lotto[5]) {
                    System.out.println("축하합니다. 2등입니다.");
                } else {
                    System.out.println("축하합니다. 3등입니다.");
                }
                break;
            case 6:
                System.out.println("축하합니다. 1등입니다.");
                break;
            default:
                break;
            }
        }

        sc.close();
    }
}

결과화면 ///////////

로또를 몇개 구매하시겠습니까? : 5

===============================

로또 당첨번호 : [2, 43, 4, 31, 13, 18, 19] 보너스 번호는 [ 19 ]

===============================

당신의 로또 번호 :
[2, 40, 31, 4, 14, 38]
당신의 로또 응모 결과
당첨된 번호 개수는 : 3개 입니다.
축하합니다. 5등입니다.

[32, 33, 12, 14, 38, 1]
당신의 로또 응모 결과
당첨된 번호 개수는 : 0개 입니다.
낙첨되었습니다.

[8, 35, 11, 44, 37, 22]
당신의 로또 응모 결과
당첨된 번호 개수는 : 0개 입니다.
낙첨되었습니다.

[42, 23, 38, 41, 44, 28]
당신의 로또 응모 결과
당첨된 번호 개수는 : 0개 입니다.
낙첨되었습니다.

[42, 3, 22, 41, 26, 24]
당신의 로또 응모 결과
당첨된 번호 개수는 : 0개 입니다.
낙첨되었습니다.

2021/05/26 11:58

A-assasin Kr

python 3.9.6입니다. 이 방식대로 5등까지 구현했습니다.

import random
answer = list(range(1, 46))
random.shuffle(answer)
answer = answer[:7]
count = int(input('로또를 몇 개 구매하시겠습니까?: '))
print(f'당첨 번호: {answer[:-1]}, 보너스: {answer[-1]}')
answer = set(answer)
for _ in range(count):
    trial = list(range(1, 46))
    random.shuffle(trial)
    trial = trial[:7]
    print(f'구매 번호: {trial[:-1]}, 보너스: {trial[-1]}')
    trial = set(trial)
    if len(answer.intersection(trial)) >= 3:
        print(f'{len(answer - trial)+1}등입니다.')
    else:
        print('당첨 실패입니다.')

실행 결과입니다.

또를 몇 개 구매하시겠습니까?: 5
당첨 번호: [20, 9, 31, 40, 44, 26], 보너스: 5
구매 번호: [12, 22, 3, 17, 11, 43], 보너스: 20
당첨 실패입니다.
구매 번호: [8, 24, 12, 22, 5, 33], 보너스: 6
당첨 실패입니다.
구매 번호: [24, 5, 14, 20, 22, 8], 보너스: 3
당첨 실패입니다.
구매 번호: [34, 9, 21, 24, 17, 13], 보너스: 18
당첨 실패입니다.
구매 번호: [30, 6, 31, 23, 20, 44], 보너스: 14
5등입니다.

2021/07/18 11:32

이준우

import random
n = int(input("How many lottos do you buy?: "))

def lotto_buy():
    num = list(range(1, 46))
    buy = random.sample(num, 7)
    return buy

def lotto_random():
    num = list(range(1, 46))
    ran = random.sample(num, 7)
    return ran

def match(a, b):
    diff = list(set(a) - set(b))
    return diff

ran = lotto_random()
bonus_ran = random.sample(ran, 1)
print("=====The number is " + str(ran) + ", and bonus number is " + str(bonus_ran) + "=====")

for i in range(n):
    buy = lotto_buy()
    bonus_buy = random.sample(buy, 1)
    print("The number you buy is " + str(buy) + ", and bonus number is " + str(bonus_buy))

    count_1st = 0
    count_2nd = 0
    count_3rd = 0
    count_4th = 0
    count_5th = 0
    count_NONE = 0

    if sorted(ran) == sorted(buy):
        print("Congradulation! You are 1st.")
        count_1st = count_1st + 1
    elif len(match(ran, buy)) == 1 and bonus_ran == bonus_buy:
        print("You are 2nd.")
        count_2nd = count_2nd + 1
    elif len(match(ran, buy)) == 2:
        print("You are 3rd.")
        count_3rd = count_3rd + 1
    elif len(match(ran, buy)) == 3:
        print("You are 4th.")
        count_4th = count_4th + 1
    elif len(match(ran, buy)) == 4:
        print("You are 5th.")
        count_5th = count_5th + 1
    else:
        print("NONE")
        count_NONE = count_NONE + 1

print(count_1st)
print(count_2nd)
print(count_3rd)
print(count_4th)
print(count_5th)
print(count_NONE)

2021/12/23 17:51

용가리

python(22.10.31)

import random

count = int(input("로또를 몇 개 구매하시겠습니까?: "))
numbers = list(range(1, 46))
choice_number = list(random.sample(numbers, 7))

random_number = set(choice_number[:6])
bouns = choice_number[-1]

print(f"현재 당첨번호는 {random_number} 보너스번호는 {bouns} 입니다.")
for i in range(count):
    mylotto = set(random.sample(numbers, 6))
    correct = random_number & mylotto

    if len(correct) == 6:
        print(f"구매하신 추첨번호는 {mylotto} 입니다. 축하드립니다. 1등입니다")
    elif len(correct) == 5:
        if bouns in correct :
            print(f"구매하신 추첨번호는 {mylotto} 입니다. 축하드립니다. 2등입니다")
        else:
            print(f"구매하신 추첨번호는 {mylotto} 입니다. 축하드립니다. 3등입니다")
    elif len(correct) == 4:
            print(f"구매하신 추첨번호는 {mylotto} 입니다. 축하드립니다. 4등입니다")
    elif len(correct) == 3:
        print(f"구매하신 추첨번호는 {mylotto} 입니다. 축하드립니다. 5등입니다")
    else:
        print(f"구매하신 추첨번호는 {mylotto} 입니다. 꽝 다음기회에")

c++```{.cpp}(26.06.30)

include

include

using namespace std;

int main() { random_device rd; mt19937 gen(rd()); uniform_int_distribution distribution(1, 45);

int lottoNum[7] = { 0 };
for (int i = 0; i < 7; i++) {
    lottoNum[i] = distribution(gen);
}
int amount = 0;
cout << "몇개 구매하시겠습니까?";
cin >> amount;
cout << "현재 당첨번호는 ";
for (int i = 0; i < 6; i++) {
    cout << lottoNum[i] << " ";
}
cout << "보너스 번호는" << lottoNum[6] << " 입니다" << endl;

for (int i = 0; i < amount; i++) {
    int buyingLotto[7] = { 0 };
    cout << "구매하신 추첨번호는 ";
    for (int i = 0; i < 7; i++) {
        buyingLotto[i] = distribution(gen);
    }
    for (int i = 0; i < 6; i++) {
        cout << buyingLotto[i] << " ";
    }
    cout << "보너스 번호는" << buyingLotto[6] << " 입니다" << endl;
    int count = 0;
    for (int i = 0; i < 6; i++) {
        if (buyingLotto[i] == lottoNum[i]) count++;
    }
    int flag = 0;
    if (buyingLotto[6] == lottoNum[6]) flag = 1;
    if (count == 6) cout << "1등!!" << endl;
    else if (count == 5 && flag == 1) cout << "2등!!" << endl;
    else if (count == 5) cout << "3등!!" << endl;
    else if (count == 4) cout << "4등!!" << endl;
    else if (count == 3) cout << "5등!!" << endl;
    else cout << "꽝!!" << endl;
}

} ```

2022/10/31 23:29

김성범

목록으로