5tka
5tka

Reputation: 863

filling the array with a random number, from 0 to 2, but so that the opposite cell is filled depending on the condition

Working on a grading model, but stuck on filling an array. I need to fill the array with numbers from 0 to 2, but: - so that the main diagonal is filled only 1; - if, for example, the element a (31) = 2, then a (13) must be 0, and a set of; - if for example the element a (31) = 1, then a (13) must be 1, and a set of; The principle itself, I understand.

            if (array[i+1,j] = 2)
            {
                (array[i, j+1] = 1)
            } 
it's wrong i know

for now i have enter image description here

            int[,] array = new int[5, 5];

            Random rnd = new Random();
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    array[i, j] = rnd.Next(0, 3);
                    if (i == j)
                    {
                        array[i, j] = 1;
                    }
                }
            }
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    Console.Write("{0}\t", array[i, j]);
                }
                Console.WriteLine();
            }

here more detailes enter image description here

Upvotes: 1

Views: 91

Answers (1)

Guru Stron
Guru Stron

Reputation: 142923

Please check does this work for you(hope understood task correctly):

var arr = new int[4, 4];
var rnd = new Random();
var length = arr.GetLength(0);
for (var i = 0; i < length; i++)
{
    for (var j = i; j < length; j++)
    {
        if (i == j)
        {
            arr[i, j] = 1;
        }
        else
        {
            var curr = rnd.Next(0, 2);    
            arr[i, j] = curr;
            var reverse = curr switch
            {
                0 => 2,
                1 => 1,
                2 => 0,
                _ => throw new Exception("Should not happen")
            };

            // or if C# 8.0 is not way to go:
            //int reverse;
            //switch (curr)
            //{
            //  case 0: reverse = 2; break;
            //  case 1: reverse = 1; break;
            //  case 2: reverse = 0; break;
            //  default: throw new Exception("Should not happen");
            //}
            arr[j, i] = reverse;
        }
    }
}

Upvotes: 1

Related Questions