2012-01-13 5 views
1

내 코드에서 우리는 random.Next를 사용하여 ListBox에서 무작위로 선을 당기는 것을 볼 수 있습니다. 문제는 만약 내가 같은 수의 문자를 검사하기를 원한다면 나는 새로운 난수를 사용하여 어떤 문제를 일으킨다.동일한 난수를 두 번 얻는 방법은 무엇입니까?

IF 문에서 첫 번째 난수를 어떻게 사용할 수 있습니까?

SendKeys.Send(lbMessage.Items[random.Next(lbMessage.Items.Count)]. 
    ToString().Substring(currentChar++, 1)); 

if (currentChar == lbMessage.Items[random.Next(lbMessage.Items.Count)].ToString().Length) 
{ 
    SendKeys.Send("{enter}"); 
    tmrSpace.Enabled = false; 
    currentChar = 0; 
} 
+5

동일한 번호를 얻는 방법을 알고 있다면 그 번호는 무작위가 아닙니다. – Maheep

답변

2

지역 변수의 첫 번째 임의의 숫자를 저장하고 다음과 같이 나중에 사용할 : 간단하게 대해 어떻게 변수 :-)

var rnd = random.Next(lbMessage.Items.Count); 
SendKeys.Send(lbMessage.Items[rnd]. 
    ToString().Substring(currentChar++, 1)); 

if (currentChar == lbMessage.Items[rnd].ToString().Length) 
{ 
    SendKeys.Send("{enter}"); 
    tmrSpace.Enabled = false; 
    currentChar = 0; 
} 
+0

그러나 변수가 다시 호출되면 임의 변경이 발생하지 않습니까? 나는 이것을 시도하고 새로운 임의의 시드를 생성하는 것으로 보인다. – NewHelpNeeder

+0

그런 다음 생성 된 임의의 번호를 코드의 다른 위치에 저장해야합니다. 여기서 코드는 변경되지 않을 것입니다. –

1

을 임의성을 임시로 저장 하시겠습니까?

int randomness = random.Next(lbMessage.Items.Count); 
SendKeys.Send(lbMessage.Items[randomness].ToString().Substring(currentChar++, 1)); 

if (currentChar == lbMessage.Items[randomness].ToString().Length) 
{ 
    SendKeys.Send("{enter}"); 
    tmrSpace.Enabled = false; 
    currentChar = 0; 
} 
+0

이것은 새로운 랜덤을 생성하는 것처럼 보입니다. 나는 이것을 시도했지만 씨앗이 바뀌는 것 같습니다. – NewHelpNeeder

+0

아니요, 뭔가 잘못하고 있어야합니다. 'rnd'는 두 번째 줄과 세 번째 줄에서 동일합니다. –

+0

@NewHelpNeeder - 이것은 첫 번째 라인에서 한 번 난수를 생성하고 send 키와 if 문에서 다시 사용합니다. 다른 숫자는 어때? – RQDQ

0

에 백업

int ran = random.Next(lbMessage.Items.Count); 
SendKeys.Send(lbMessage.Items[ran].ToString().Substring(currentChar++, 1)); 

if (currentChar == lbMessage.Items[ran].ToString().Length) { 
    SendKeys.Send("{enter}"); 
    tmrSpace.Enabled = false; 
    currentChar = 0; 
} 
0

이게 당신이 원하는 것입니까?

int index = random.Next(lbMessage.Items.Count); 

string value = lbMessage.Items[index].ToString(); 

SendKeys.Send(value.Substring(currentChar++, 1)); 

if (currentChar == value.Length) 
{ 
    SendKeys.Send("{enter}"); 
    tmrSpace.Enabled = false; 
    currentChar = 0; 
} 
0

시드 값을 Random() 생성자에 전달하면 매번 동일한 임의 값이 반환됩니다.

Random random = new Random(86); // Seed can be any Int32 value 

달성하려는 목표는 무엇입니까? 나는 Sergio의 대답이 당신이 찾고있는 것이라고 생각했을 것이다. 그러나 그것은 그렇게 보이지 않는다.

관련 문제