Adam Sandler wrote:
The following code does both array and collection.
It is not the most efficient way of doing it, but the
algorithm is easy to understand.
public class Util<T>
{
private static Random rng = new Random();
public static T[] Shuffle(T[] a)
{
T[] a2 = (T[])a.Clone();
int[] b = new int[a.Length];
for(int i = 0; i < b.Length; i++) b[i] = rng.Next();
Array.Sort(b, a2);
return a2;
}
public static ICollection<TSh uffle(ICollecti on<Tc)
{
T[] a = new T[c.Count];
c.CopyTo(a, 0);
return new List<T>(Shuffle (a));
}
}
Arne
I have a question about sorting a collection randomly. All the items
in the collection are unique.
in the collection are unique.
The problem is, the sorted array can now contain duplicates! I'm
assuming the problem can come from using Random, which isn't
guaranteed to provide a unique number every time.
>
How do I sort an array randomly where the array items should remain
unique and I don't introduce duplicate items?
assuming the problem can come from using Random, which isn't
guaranteed to provide a unique number every time.
>
How do I sort an array randomly where the array items should remain
unique and I don't introduce duplicate items?
It is not the most efficient way of doing it, but the
algorithm is easy to understand.
public class Util<T>
{
private static Random rng = new Random();
public static T[] Shuffle(T[] a)
{
T[] a2 = (T[])a.Clone();
int[] b = new int[a.Length];
for(int i = 0; i < b.Length; i++) b[i] = rng.Next();
Array.Sort(b, a2);
return a2;
}
public static ICollection<TSh uffle(ICollecti on<Tc)
{
T[] a = new T[c.Count];
c.CopyTo(a, 0);
return new List<T>(Shuffle (a));
}
}
Arne