Random Section Algorithm

I have a two dimensional array. I want to choose a random case and continue to ensure that I never select the same slot twice until I finally select all the slots (so there’s nothing random about the last course choice). Is there a known algorithm for this? I use C #, but obviously this is more about algorithms than any particular platform. Yes, the "big book" is on my shopping list :)

0
source share
4 answers

Using the Fisher-Yates shuffle algorithm as mentioned earlier (in O (n) time)

int X = 3; int Y = 4; int[] array = new int[X * Y]; for (int i = 0; i < array.Length; i++) array[i] = i; FisherYatesShuffle(array); var randomSlots = array.Select((i,j) => new {x=array[j]%X , y=array[j]/X }) .ToArray(); 

 public static void FisherYatesShuffle<T>(T[] array) { Random r = new Random(); for (int i = array.Length - 1; i > 0; i--) { int j = r.Next(0, i + 1); T temp = array[j]; array[j] = array[i]; array[i] = temp; } } 
+3
source

Take a look at the Fisher-Yates shuffle . It is designed to select a random permutation from a set.

+5
source

Assuming your array looks like this:

 Random rand = new Random(); object[,] array = new object[width,height]; bool[,] chosen = new bool[width,height]; int i, j; do { i = rand.Next(width); j = rand.Next(height); } while (chosen[i,j]); chosen[i,j] = true; object current = array[i,j]; 

This should work fine.

+1
source

I did it for numbers

 list<int> PastList=new PastList<int>(); private void Chose() { int i = Recurs(); PastList.Add(i); } private int Recurs() { int i; i = rnd.Next(0, 99); if (PastList.Contains(i)) { i = Recurs(); } return i; } 
0
source

Source: https://habr.com/ru/post/924092/


All Articles