1

how can i Create a randomly ordered array from the existing array I have? Like how can i make a new array copy elements from my old array into the new, but in a random order. this is what i have

 MobileObjects[] array = new MobileObjects[3];
 MobileObjects mob = new MobileObjects();
 mob.name = ("Jawaharal");
 mob.setPosition();
 mob.id = 1;
 array[0] = mob;

 MobileObjects mob1 = new MobileObjects();
 mob1.name = ("Willow");
 mob1.setPosition();
 mob1.id = 2;
 array[1] = mob1;

 MobileObjects mob2 = new MobileObjects();

 mob2.name = ("Indira");
 mob2.id = 3;
 mob2.setPosition();
 array[2] = mob2;
 //shows whats in array
 foreach (MobileObjects host in array)
 {
    Console.WriteLine("Name : " + host.name + " ");
    Console.WriteLine("ID   : " + host.id);
    Console.WriteLine("Position: " + host.position[0] + " " + 
    host.position[1] + " " + host.position[2]);
 }

}

Momo
  • 11
  • 2
  • Possible duplicate of [Best way to randomize an array with .NET](https://stackoverflow.com/questions/108819/best-way-to-randomize-an-array-with-net) – Jonathon Chase May 24 '18 at 01:10

2 Answers2

0

The best way, taking O(n) time, is to copy all the elements into a new array and then shuffle it. Fisher-Yates is the standard shuffling algorithm and is easy to implement. In pseudocode:

n = myArray.length
for i=n, i>0, i--
    j = randomIntegerBetween(0, i)
    swap(myArray, i, j)

This clearly runs in O(n). The implementation details will depend on how secure you need your randomness to be. The number of permutations of even a moderately-sized array will be much higher than the period of most PRNGs, so if that becomes an issue you'll need a better source of randomness.

Draconis
  • 3,209
  • 1
  • 19
  • 31
0

You could use the Fisher-Yates algorithm.

public static void Shuffle<T> (this Random rng, T[] array)
{
    int n = array.Length;
    while (n > 1) 
    {
        int k = rng.Next(n--);
        T temp = array[n];
        array[n] = array[k];
        array[k] = temp;
    }
}

You could use a basic Linq shuffle;

var MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();

or Linq with a better randomisation

using System.Security.Cryptography;
...

RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
...

static int GetNextInt32(RNGCryptoServiceProvider rnd)
    {
        byte[] randomInt = new byte[4];
        rnd.GetBytes(randomInt);
        return Convert.ToInt32(randomInt[0]);
    }

Note the above 2 Linq examples, are O(n log n)

TheGeneral
  • 79,002
  • 9
  • 103
  • 141