hi i'm stuck in a situation, i want to pick 10 random elements at a time from a vector.what i have done so far is, i generate a random number uses the generated random number as the index of the element be picked the element from the vector. Now my problem i don't want to pick the element which has already been picked and i know it does that because the indexes being generated repeats due to the random number i'm generating. To get view what i'm really talking about i'm posting a code. Please how do i avoid element already selected. Thanks
i would shuffle the List/Vector then pick the 10 (or any other number) elements starting at index 0 (of course you need to have at least 10 elements in the List then). Look at java.util.Collections for shuffling and at the List.subList() method for creating a sub list (picking the first 10 elements)
This might not be the most performant solution but you can write it in two or three lines.
if you want to do this without shuffling then you need to create "unique" random numbers:
this might be inefficient to (when the number of items you want to pick is close to the number of total items in the list the "algorithm" is not so smart :-) )
Joined: Feb 26, 2005
no is not an assignment. Random number generation was what came to mind the first time i thought about how to solve it. I will be trying all what has been said and will post code when i'm stack. Thanks
The man who makes no mistakes does not usually make anything<br /> <br />>>> SCJP 5.0 >> SCJD B&S <<< In progress
Joined: Jun 19, 2001
Arno, i think that's what he did. He created random numbers (and each number would be the index to an element in a List) but he does not want the same index more than once therefore you need to remember what numbers were generated before (or he will pick the same element from the List more than once).
i realised where the problem was lying. i found out that when the button is clicked to call the "pickNumber" function, a new instance of the array to be passed to the "pickNumber" function is created so the element that i remove from the vector does goes away but a new but the same element are added to vector. To solve this, i created a new function that accepts a vector, then a randomly element is remove from that vector. in the actionPerform method i set a counter, when the counter is zero it should call the pickNumber other wise it should call the second function i created which accepts the vector created in the pickNumber funtion. To really explain the english, here is the code
This is not smart enough for me if you think there is a better way of doing this please advice
[ July 28, 2006: Message edited by: Henry Addo ]
[ July 28, 2006: Message edited by: Henry Addo ] [ July 28, 2006: Message edited by: Henry Addo ]
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com