Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Right now, you're seeding the RNG and pulling the entire sequence every time you want a number. You don't need to do that. Instead, give <code>rand</code> a wider scope. That way you can reuse it each time you want to get a number.</p> <p>This makes things simpler because you don't need to iterate over the list each time, so you don't have to build the list <em>at all</em>. That means you no longer have to loop in <code>pickNumber()</code>, and most of what you have in <code>selectObject()</code> is obsolete also. </p> <p>Not only is this <em>simpler</em>, but it's also <em>faster</em>. Instead of looping/generating the whole list each time, you only have to grab a couple numbers until you have a good one. On average, this will be <code>4/3</code> tries per call, since about a third will be duplicates.</p> <p>Try something like this instead:</p> <pre><code>public class UniqueRandomObjectSelector { int seed = 11231; int prev = -1; int range = 3; Random rand; int[] values; int maxIndex = 1000; public static void main(String[] args) { /// to generate value 37 on the fly System.out.println("37th value is " + selectObject(37)); /// to print 1000 in order (and store them in an array) rand = new Random(seed); list = new int[maxIndex+1]; for (int i = 0; i &lt;= maxIndex; i++) { values[i] = getRandomNonRepeating(); System.out.println(i + "th random value is " + values[i]); } /// to get value 37 from values[] System.out.println("37th value is " + values[37]); } static int selectObject(int index){ rand = new Random(seed); int value = -1; for(int i=0; i&lt;=index; i++) value = getRandomNonRepeating(); return value; } static int getRandomNonRepeating() { int next = -1; while(next == prev || next &lt; 0){ next = rand.nextInt(range); } prev = next; return next; } } </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. This table or related slice is empty.
    1. 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