Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>From the requirements you've given, I would personally just use a medium-quality random number generator that you know won't produce duplicates within the number of unique numbers that you require. Unless you have an extra requirement you haven't mentioned, it seems overkill to keep the set of all the previously generated numbers.</p> <p>For example, using a 32-bit XORShift generator will produce all 2^31 negative 4-byte integers in "random" order before repeating the pattern. If you need more numbers than that, you probably don't want to be putting them in a hash set anyway. So something like this (warning: off-top-of-head untested code...):</p> <pre><code>int seed = (int) System.nanoTime(); final int origSeed = seed; public int nextUniqueNegativeNumber() { int n = seed; do { n ^= (n &lt;&lt; 13); n ^= (n &gt;&gt;&gt; 17); n ^= (n &lt;&lt; 5); seed = n; if (n == origSeed) { throw new InternalError("Run out of numbers!"); } } while (n &gt; 0); return n; } </code></pre> <p>I'll leave it up to the reader to convert "seed" to use an AtomicInteger if concurrency is necessary...</p> <p>Edit: actually, to optimise the concurrent case you maybe only want to write back to "seed" after getting the next <em>negative</em> number.</p> <p>OK, by popular demand, the atomic version would then be something like this:</p> <pre><code> AtomicInteger seed = new AtomicInteger((int) System.nanoTime()); public int nextUniqueNegativeNumber() { int oldVal, n; do { do { oldVal = seed.get(); n = oldVal ^ (oldVal &lt;&lt; 13); // Added correction n ^= (n &gt;&gt;&gt; 17); n ^= (n &lt;&lt; 5); } while (seed.getAndSet(n) != oldVal); } while (n &gt; 0); return n; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload