C# Randomly pick value from table with specify pattern

Viewed 51

I would like to have 4 list of data which are 12 randomly picked data on each row in those table with a designated pattern of "*".

I did try use Random() function but it was not working as the desire output.

Below are my sample code :

for (int i = 0; i < dgvA1.Rows.Count; i++)
                {
                    int row = 0; int col = 0;

                    //Get First Row
                    for (int x = 0; x < 12;x++)
                    {
                        Random r = new Random();
                        int randomNumber = r.Next(1, 35); //for ints
                        row = randomNumber;
                        col = randomNumber;
                        rbLog.Text += row.ToString() + ";" + col.ToString();
                    }
                }

Below are the picture of the table, and the red line are the coordinate that i wanted to be randomly selected on each of the line. enter image description here

Total will be 4 line of random picked with 12 data each line. Any other method or linQ can done that?

Thanks

1 Answers

Here's some code to get you started -

List<(int, int)> principalDiagonalIndices = new List<(int, int)>();
List<(int, int)> secondaryDiagonalIndices = new List<(int, int)>();

int rowCount = dgvA1.Rows.Count;

for (int i = 0; i < rowCount; i++)
{
    for (int j = 0; j < rowCount; j++)
    {
        if (i == j)
        {
            principalDiagonal.Add((i, j));
        }
        else if ((i + j) == (rowCount - 1))
        {
            secondaryDiagonalIndices.Add((i, j));
        }
    }
}

Random r = new Random();
for (int i = 0; i < 12; i++)
{
    var principalIdx = principalDiagonalIndices[r.Next(0, principalDiagonalIndices.Count)];
    Console.WriteLine("Random principal diagonal index - {0}", dgvA1[principalIdx.Item1, principalIdx.Item2]);
    
    var secondaryIdx = secondaryDiagonalIndices[r.Next(0, secondaryDiagonalIndices.Count)];
    Console.WriteLine("Random secondary diagonal index - {0}", dgvA1[secondaryIdx.Item1, secondaryIdx.Item2]);
}

Collect the principal and secondary diagonal in the list and iterate 12 times to get a pseudo-random index.

For principal diagonal, if you observe the row and column are equal (i == j).

And for secondary diagonal it should be row and col index summed up should equal to one minus the row-count.

Related