0

I need to find a string in a two dimensional array and I don't know how. The code should look like this:

...
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)] = "*";
...

The * symbol is always in a different spot and I'd like to know how do I find it. Thanks

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
  • The code you're sharing is the on the randomly put the "*" in the two-dimensional array, right? And then you need to find the location where that "" is, right? – hmartinezd Dec 24 '14 at 16:41
  • If you have the code, why dont you first set local variables with ´x.Next(0,10)´ and ´y.Next(0,10)´, then use those variables to update the array? – serdar Dec 24 '14 at 18:02

2 Answers2

1

You can find it by iterating through the array just like you did for initializing it, except instead of assigning the array index a value, you'll check it for equality:

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.");
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • @hmartinezd In fact, I think you should take a look at: http://stackoverflow.com/questions/1659097/why-would-you-use-string-equals-over – itsme86 Dec 24 '14 at 16:46
0

As an alterntive search query with 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 is a list of matches in the form of X,Y

t3chb0t
  • 16,340
  • 13
  • 78
  • 118