'C#'에 해당되는 글 1건

  1. 2009.03.18 C# 로또번호 랜덤 생성 소스
C#2009. 3. 18. 10:38

using System;
using System.Text;

namespace Lottery
{
    class Lotto
    {
        private static Random rnd = new Random();

        public static void Main(string[] args)
        {
            for(int i=0; i<30; i++)
            {
                System.Console.Write(GetLottoNum() + ((i+1)%3==0?"\n":"\t"));
            }
        }

        public static string GetLottoNum()
        {
            StringBuilder sb = new StringBuilder();
            int[] num = CreateLottoNum();
            num = BubbleSort(num);
            foreach(int i in num)
            {
                if(i < 10)
                {
                    sb.Append("0" + i.ToString() + " ");
                }
                else
                {
                    sb.Append(i.ToString() + " ");
                }
            }

            return sb.ToString();
        }

        //get random number(6place within 1 to 45)
        private static int[] CreateLottoNum()
        {
            int[] num = new int[6];
            for(int i=0; i<num.Length; i++)
            {
                num[i] = (int)rnd.Next(1,45);
                for(int j=0; j<i; j++)
                {
                    if(num[i] == num[j])
                    {
                        i--;
                        break;
                    }
                }
            }
            return num;
        }

        //bubble sort
        private static int[] BubbleSort(int[] num)
        {
            int tmp;
            for(int i=0; i<num.Length-1; i++)
            {
                for(int j=0; j<num.Length-i-1; j++)
                {
                    if(num[j] > num[j+1])
                    {
                        tmp = num[j];
                        num[j] = num[j+1];
                        num[j+1] = tmp;
                    }
                }
            }
            return num;
        }
    }
}

Posted by Main()