Given a set X, using java how do I pick two random items from it so that i could maybe increment one item and decrement the other at the same time. Thank you in advance.
Asked
Active
Viewed 101 times
1 Answers
0
I'd check the size of the set, and then randomly choose two "indexes" below it. Not that Set
elements in java don't have real indexes, of course (at least not in the sense that List
s have them, with a get(int)
method, but this behavior can be simulated by iterating over the Set
and counting the number of steps):
Set<Object> set = ...;
Random random = new Random(); // or some better RNG
int size = set.size();
int step1 = rand.nextInt(size - 1);
int step2 = rand.mextInt(size - step1);
Iterator<Object> iter = set.iterator();
for (int i = 0; i < step1 - 1; ++i) {
iter.next();
}
Object rand1 = iter.next();
for (int i = 0; i < step2 - 1; ++i) {
iter.next(); // Note, this is the SAME iterator!
}
Object rand2 = iter.next();

Mureinik
- 297,002
- 52
- 306
- 350