There is an array of 5x5. You need to fill it with zeros, and two randomly selected items

  • And what exactly is the problem? What did not work out? - pavel
  • You can take two random numbers from 0 to 4, say 1 and 3, and then insert a unit in the array element with indices 1 and 3. But will it be right, is it not surprising? - Draktharon

1 answer 1

You basically need to select two random indexes from 0 to 24.

The easiest way to do this is using the standard Random :

  1. With help

     i1 = random.Next(25) 

    get the first index.

  2. For the second index, 24 values ​​remain, but it is necessary to choose among all the values ​​not equal to i1 . The easiest way to do this is to write this:

     i2 = random.Next(24); if (i2 >= i1) i2++; 

Ok, now you need to turn each of the indexes into a double index from 0 to 4. This is done with

 x = i / 5; y = i % 5; 

Further obvious. Fill the array with zeros, put units on two counted positions.

  • and how to make a random couple of elements? Use i3 = random.Next (23) and i4 = random.Next (22) ;; only puts a new random element next to the previous random element - Draktharon
  • @RustemValeev: If you need a sample of k random elements, it is easier, probably, to make a selection of random elements, as described here (second block of code), only to lead not to n , but to k (in your case 4). - VladD