C#
C# Random 클래스 (feat 중복제거)
sheepone
2021. 6. 24. 10:33
반응형
Random 매서드
using System;
using System.Diagnostics;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
//Next();
int iNext = rand.Next(); //0 <= value < MaxValue
Debug.WriteLine(iNext); //output 878041336
//Next(min, max);
int iminmax = rand.Next(1,2); //min <= value < max
Debug.WriteLine(iminmax); //output 29
//Next(max);
int imax = rand.Next(100); //0 <= value < max
Debug.WriteLine(imax); //output 37
//Next Bytes(byte[] buffer);
byte[] buffer = new byte[3]; //0 <= value < MaxValue
rand.NextBytes(buffer);
foreach(var buff in buffer)
Debug.WriteLine(buff); //output 103, 115, 123
//NextDouble();
double drandom = rand.NextDouble(); //0.0 <= value < 1.0
Debug.WriteLine(drandom); //output 0.664724550053815
}
}
}
중복 제거 (예제 로또 발생기)
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ConsoleApp8
{
class Program
{
static void Main(string[] args)
{
List<int> lotto = new List<int>();
int iSelect;
for(int i=0; i<6; i++) //필요한 갯수 입력 필요, 6번
{
do
{
iSelect = new Random().Next(1,46); //범위 입력 필요, 1<= value < 46
}
while (lotto.Contains(iSelect));
lotto.Add(iSelect);
Debug.WriteLine(lotto[i]); //output 39 35 7 44 15 8
}
}
}
}
반응형