Long time without posting.
Too many things happened in my life during that time but it's not topic for this blog, then,
what about code this time?
what about code this time?
Simple put, I needed shuffle a simple List in C# and I was not able to find some easy way over the internet, so I spent some minutes to create my own way, a small handly function to shuffle IList, use it, enjoy it and improve it (in this case, just let me know how to do it better).
long life and stay creative!
void Shuffle<T>(ref List<T> t)
{
//create a temporary empty list
List<T> tmp = new List<T>();
System.Random rand = new System.Random();
//create a temporary index list
List<int> indexList = new List<int>();
for (int j = 0; j < t.Count; ++j)
indexList.Add(j);
while (indexList.Count > 0)
{
int k = rand.Next(0, indexList.Count - 1);
// Console.WriteLine("index: " + indexList[k] + " content: " + t[indexList[k]]);
tmp.Add(t[indexList[k]]);
indexList.RemoveAt(k);
tmp.Reverse ();
}
t = new List<T>(tmp);
return;
}
void Shuffle<T>(ref List<T> t)
{
//create a temporary empty list
List<T> tmp = new List<T>();
System.Random rand = new System.Random();
//create a temporary index list
List<int> indexList = new List<int>();
for (int j = 0; j < t.Count; ++j)
indexList.Add(j);
while (indexList.Count > 0)
{
int k = rand.Next(0, indexList.Count - 1);
// Console.WriteLine("index: " + indexList[k] + " content: " + t[indexList[k]]);
tmp.Add(t[indexList[k]]);
indexList.RemoveAt(k);
tmp.Reverse ();
}
t = new List<T>(tmp);
return;
}