Java - Get Random Object

Associate
Joined
8 Mar 2007
Posts
88
Hi there,

I have a class which i'll call MyNumbers which basically lets you create an object which is a number with an odd even flag.

Now i have another class which needs to create a range of these numbers and then choose a random odd or even number from the list and remove it.

I originally thought i could store these in an ArrayList but am unsure how i would go about selecting a random odd or even.

Should i be using some other structure to store it?

Any help would be greatly appreciated.

Jon
 
Use a random number generator to get a specific element in the array, use the get() method to assign the random element to a temp variable then use the remove() method to delete the element from the arraylist
 
Hm nah it's not really what i'm looking for.

Let's say you have in the arraylist:

1 - odd
2 - Even
3 - Odd
4 - Even

If the program required an odd it could randomly select from 1 and 3 and then remove said element.

I was thinking because i'd made a MyNumber class i could search the objects based on one of the variables.
 
Here you go in semi-pseudo code. I think this should do what you want it to. Unless I misunderstand what you require. Requires that you store them in odd,even,odd etc.. in your data struct.

Code:
bool even = true; // Set to false to look for odd.

int selection = random(0-array.length) // Generate a random number 

if ((selection % 2 == 0) && even) // Its even and looking for even
{
                get(selection)
}
else if ((selection % 2 == 0) && !even) // Its even and looking for odd
{
               get(selection+1) // Get the next item (i.e odd)
}
else // Its odd return odd.
{
              get(selection);
}
 
In that case either use two array lists, one for odd numbers and one for even our stick the code for the code for removing an element in a do-while loop. Keep checking the odd/even variable of the randomly choosen element until you get one you want.
 
Thanks for the suggestions.

Thanks Una, i thought about that but if i removed an element the array could be left:

13456 which is odd odd even odd even:

So that wouldn't work.

The 2 arraylists is a good idea. Either select random from odd or select random from even.

Thanks again.
 
Back
Top Bottom