mardi 26 juillet 2016

Compare a New Array Entry to all its Ancestors

I'm attempting to create an array composed of unique random integers. The method I've constructed, shown below, will almost work. The problem is in the while loop, that compares the new random entry to its immediate ancestor. This condition ensures that there will not be a pair of matching values, side-by-side, in the array. Unfortunately this condition does not compare the new random value to every random value generated thus far. How can I accomplish this?

private static Random rand = new Random();

//'dynamicLength' is dependent on another object. With the way I've set up the 
//method, the size shouldn't matter.
private static int[] randArr = new int[dynamicLength];

public static int[] randGenArr(int upBound, int lowBound)
{
    int newRand;

    for (int i1 = 0; i1 < randArr.length; i1++)
    {
       //new random value
       newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;

       //walk through the randArr up to the point we initialized
       //last iteration
       for (int i2 = 0; i2 <= i1; i2++)
       {
           //compare the new value to its IMMEDIATE ancestor
           while (newRand == randArr[i2])
           {
               newRand = rand.nextInt(upBound - lowBound + 1) + lowBound;
           }
       } 
       //after validation, initialize randArr          
       randArr[i1] = newRand;
   }

   return randArr;
}

I'm only focused on the body of this code. I've included the method header and the field declarations for clarity.




Aucun commentaire:

Enregistrer un commentaire