简体   繁体   中英

How do I store references to elements of a 2D array?

I'm checking each element of a 2d array for specific conditionals. If the element is true I want to check it's direct neighboring adjacent elements. If the neighboring elements are false I want to keep track of them, lets call these "validElements". Once all elements have been checked I want to pick one of the validElements at random and make it true, then clear that collection of validElements and repeat this process an arbitrary amount of times.

I know how to check each element and their neighbors for the conditionals but i'm not sure the proper way to keep track of the references to elements that are considered "validElements". How should I keep track of this data?

public bool [,] Grid = new bool [3,3];

// lets make the middle element true so we have a starting point. 

Grid[Grid.GetLength(0) / 2, Grid.GetLength(1) / 2] = true;

for (int row = 0; row < Grid.GetLength(0); row++)
{
    for (int col = 0; col < Grid.GetLength(1); col++)
    {
        if (Grid[row, col])
        {
            // if neighboring cells are false keep track of them somehow
        }
    }
}

One of the most basic solutions would be to create a list of coordinates where you'll store all the Xs and Ys where you found a valid element. So, before your

for (int row = 0; row < Grid.GetLength(0); row++)

add a

var validElements = new List<(int x, int y)>();

and instead of your

// if neighboring cells are false keep track of them somehow

do

if (/*some condition*/)
{
    validElements.Add((row, col));
}

Next, once the loop is done, you need to pick a random valid element and set it to true. You can do this by

var random = new Random();
var randValidElement = validElements[random.Next(validElements.Count - 1)]; 
// above line is assuming you have at least one valid element. 
// You should do a check if validElements.Count == 0 then do something
Grid[randValidElement.x, randValidElement.y] = true; // this is the final step

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM