Repeated random sorting of an array using a key is required

I want to randomly shuffle a list / array with a key. I want to be able to repeat the same random order using the key.

So, I will randomly generate a numeric key from 1 to 20, and then use this key to randomly shuffle the list.

At first, I tried just using the key to continue iterating through my list, decreasing the key to = 0, and then capturing any element that I work on, deleting it and adding it to my shuffled array. The result is random, but when the arrays are small (which will be most of mine) and / or the key is small, it does not end with shuffling ... it seems more like a shift.

I need to determine what order

Here is a sample code in csharp:

public static TList<VoteSetupAnswer> ShuffleListWithKey(TList<VoteSetupAnswer> UnsortedList, int ShuffleKey)
    {
        TList<VoteSetupAnswer> SortedList = new TList<VoteSetupAnswer>();
        int UnsortedListCount = UnsortedList.Count;
        for (int i = 0; i < UnsortedListCount; i++)
        {
            int Location;
            SortedList.Add(OneArrayCycle(UnsortedList, ShuffleKey, out Location));
            UnsortedList.RemoveAt(Location);
        }
        return SortedList;
    }

    public static VoteSetupAnswer OneArrayCycle(TList<VoteSetupAnswer> array, int ShuffleKey, out int Location)
    {
        Location = 0;
        if (ShuffleKey == 1)
        {
            Location = 0;
            return array[0];
        }
        else
        {
            for (int x = 0; x <= ShuffleKey; x++)
            {
                if (x == ShuffleKey)
                    return array[Location];
                Location++;
                if (Location == array.Count)
                    Location = 0;
            }
            return array[Location];
        }
    }
0
2

, RNG .

 /**
     * Randomly permutes the array of this permutation. All permutations occur with approximately equal
     * likelihood. This implementation traverses the permutation array forward, from the first element up to
     * the second last, repeatedly swapping a randomly selected element into the "current position". Elements
     * are randomly selected from the portion of the permutation array that runs from the current position to
     * the last element, inclusive.
     * <p>
     * This method runs in linear time.
     */
    public static void shuffle(Random random, int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            swap(a, i, i + random.nextInt(a.length - i));
        }
    }
+1

- Fisher-Yates. . , . . .

linq:

var key=0;
var r=new Random(key);
myList.OrderBy(x=>r.Next());

key, .

0

Source: https://habr.com/ru/post/1734354/


All Articles