Welcome to Dream.In.Code
Become a Java Expert!

Join 150,385 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,143 people online right now. Registration is fast and FREE... Join Now!




Random Number generation....

 
Reply to this topicStart new topic

Random Number generation....

fahlyn
7 Feb, 2008 - 12:02 PM
Post #1

New D.I.C Head
*

Joined: 3 Nov, 2007
Posts: 43


My Contributions
I need to generate a random integer for a process that I'm working on. I know I could use Math.Random() to do this, however here is where I'm stuck. I've got a list of Integers...they aren't necessarily in any order or within any range of numbers. Basically I need to re-order the list so it is completely random. I'm not sure how to go about doing this...it needs to be very efficient. The only thing I've thought of so far is getting a random number from Math.Random, checking to see if it is in my list, if it is remove it from my list and add it to a new list...and repeat until my old list is empty...it seems like i will potentially generate a lot of extra random numbers that will not be in my list. Any ideas of an efficient way to put a list into a random order?

One thing I have considered is putting each value into a HashMap and looping through the HashMap key by key....but I'm not sure how random that would be since I'd be putting them into the HashMap sequentially and pulling them out sequentially...


This post has been edited by fahlyn: 7 Feb, 2008 - 12:05 PM
User is offlineProfile CardPM
+Quote Post

capty99
RE: Random Number Generation....
7 Feb, 2008 - 12:14 PM
Post #2

the real kya
Group Icon

Joined: 26 Apr, 2001
Posts: 9,259



Thanked: 16 times
Dream Kudos: 550
My Contributions
yeah , thats an excessive way to do it.

you could just build an array of the numbers you have,

and then randomly pick which spot in the array to use.

so if your array has numbers :

5, 13, 29, 55

then your math random picks an int < 4.

and it will randomly pick one of those
User is offlineProfile CardPM
+Quote Post

fahlyn
RE: Random Number Generation....
7 Feb, 2008 - 12:26 PM
Post #3

New D.I.C Head
*

Joined: 3 Nov, 2007
Posts: 43


My Contributions
Yeah, I'm a dork. I literally had that same thought 30 seconds after I posted this. Here's what I'm doing, and it seems to work fine. Sorry to waist your time, thanks.


CODE

        while(ol.size() > 0){
            Random randGen = new Random();
            int rand = randGen.nextInt(ol.size());
            nl.add(ol.remove(rand));
        }

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/9/09 04:54PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month