0

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.

aditya
  • 339
  • 2
  • 12
  • 1
    Does the following link help: http://stackoverflow.com/questions/124671/picking-a-random-element-from-a-set – steveb Aug 11 '16 at 07:55

1 Answers1

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 Lists 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