2013-07-22 4 views
0

숫자와 사운드라는 두 개의 배열이 있습니다. 내 코드는 아래와 같습니다. 난수 생성기를 사용할 때 사운드 배열에 동일한 값을 할당하지 않아도됩니다. 소리 [0], 소리 [1], 소리 [3]은 항상 다른 값을 가져야합니다. 간단한 방법을 원하는 성능에 문제가 없으면 감사랜덤 생성기를 사용하여 배열에 다른 값을 할당

string[] numbers ={ "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"}; 

Random r= new Random(); 

sounds[0] = numbers[r.Next(0, numbers.Count())]; 

sounds[1] = numbers[r.Next(0, numbers.Count())]; 

sounds[2] = numbers[r.Next(0, numbers.Count())]; 
+0

정확히 무엇이 문제입니까? 아니면 지금은 무엇을 생성합니까 –

+0

정말로 목적 번호가 작동하지 않습니다, 당신은 그냥 r.Next (1, 20) – Sayse

+0

내가 프로그램을 컴파일하면 소리 [0], 소리 [1], 소리 [ 3]은 같은 값일 수 있습니다. 예를 들어, 소리 [0] = 5, 소리 [1] = 5, 소리 [3] = 20. sounds [0]과 sounds [1]은 예를 들어 여기에 같은 값을 가지고 있습니다. 나는 그들이 서로 다른 가치가되기를 바란다. – user2569038

답변

0

, 당신은 목록으로 배열을 변환하고 각 요소를 제거 할 수 있습니다 촬영과 같이

여기
string[] numbers ={ "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12","13","14","15","16","17","18","19","20"}; 

List<string> remaining = new List<string>(numbers); 

Random r = new Random(); 

for (int i = 0; i < 3; ++i) 
{ 
    int n = r.Next(0, remaining.Count); 
    sounds[i] = remaining[n]; 
    remaining.RemoveAt(n); 
} 
+0

잘 부탁드립니다 – user2569038

0

오히려 간단하다/당신에게 몇 가지 아이디어를 줄 수있는 순진한 대답. .Length은 O (1) 연산이므로 .Count()이 아닌 .Length을 사용해야하며 이미 해당 속성이 있습니다. sounds이 더 큰 경우이 솔루션은 확장되지 않습니다. 그렇다면 numbers 배열을 섞어 놓고 싶을 것이다. 이것은 당신에게 3 개의 유일한 가치를 줄 것이다.

string[] numbers = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" }; 
string[] sounds = new string[3]; 
Random r = new Random(); 

//get the first one, this one will always be unique 
sounds[0] = numbers[r.Next(0, numbers.Length)]; 
//set the second equal to the first, so that it will enter the while loop. 
sounds[1] = sounds[0]; 
while (sounds[1] == sounds[0]) //repeats until it gets a unique value 
    sounds[1] = numbers[r.Next(0, numbers.Length)]; 
sounds[2] = sounds[0]; 
while (sounds[2] == sounds[1] || sounds[2] == sounds[0]) //works the same as previous, except it checks for both 
    sounds[2] = numbers[r.Next(0, numbers.Length)]; 
+0

작동 감사합니다 – user2569038

관련 문제