java - Generating unique random number is increasing complexity and might cause performance overhead? -
implementation:
private static list<integer> getrandomdistribution(list<string> unsortedlist, int max) { random random = new random(); list<integer> indexcontainer = new arraylist<>(); (int = 0; < max; i++) { int index = random.nextint(max); // below don't like, if (indexcontainer.contains(index)) { i--; } else { indexcontainer.add(index); } } return indexcontainer; }
so saying that, until don't find required unique random number. continue loop, happen might keep looping long time increasing overhead.
problems:
- int index = random.next(max) should decide randomness, have maintain ordering. why have used list
- secondly, i-- stuck, because frankly don't implementation.
note: have maintain order within indexcontainer.
since generating permutation of numbers 0 max-1
, make more sense populate list numbers 0 max-1
, call collections.shuffle(list)
.
random random = new random(); list<integer> indexcontainer = new arraylist<>(); (int = 0; < max; i++) { indexcontainer.add(i); } collections.shuffle(indexcontainer, random);
Comments
Post a Comment