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

2
  • 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? Commented Dec 24, 2014 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? Commented Dec 24, 2014 at 18:02

2 Answers 2

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.");
Sign up to request clarification or add additional context in comments.

1 Comment

@hmartinezd In fact, I think you should take a look at: stackoverflow.com/questions/1659097/…
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.