Reputation: 4323
I have a xml file having 50 different questions and i need only 15 out of them randomly and non-repeated.I used the code below
int n = ((int)(Math.random()*100))%50;
if(temp<15)
{
for(int i=0;i<temp;i++)
{
System.out.println("hello naresh");
if(n==check[i])
{
n=((int)(Math.random()*100))%50;
}
}
check[temp]=n;
}
temp++;
return n;
But by using this some questions are repeated.Please suggest me something which help me to generate the non-repeated questions.
Upvotes: 0
Views: 184
Reputation: 4323
By this way u can generate any no of random no.
int max=50;
List<Integer> indices;
int randomIndex = 0;
random(){
int arrIndex = (int)((double)indices.size() * Math.random());
System.out.println("my random no is:"+arrIndex);
randomIndex = indices.get(arrIndex);
indices.remove(arrIndex);
return randomIndex;
}
Upvotes: 1
Reputation: 11662
Shuffle the numbers 0,1,...49 and take the first 15 numbers:
ArrayList<Integer> indices = new ArrayList<Integer>();
for (int i = 0; i < 50; i++)
indices.add(i);
Collections.shuffle(indices);
List<Integer> random15 = indices.subList(0,15);
It also shuffles the other 35 numbers, a bit of unnecessary work, but for such small numbers it's not a problem.
Upvotes: 1