473,573 Members | 2,716 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Shuffle a Collection

Hi everyone,

I have to write a function to shuffle a collection. If anyone has any idea
on how to implement it please share with me.

The signature of function is:
ICollection Shuffle(ICollec tion c);

Thanks.

AM
Aug 30 '07 #1
4 7657
I have already implemented it, any comments/suggestions on my implementation
are welcome:
----------------------------------------------------------------------
public static ICollection Shuffle(ICollec tion c) {
if (c == null || c.Count <= 1) {
return c;
}

byte[] bytes = new byte[4];
RNGCryptoServic eProvider cRandom = new RNGCryptoServic eProvider();
cRandom.GetByte s(bytes);

int seed = BitConverter.To Int32(bytes, 0);
Random random = new Random(seed);

ArrayList orig = new ArrayList(c);
ArrayList randomized = new ArrayList(c.Cou nt);
for (int i = 0; i < c.Count; i++) {
int index = random.Next(ori g.Count);
randomized.Add( orig[index]);
orig.RemoveAt(i ndex);
}
return randomized;
}
------------------------------------------------

Thanks.

AM
"Aamir Mahmood" <aa**********@g mail.comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
Hi everyone,

I have to write a function to shuffle a collection. If anyone has any
idea on how to implement it please share with me.

The signature of function is:
ICollection Shuffle(ICollec tion c);

Thanks.

AM

Aug 30 '07 #2
Aamir Mahmood wrote:
I have to write a function to shuffle a collection. If anyone has any idea
on how to implement it please share with me.

The signature of function is:
ICollection Shuffle(ICollec tion c);
2.0+ style:

public class Util<T>
{
private static Random rng = new Random();
public static ICollection<TSh uffle(ICollecti on<Tc)
{
T[] a = new T[c.Count];
c.CopyTo(a, 0);
byte[] b = new byte[a.Length];
rng.NextBytes(b );
Array.Sort(b, a);
return new List<T>(a);
}
}

1.x style:

public class Util
{
private static Random rng = new Random();
public static ICollection Shuffle(ICollec tion c)
{
object[] a = new object[c.Count];
c.CopyTo(a, 0);
byte[] b = new byte[a.Length];
rng.NextBytes(b );
Array.Sort(b, a);
return new ArrayList(a);
}
}

Arne
Aug 30 '07 #3
On Aug 30, 3:08 am, Arne Vajhøj <a...@vajhoej.d kwrote:
Aamir Mahmood wrote:
I have to write a function to shuffle a collection. If anyone has any idea
on how to implement it please share with me.
The signature of function is:
ICollection Shuffle(ICollec tion c);

2.0+ style:
<snip>

Shuffling by sorting is going to be (at best) O(n log n). It's fairly
easy to do it as O(n)... admittedly it's more code, but for large
collections it could be significant.

Jon

Aug 30 '07 #4
Jon Skeet [C# MVP] wrote:
On Aug 30, 3:08 am, Arne Vajhøj <a...@vajhoej.d kwrote:
>Aamir Mahmood wrote:
>>I have to write a function to shuffle a collection. If anyone has any idea
on how to implement it please share with me.
The signature of function is:
ICollection Shuffle(ICollec tion c);
2.0+ style:

<snip>

Shuffling by sorting is going to be (at best) O(n log n). It's fairly
easy to do it as O(n)... admittedly it's more code, but for large
collections it could be significant.
True.

The advantage of the sorting method is that the methods validity
is rather obvious.

Arne
Sep 1 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
12917
by: JC | last post by:
I am very new to programming and learning on my own. Why do I keep getting duplicate values using this code? I want to shuffle a deck of 52 cards. The logic seems right to me. Randomize For C = 0 To 1000 C1 = Cards(Int(Rnd * 52)) ' returns a number from 0 to 51
24
7269
by: Joerg Schuster | last post by:
Hello, I am looking for a method to "shuffle" the lines of a large file. I have a corpus of sorted and "uniqed" English sentences that has been produced with (1): (1) sort corpus | uniq > corpus.uniq corpus.uniq is 80G large. The fact that every sentence appears only
3
3154
by: songie D | last post by:
If you remove an item from a collection (that is derived from CollectionBase and thus implements IList will the index property automatically 'shuffle' up one i.e. if of {0, 1, 2, 3} I delete item 2, then will I be left with {0, 1, 2} or {0, 1, 3} Basically I am implementing a custom collection and wondered if I could rely o the fact that...
9
5329
by: Tuxedo | last post by:
I'd like to reorganize the third, fourth, fifth and sixth, as well as any elements thereafter in an array in random order: var a = new Array('first','second','third','fourth','fifth','sixth','etc') In other words, the first, second and third element should remain in position 0, 1 and 2, while the fourth, fifth and sixth, etc. should appear...
25
2626
by: tooru honda | last post by:
Hi, I have read the source code of the built-in random module, random.py. After also reading Wiki article on Knuth Shuffle algorithm, I wonder if the shuffle method implemented in random.py produces results with modulo bias. The reasoning is as follows: Because the method random() only produces finitely many possible results, we get...
84
3465
by: jacob navia | last post by:
As many people know, I think that garbage collection is a good solution for many memory allocation problems. I am aware however, that nothing is "the silver bullet", not even the GC. A recent article in slashdot http://developers.slashdot.org/article.pl?sid=07/11/17/0552247 proves that.
11
12963
by: whodgson | last post by:
I`m trying to write a shuffle function to shuffle a sorted array with an even number of elements but it won`t print past the first 2 elements as shown below. When i print the temp array it only prints the first 2 elements also. So i presume the loop is is stopping after 2 iterations. Can anyone see my error?. #include<iostream> using...
0
209
by: =?ISO-8859-1?Q?Arne_Vajh=F8j?= | last post by:
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> {
1
1800
by: anjkris07 | last post by:
I've been studying java for a week now. I have a project that needed to display a deck of cards and shuffle them alternately (like cutting the deck then insert each card). Then deal it, much like the war game of cards. I'm just still on the shuffle stage but the the deck remains the same even after shuffling. I think my codes got problem with the...
0
7668
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7986
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8179
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7736
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8036
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5556
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3701
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3699
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
999
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.