The first big problem with your code is that you're creating two instances of Random
. The crappy seeding of new Random()
means that those instances will most likely return exactly the same sequence.
new Random()
seeds using Environment.TickCount
, which only changes every few milliseconds. So if you create two instances of Random
in quick succession, the time will be the same and thus they output the same sequence.
The proper solution is to create only one instance of Random
at the beginning, and use if for all your randomness needs. Just be careful about multi-threading, instances of Random
are not thread-safe.
Also note that the upper bound of random.Next
is exclusive, so your code will work only on arrays with 11 elements. It's better to use the collection size instead of hardcoding the value.
Another problem with your code is that you didn't implement a proper swap. To swap you need to your swap has two issues: You're using new indices for the second direction, and you don't create a temporary copy in a local variable to avoid reading the overwritten value, instead of original one.
With these issues fixed your code looks like this:
Random random = new Random();//one persistent instance
public void shuffle()
{
for (int i = 0; i < 100000; i++)
{
var i1=random.Next(kaarten.Count);
var i2=random.Next(kaarten.Count);
var temp=kaarten[i1];
karten[i1]=kaarten[i2];
karten[i2]=temp;
}
}
That said, your approach is a bit inefficient, since you iterate 100000 times. The standard shuffling algorithm is a Fisher-Yates shuffle which Jon-Skeet describes at Is using Random and OrderBy a good shuffle algorithm?.