Home > Mobile >  Shuffle in same order
Shuffle in same order

Time:12-13

I have a list of sprites and list of strings. I would like to shuffle this. The shuffle works but differently for both sprites and strings. Can the order of the shuffle for both be the same?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ShuffleList : MonoBehaviour
{
    public List<Sprite> iconSprite = new List<Sprite>();
    public List<string> priceText = new List<string>();

    // Start is called before the first frame update
    void Start()
    {
        iconSprite.Shuffle();
        priceText.Shuffle();
    }

}

public static class IListExtensions {
    /// <summary>
    /// Shuffles the element order of the specified list.
    /// </summary>
    public static void Shuffle<T>(this IList<T> ts) {
        var count = ts.Count;
        var last = count - 1;
        for (var i = 0; i < last;   i) {
            var r = UnityEngine.Random.Range(i, count);
            var tmp = ts[i];
            ts[i] = ts[r];
            ts[r] = tmp;
        }
    }
}

CodePudding user response:

You need to shuffle both lists at once. So instead of an extension-method that only has a single parameter, just use a normal method having two lists as params.

public static void Shuffle<T1, T2>(IList<T1> list1, IList<T2> list2) 
{
    var count = ts.Count;
    var last = count - 1;
    for (var i = 0; i < last;   i) {
        var r = UnityEngine.Random.Range(i, count);
        var tmp1 = list1[i];
        var tmp2 = list2[i];
        list1[i] = list1[r];
        list1[r] = tmp1;
        list2[i] = list2[r];
        list2[r] = tmp2;
    }
}

Alternativly you can also use the same seed for the random-generator, which will lead to identical sequences being generated:

public static void Shuffle<T>(this IList<T> ts, long seed) 
{
    UnityEngine.Random.InitState(seed);
    var count = ts.Count;
    var last = count - 1;
    for (var i = 0; i < last;   i) {
        var r = UnityEngine.Random.Range(i, count);
        var tmp = ts[i];
        ts[i] = ts[r];
        ts[r] = tmp;
    }
}

Now you can provide the same seed for both calls to the function, e.g.:

void Start()
{
    var seed = Datetime.Now.Ticks;
    iconSprite.Shuffle(seed);
    priceText.Shuffle(seed); // use the exact same seed again to produce the same random sequence
}
  • Related