2014-12-24 3 views
0

2 차원 배열의 문자열을 찾아야하고 어떻게해야할지 모르겠다. 코드는 다음과 같아야합니다문자열의 2 차원 배열에서 특정 문자열을 찾는 방법은 무엇입니까?

... 
Random x = new.Random(); 
Random y = new.Random(); 
string[,] array = new string[10,10]; 
{ 
    for (int i = 0; i < 10; i++) 
    { 
     for (int j = 0; j < 10; j++) 
     { 
      array[i, j] = ""; 
     } 
    } 
} 
array[x.Next(0,10),y.Next(0,10)] = "*"; 
... 

* 기호는 다른 자리에 항상 나는 내가 그것을 발견 할 방법을 알고 싶습니다. 감사합니다

+0

의 형태로 경기의 목록입니다 the 무작위로 2 차원 배열, 오른쪽에 "*"를 넣어? 그리고 그 위치가 ""어디에 있는지 찾아야합니다. – hmartinezd

+0

코드가있는 경우 먼저 'x.Next (0,10)'및 'y.Next (0,10) '로 지역 변수를 설정 한 다음 해당 변수를 사용하여 배열을 업데이트하십시오. – serdar

답변

1

당신은 제외하고, 그것을 초기화하는 대신 배열 인덱스에 값을 할당하기위한 그랬던 것처럼 배열을 반복하여 찾을 수 있습니다, 당신은 어떤지를 확인해 보겠습니다 :

int i = 0; 
int j = 0; 
bool found = false; 

for (i = 0; i < 10 && !found; i++) 
{ 
    for (j = 0; j < 10; j++) 
    { 
     if (array[i, j] == "*") 
     { 
      found = true; 
      break; 
     } 
    } 
} 

if (found) 
    Console.WriteLine("The * is at array[{0},{1}].", i - 1, j); 
else 
    Console.WriteLine("There is no *, you cheater."); 
+0

@hmartinezd 사실, 당신이 좀 봐야한다고 생각 : http://stackoverflow.com/questions/1659097/why-would-you-use-string-equals-over – itsme86

0

을 alterntive으로 LINQ와 검색 쿼리

Random xRnd = new Random(DateTime.Now.Millisecond); 
Random yRnd = new Random(DateTime.Now.Millisecond); 

string[,] array = new string[10, 10]; 

array[xRnd.Next(0, 10), yRnd.Next(0, 10)] = "*"; 

var result = 
    Enumerable.Range(0, array.GetUpperBound(0)) 
    .Select(x => Enumerable.Range(0, array.GetUpperBound(1)) 
     .Where(y => array[x, y] != null) 
     .Select(y => new { X = x, Y = y })) 
    .Where(i => i.Any()) 
    .SelectMany(i => i) 
    .ToList(); 

result 당신이 공유하고있는 코드는 X,Y

관련 문제