How to jumble up numbers into an array? (e.g 1-10)

Pretty new to coding in general here, I am trying to pre-select a random order for the use of random level selection. For example, 10 levels pre-selected into random order :

Levelselect[1] = 5
Levelselect[2] = 8
Levelselect[3] = 3
.
.
.
Levelselect[9] = 2
Levelselect[10] = 9

What is the most graceful way to do this? (Might have to go up to over 100)

Thanks in advance!

There is no standard shuffle function, but there are plenty of ways to do that.
Have a look there: c# - Best way to randomize an array with .NET - Stack Overflow

Hello,

All you have to do is to put a random number in each of your array spot. You can clamp the random values to the bounds you need.
If you have a lot of values to put in your array (you said over 100), then create those values in a loop and fill in your array at the same time.

Thanks for the replies.

@ericbegue , thanks for the link - I will have to try that, although I am not familiar at all with those libraries, and would prefer to do without…

@Darholm - the problem is, the number must not repeat. It’s shuffling, like ericbegue described.

Ok then it is the index in the array that may be randomized :wink:
Of course, doing so you’ll have to check that there is nothing already in the array when you get a new index.
And do some little optimization the more the array is filled in.

int RandomLevel = Random.Range(0,MaxLevelID);

Here’s how I would do it:

You have your array of indices, 0…n-1. Pick one of these at random, and add it to your randomized list. Move the last number from the index array to the picked number’s spot, reducing the size of the index array to n-1. Repeat.

This runs in O(n) time, and I think it’s as fast and as simple as you can do it.

List is a easier way to do this.

  1. Fill up a list with numbers 1 to 10
  2. Generate a random number between 0 and size of the list ( initially 0 - 9)
  3. Use the List[RandomNumber] as your current level, and remove the same from list using List.RemoveAt.
  4. Now your list will be one count less and your already loaded level will not be there.
  5. Repeat #2 and #3 till list is empty.

Thank you !

That’s pretty much the same as what I wrote, but List.RemoveAt runs in O(n) time, so your method would run in O(n^2) time. That doesn’t matter if your n is small, or if it doesn’t get run that often, but in this case, the small difference between our algorithms has a large theoretical performance impact.

Something like this:

while(objects.Length > 0) {

    int index = Random.Range(0, objects.Length);   
    int lastIndex = objects.Length - 1;   
   
    randomizedObjects.Add(object[index]);
    objects[index] = objects[lastIndex];   
    objects[lastIndex] = null;
}