Reputation: 499
So the idea here is that I have an ArrayList with a set of words, I want to sort the list so that it only includes entries with even numbered indecies and then picks out an entry at random. I gave this a bash and I managed to get it to show only odd entries like so:
int i = 0;
for (Iterator<Phrase> it = phrases.iterator(); it.hasNext(); i++)
{
Phrase current = it.next();
if (i % 2 == 0)
{
System.out.println(current);
}
}
And this prints off every odd numbered element on the ArrayList which is fine, but I don't know how to select one at random from the odd numbered ones. This is what I tried putting into the if statement but it doesn't do what I want it to, it does print off the elements at random but it also includes the odd numbered elements when I only want the even ones
Random r = new Random();
int x = r.nextInt(phrases.size());
System.out.println(phrases.get(x));
Any help would be very appreciated here, thanks.
Upvotes: 0
Views: 230
Reputation: 15408
but I don't know how to select one at random from the odd numbered ones.
what about ensuring x
to be half of the size and multiply it with 2
to have the even index. Try the following:
Random r = new Random();
int x = r.nextInt(phrases.size()/2) + (list.size() & 1) - 1;
// size is divided by 2
// so that x is randomly 0 to (size/2 -1) inclusive
System.out.println(phrases.get(x * 2)); // ensuring the accessing index are even
Upvotes: 1
Reputation: 3767
You could loop until you get one, but technically, that may never happen. So instead, just make sure x is a multiple of 2.
Random r = new Random();
int x = r.nextInt(phrases.size()); // Might be even or odd
x = x % 2 != 0 ? x + 1 : x; // if x is not divisible by 2, x + 1, else x
// x is is now a multiple of two
if(x >= phrases.size()){ // make sure x is still within the
// index boundaries.
x = x-2;
if(x < 0){
x = 0;
}
}
System.out.println(phrases.get(x));
Upvotes: 0