1

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?

1
  • This helps a lot, thank you. I am still fairly new to C#, what is the purpose of this code? mostly I am confused about the {true,null} and {false, true} parts. bool?[,] bools = new bool?[,] { { true, null }, { false, true } }; Commented Oct 15, 2010 at 5:02

2 Answers 2

2

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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);
 }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.