473,748 Members | 7,377 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Randomize array items

I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?

Cheers,
Steve
Jul 21 '05 #1
2 15020
Fieldmedic <Fi********@dis cussions.micros oft.com> wrote:
I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?


There's no need to use an ArrayList - the size doesn't need to change.

Here's a method which will actually shuffle *any* IList:

static Random rng = new Random();
static void Randomize(IList list)
{

for (int i=list.Count-1; i > 0; i--)

{
int swapIndex = rng.Next(i+1);
if (swapIndex != i)
{
object tmp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = tmp;
}
}
}

The way it works is to mentally divide the list into two halves - the
unshuffled half (in the range [0,i]) and the shuffled half (in the
range [i+1, list.Count-1]).

In each iteration, it picks a random element from the unshuffled half,
and swaps it with the element at the end of the unshuffled half, then
moves the boundary down.

Note that if you're shuffling arrays of value types, you should use a
strongly typed version of the above, changing the declaration of both
list and tmp appropriately, to avoid boxing.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #2
Jon,
Thanks for the input! The reason I was thinking arraylist was because
the "list" of items will actually come from the selected items in a ListBox.
The ListBox connects to a database and the user can select from the items in
it to narrow create the list of items to be randomized. I'll give your code a
shot, although I have to convert it to VB. :)

Thanks again,
Steve
"Jon Skeet [C# MVP]" wrote:
Fieldmedic <Fi********@dis cussions.micros oft.com> wrote:
I'm trying to determine the best way to randomize a set of array items. I'm
thinking that I could use an arraylist and have it use the lower and upper
bounds as the limits. Any suggestions?


There's no need to use an ArrayList - the size doesn't need to change.

Here's a method which will actually shuffle *any* IList:

static Random rng = new Random();
static void Randomize(IList list)
{

for (int i=list.Count-1; i > 0; i--)

{
int swapIndex = rng.Next(i+1);
if (swapIndex != i)
{
object tmp = list[swapIndex];
list[swapIndex] = list[i];
list[i] = tmp;
}
}
}

The way it works is to mentally divide the list into two halves - the
unshuffled half (in the range [0,i]) and the shuffled half (in the
range [i+1, list.Count-1]).

In each iteration, it picks a random element from the unshuffled half,
and swaps it with the element at the end of the unshuffled half, then
moves the boundary down.

Note that if you're shuffling arrays of value types, you should use a
strongly typed version of the above, changing the declaration of both
list and tmp appropriately, to avoid boxing.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #3

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

Similar topics

8
1898
by: knoak | last post by:
Hi there, I have i site with photo-albums on it. to create a new album all i do is create a new folder. I use the following code. My only question is, how can i randomize the output, so the order of the folders is different every time? ++++++++++++++++++++++++++++++++++++++++++++++++++++
21
4178
by: Jeff Thies | last post by:
I'd like to randomly sort an array. A good method?
1
3426
by: Ellen Manning | last post by:
I've got an A2K database with a report that generates any number of random medical record numbers. The user inputs how many numbers they want and report uses the Randomizer function found on "The Access Web" site to generate these numbers. Out of 38000 records, there are 900 unique medical record numbers. I run the randomizer function on a query of these unique medical record numbers. The user states there are too many duplications...
2
343
by: Fieldmedic | last post by:
I'm trying to determine the best way to randomize a set of array items. I'm thinking that I could use an arraylist and have it use the lower and upper bounds as the limits. Any suggestions? Cheers, Steve
4
2228
by: Arnold | last post by:
Hi there, Here's the situation--there is a text field in a form in which students will key in data. On the keypress event, I'd like for different sounds to be played for each character typed, either randomly or in a loop (I have a number of small, cool, computer-like sounds). I can get one sound to play for the keypress event, but don't know how to play multiple sounds. Here's the codes for playing one sound...
1
3767
by: Badass Scotsman | last post by:
Hello, This code is supposed to generate a random string each run, however I have had it live on a few sites, and it seems to create repeat strings all over the place. ------------------------------------------------------------- <% FUNCTION GetRandomCode(randomcode,codelength,numberofcombinations) codecharacters = 35
1
1566
by: Samuel Shulman | last post by:
Any function to randomize strings? thank you, Samuel
6
2402
by: mrtaka79 | last post by:
Okay, first of all, I'm a complete noob, so go easy on me. I have this code that works perfectly for me. The only thing I want to add is to randomize the pictures/links that show up. Can anyone just tell me where to add additional code to the following? BTW this is the only code I could find that works in my Beta Blogger sidebar. <a href="javascript:gotoshow()"><img border="0" width="300" src="/OneMissedCall1.jpg" name="slide"...
5
2898
by: gggram2000 | last post by:
Hi, I'ved spent two full days trying to find a solution, I can randomize numbers between two ranges and it works fine, But my problem is when i want to randomize five numbers that I got. eg. I randomize 1-100 and I get 50. I randomize 1-900 on another input field and I get 578. I randomize 2-56 and get 31. " " and get 43. " " and get 78. So I have five numbers: 50, 578, 31, 43 and 78.
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8828
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9537
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9243
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4599
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3309
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2780
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.