[C#] 중복을 제외하고 랜덤으로 숫자를 뽑는 기능 구현
C#으로 중복을 제외하고 숫자를 랜덤으로 뽑는 기능을 구현합니다.
using System;
using System.Collections.Generic;
using System.Linq;
namespace MyProject{
class Program{
// 0~lastIndex 까지의 숫자를 중복없이 Count 만큼 뽑는 함수
static List<int> RandomNumber(int lastIndex, int count)
{
List<int> result = new List<int>();
int element;
while(result.Count < count)
{
element = new Random().Next(lastIndex);
result.Add(element);
result = result.Distinct().ToList(); // 중복제거 작업
}
return result;
}
static void Main(string[] args)
{
List<int> list = RandomNumber(5,3);
// 리스트를 한 줄로 출력
Console.WriteLine(string.Join(",",list));
}
}
}
이제 코드에 대해서 자세히 설명하자면 result 리스트의 크기가 Count와 같아질 때까지 무한 반복한다.
while(result.Count < count)
element에 0~lastIndex까지의 임의의 숫자를 뽑아내고, result에 Add한다. 마지막으로 Distinct()으로 중복을 제거한 리스트를 생성한다.
element = new Random().Next(lastIndex);
result.Add(element);
result = result.Distinct().ToList();