views:

47

answers:

2

I am working with a 2-D array of nullable booleans bool?[,]. I am trying to write a method that will cycle through its elements 1 at a time starting at the top, and for each index that is null, it will return the index.

Here is what I have so far:

public ITicTacToe.Point Turn(bool player, ITicTacToe.T3Board game)
{
    foreach (bool? b in grid)
    {
        if (b.HasValue == false)
        {                      
        }
        if (b.Value == null)
        {
        }


    }
    return new Point();

 }

I want to be able to set the object to true/false depending on the bool passed in. Point is just a class with an x,y.

What's a great way to write this method?

+2  A: 

You should use a normal for loop and use the .GetLength(int) method.

public class Program
{
    public static void Main(string[] args)
    {
        bool?[,] bools = new bool?[,] { { true, null }, { false, true } };

        for (int i = 0; i < bools.GetLength(0); i++)
        {
            for (int j = 0; j < bools.GetLength(1); j++)
            {
                if (bools[i, j] == null)
                    Console.WriteLine("Index of null value: (" + i + ", " + j + ")");
            }
        }
    }
}

The parameter to .GetLength(int) is the dimension (i.e. in [x,y,z], You should pass 0 for length of dimension x, 1 for y, and 2 for z.)

Kirk Woll
+1  A: 

Just for fun, here's a version that uses LINQ and anonymous types. The magic is in the SelectMany statement, that converts our nested array into an IEnumerable<> of an anonymous type that has an X and Y coordinate, and the value in the cell. I'm using the form of Select and SelectMany that provides an index to make it easy to get the X and Y.

static

 void Main(string[] args)
 {
     bool?[][] bools = new bool?[][] { 
         new bool?[] { true, null }, 
         new bool?[] { false, true } 
     };
     var nullCoordinates = bools.
         SelectMany((row, y) => 
             row.Select((cellVal, x) => new { X = x, Y = y, Val = cellVal })).
         Where(cell => cell.Val == null);
     foreach(var coord in nullCoordinates)
         Console.WriteLine("Index of null value: ({0}, {1})", coord.X, coord.Y);
     Console.ReadKey(false);
 }
SamStephens
@Sam, +1, I always like LINQ answers.
Kirk Woll