Your algorithm creates a list of up to MAX elements. Each element is an integer from 0 to MAX-1, with no duplicates. Since rand.nextInt(n) returns numbers x uniformly distributed between 0 and n such that 0 <= x < n, x >= 100-p should be always false if p == 0 (x is never 100), and always true if p == 100 (x is always >= 0). The expected number of elements is therefore MAX*(p/100.0).
This can be improved significantly if MAX is high but p is low: in most cases, you would be throwing your weighted coin, but it would come up tails and you would not add anything. Wasted work. If, however, p is high (say, over .5), then you will typically be generating on-the-order-of MAX elements; and it is unlikely that you can make things much faster (you should expect to do O(MAX) work to create O(MAX) random elements). If MAX is small, there's little difference between approaches - so I would stick to the simpler one: the one you already have.
Assuming large MAX and small p
We can model the length of the list using the well-known binomial distribution (as you are throwing MAX non-fair coins, which land "heads" with probability p). Java code is available in the Colt library. Using their classes, this should work:
Binomial b = new Binomial(MAX, p, new MersenneTwister()); int heads = b.nextInt();
And now we need to generate "heads" sorted integers between 0 and MAX-1. Let us assume that MAX is much larger than heads. We can use
TreeSet<Integer> chosen = new TreeSet<>(); for (int i=0, r=0; i<heads; i++) { do { r = random.nextInt(MAX) } while (chosen.contains(r)); chosen.add(r); }
Note that this has horrible performance when p is high, because the inner loop will be executed several times; but for such cases, your initial algorithm is already good enough.
When p is low, the proposed algorithm will require time proportional to MAX*(p/100) instead of MAX. This should more than compensate for the cost of maintaining the TreeSet ordered.
probablityand 100. Second, you're not really iterating over every number between0andMAX, the code triesMAXtimes to generate a number. If you want to do something X times there has to be a loop somewhere.ito the list. Thanks for the correction.