Randomize Array in C#

Hello again,
I know how to program in C#, but Unity doesn’t support all of the things C# normally can do.

Anyway, what I need now is an array that has twelve(12) string values put in a random order.
Thanks in advance,

  • WolfShield

just curious

why not just randomise the int you use to access the array?

2 Likes

Can’t speak for WS, but:

Sometimes you want to be able to iterate through them all in a random order without going over duplicates
Sometimes you want to preserve the random order (to go through in the same order several times, or on several different occasions)
For clarity: sometimes you just feeling like saying “shuffle this array”, and the most meaningful way to express this is ar.shuffle() :slight_smile:

[ I pick random elements a lot as well, I think clearer to add a PickRandom extension method than to do it every time with random()s (every time it comes up, I have to double check that I’m not missing out the last element :stuck_out_tongue: ) , but each to their own ]

3 Likes

Thanks for the help guys!

  • WolfShield

If you want to shuffle the array (randomize the order of the elements), you can try the Knuth shuffle algorithm:

void reshuffle(string[] texts)
    {
        // Knuth shuffle algorithm :: courtesy of Wikipedia :)
        for (int t = 0; t < texts.Length; t++ )
        {
            string tmp = texts[t];
            int r = Random.Range(t, texts.Length);
            texts[t] = texts[r];
            texts[r] = tmp;
        }
    }
31 Likes

work perfectly for me, thanks a lot!!

Please use the like button instead as a way to say thanks. The above is necroing a post from nearly 12 years ago.

7 Likes