Note that there are some explanatory texts on larger screens.

plurals
  1. POSequence of random selection with no two consecutive objects same
    primarykey
    data
    text
    <p>I wanted to write a function which can be subsequently called with a integer parameter (starting from 1 to 100) which randomly gives me an integer 0, 1, or 2 but never two same in a row.</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Random; public class UniqueRandomObjectSelector { //Goal is to select objects from a bucket randomly with teh condition that //no two selections in a row would be same public static void main(String[] args) { for (int i = 0; i &lt; 100; i++) { System.out.println(i + "th random Object is " + selectObject(i) + " "); } } //Pick the object from the pool of 3 . e.g. the bucket contains the numbers 1, 2 and 3 private static int PickObject(int j) { Random rand = new Random(getSeed()); //Find i-1 wala number for (int i = 1; i &lt; j; i++) { rand.nextInt(3); } return rand.nextInt(3); } //Fixed seed so that random number generation sequence is same static long getSeed() { return 11231; } static int selectObject(int index) { //Holds the sequence of Objects List&lt;Integer&gt; list = new ArrayList&lt;&gt;(); int prev = -999; int i = 1; //Keep generating the sequence till we have the requested index of objects while (list.size() &lt;= index) { //Get a random number from fixed seed int ranNum = PickObject(i); //Check if this was same as previous while (prev == ranNum) { ranNum = PickObject(++i); } prev = ranNum; list.add(ranNum); i++; } return (list.get(index)); } } </code></pre> <p>Can this be simplified , looks like I am using too many loops.</p>
    singulars
    1. This table or related slice is empty.
    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. 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