Shuffle algorithm not working C#

I’m trying to write code to shuffle a list randomly by adding random elements to an empty list (and removing them as I go) until they’re all added. It seems to sort itself after 2 iterations, what’s wrong with my code?

private List<int> Shuffle(List<int> listdecreasing)
        List<int> listfilling = new List<int>();
        int leng = new int();
        leng = listdecreasing.Count;
        int mobileLeng = 0;
        int randomholder = 0;
        int foundbyrandom = 0;

        for (int counter = 0 ; counter < leng ;counter++)
            mobileLeng = listdecreasing.Count;
            randomholder = UnityEngine.Random.Range(0, mobileLeng);
            foundbyrandom = listdecreasing[randomholder];
        return listfilling;

Welcome to the forums.

Not quite sure what you mean by

…do you mean that the code works after 2 iterations, or that the resultant list is sorted after 2 iterations?

Either way, that approach is not the one I’d use to shuffle an existing list. I’d use a similar method to the one described in the Unity documentation, here (since you’re relying on their Random.Range method):


what I mean is running it one will seem to scramble but running it a second time seems to unscramble it rather than randomly scramble it.


It is relevant for my code that every random possibility is equally weighted so I don’t think a swapping algorithm would work.