Hi, I need to generate 10 random numbers without repeating the same number again. This is what I need to achieve: I have a set of 100 questions and each time the test taker wants to take a test, the program should generate 10 questions from the available 100 question set. So, far i am able to generate random numbers without zero in the following way. But, how to avoid repeating the same number again? Any ideas or code will be appreciated.
public class RandomTest { public static void main(String args[]) { Random generator = new Random(); int rnumber = generator.nextInt( 100 )+1; // what is the code to eliminate the repetition...? System.out.println("Random Number: "+ rnumber);
What about using some kind of Collection? You can check to see if a Collection already contains an element.
KiranKumar Gogineni
Greenhorn
Joined: May 23, 2006
Posts: 9
posted
0
I am a newbie to Collections. Could you please outline the psuedocode or approximate code so that I can explore the exact collection and try to implement? Thanks for your idea. Regards, Kiran
Michael Dunn
Ranch Hand
Joined: Jun 09, 2003
Posts: 4632
posted
0
> I have a set of 100 questions
use Collections.shuffle(..) to mix 'em up, then take the first 10 from your set
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
Alternatively, you can take advantage of the fact that collections that implement the Set interface don't allow duplicates:
[ May 23, 2006: Message edited by: Garrett Rowe ]
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Thanks a lot for your ideas. I will try to implement it. In the meanwhile, if anybody happened work on this kind of logic, please send me the code snippet that uses collections. Regards, Kiran
Michael Dunn
Ranch Hand
Joined: Jun 09, 2003
Posts: 4632
posted
0
here's a simple shuffle
Garrett Rowe
Ranch Hand
Joined: Jan 17, 2006
Posts: 1295
posted
0
And here's an example using a Set
Mallesham Karnati
Ranch Hand
Joined: May 11, 2005
Posts: 40
posted
0
Kiran, Try this. It will serve your purpose.
import java.util.*; class ShuffleTest {
public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>();
for(int x = 1; x < 101; x++) { list.add(Integer.valueOf(x)); //Adds 100 numbers to the list } Collections.shuffle(list); //This shuffles the list
for(int x = 0, y = 11; x < y; x++) { System.out.println(list.get(x)); //This gets the first 10 from the list } }
}
KiranKumar Gogineni
Greenhorn
Joined: May 23, 2006
Posts: 9
posted
0
Thank you very much guys for your quick help. Thanks a lot. Kiran