Need an Example of randomizing a grid with characters that have varying amounts

48 Views Asked by At

I would like to see peoples examples of how you would randomize a grid with different values. this is the original board

string[,] board = new string[4, 4];
for (int y = 0; y < 4; y++)
{
    for (int x = 0; x < 4; x++)
    {
        board[x, y] = ".";
    }
}

I'm trying to figure out how to place random characters instead of the "." the problem is the amount of each value that needs to be populated. For example there should be 1 "E" populated and 1 "T" populated but thee rest of the grid needs to be "N" and "L" the amount doesn't matter.

I've tried doing it this way and it didn't work

string[] values{"N", "L"}
int index = rand.Next(values.Length);

board[0, 0] = values[index];
board[0, 1] = values[index];
board[0, 2] = values[index];
board[0, 3] = values[index];
    //etc...```

I've looked around and can't seem to find any example of what I'm trying to do.

2

There are 2 best solutions below

0
On

You can try the following code:

private static Random random = new Random();
public static string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}
0
On

I would first fill in the "N" and "L" and then replace two random positions with an "E" and a "T"

string[,] board = new string[4, 4];
string[] nl = { "N", "L" };
for (int y = 0; y < 4; y++)
{
    for (int x = 0; x < 4; x++)
    {
        board[x, y] = nl[rand.Next(2)];
    }
}

Now we have a board full of "N" and "L"s. Let's choose two random positions to fill in an "E" and a "T"

int x = rand.Next(4);
int y = rand.Next(4);
board[x, y] = "E";

int x2, y2;
// Ensure that we don't place the "T" at the same place as the "E"
do {
    x2 = rand.Next(4);
    y2 = rand.Next(4);
} while (x2 == x && y2 == y);
board[x2, y2] = "T";