Random slot algorithm

后端 未结 4 1479
执念已碎
执念已碎 2020-11-27 08:35

I have two dimensional array. I want to pick a slot at random, and continue to do so never picking the same slot twice until I have finally picked all slots (so nothing ran

相关标签:
4条回答
  • 2020-11-27 08:54

    I did this for numbers

    list<int> PastList=new PastList<int>();
    private void Choоse()
    {
       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 讨论(0)
  • 2020-11-27 08:58

    Take a look at the Fisher-Yates shuffle. It's designed to pick a random permutation from a set.

    0 讨论(0)
  • 2020-11-27 09:10

    Assuming your array is 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.

    0 讨论(0)
  • 2020-11-27 09:13

    Using the Fisher-Yates shuffle algorithm as mentioned before (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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题