1

I'm trying to get five random numbers printed that never repeat, based on a certain range provided by the user. Posted below is the code I have so far. I asked a similar question last night and got some great answers, but now I'm trying to accomplish this using only arrays and loops. Thanks.

package h1p2;

public class test{
    public void method (int min, int max){
        //Declare and initialize arrays and index variables
        int rangeOne[];
        int rangeMinMax[];
        rangeOne = new int[5];
        rangeMinMax = new int[max - min];
        int z = min;
        int i = 0;
        int q = 0;
        int rangeLength = rangeMinMax.length;



        //need minimum/max differential of 50 or > to execute method
        if (max - min < 50){
            System.out.println("Please enter numbers with a differential of 50 or greater.");
        }

        //run if differential checks out
        else{
            //populate MinMax array with range specified by user
            while (i < rangeLength){
                rangeMinMax[i] = z;
                z++;
                i++;
            }
        }

        //pick random number from MinMax array
        int randomNumber = (rangeMinMax[(int) (rangeLength * Math.random())]);
        int r = 0;
        //populate rangeOne array with lotto numbers, forbidding duplicates
        while (r < 5){
            randomNumber = (rangeMinMax[(int) (rangeLength * Math.random())]);
            rangeOne[r] = randomNumber;
            randomNumber = (rangeMinMax[(int) (rangeLength * Math.random())]);
            if (r == 1 && randomNumber == rangeOne[0]){
                r--;
            }

            if (r == 2 && (randomNumber == rangeOne[0] || randomNumber == rangeOne[1])){
                r--;
            }

            if (r == 3 && (randomNumber == rangeOne[0] || randomNumber == rangeOne[1] || 
                    randomNumber == rangeOne[2])){
                r--;
            }

            if (r == 4 && (randomNumber == rangeOne[0] || randomNumber == rangeOne[1] || 
                    randomNumber == rangeOne[2] || randomNumber == rangeOne[3])){
                r--;
            }
            else{
            r++;}
        }

        //create string with results
        String results = Integer.toString(rangeOne[0]) + " " + Integer.toString(rangeOne[1])
                + " " + Integer.toString(rangeOne[2]) + " " + Integer.toString(rangeOne[3]) +
                " " + Integer.toString(rangeOne[4]);

        //print results
        System.out.println("MegaNumbers: " + results);
    }

}
7
  • If you want to avoid doubles, I would have used a hashmap or a set, and simply loop until the length reaches target number (ie, 5). Commented Feb 7, 2014 at 21:17
  • Yeah, I've accomplished that much, but I'm just trying to figure out a way doing it only using loops and arrays (just to learn the logic). thanks. Commented Feb 7, 2014 at 21:18
  • possible duplicate of How do I get a list of five random numbers to be printed without duplicates in Java? Commented Feb 7, 2014 at 21:21
  • 1
    Start by implementing set. Proceed from there. This is an OO language, after all. Commented Feb 7, 2014 at 22:08
  • 1
    How can you learn the logic if we keep providing all the answers and code for you? Do you really want to learn the logic, or can you just not use a set for your homework assignment? Commented Feb 7, 2014 at 22:11

2 Answers 2

2

If all you need is a small amount of numbers, just use a linear search to simulate a set. Then keep generating random numbers until you've generated enough unique ones to suffice. Obviously this isn't the most efficient, but it is simple.

private static Random rand = new Random();

public static boolean contains(int [] data, int value)
{
    for (int i = 0; i < data.length; i++)
    {
        if (data[i] == value)
        {
            return true;
        }
    }

    return false;
}

public static int[] getRandom(int size, int lowerBound, int upperBound)
{
    if (upperBound - lowerBound <= size)
    {
        throw new IllegalArgumentException("Range is too small!");
    }

    int totalRandoms = 0;

    int[] randoms = new int[size];

    while (totalRandoms != size)
    {
        int randNumber = rand.nextInt(upperBound - lowerBound) + lowerBound;
        if (! contains(randoms, randNumber))
        {
            randoms[totalRandoms] = randNumber;
        }
    }

    return randoms;
}

P.S. I've left some of the details up to you, I've just included a couple non-OO functions to give you a feel for a possible algorithm.

Sign up to request clarification or add additional context in comments.

Comments

1

I wrote randomList() to accept three parameters:

1) the minimum random value

2) the maximum random value

3) and the number of random values the array should have.

The method first creates an array called choices filled with all the values from the min value to max value. It then starts a loop that fills a new array with values from choices. Whenever the loop chooses a random value from choices, it moves that value to the back of the choices array and updates lastIndex so it doesn't choose any values from the back of choices anymore.

An easier way to do this would be to make choices an ArrayList and simply delete the already taken values from it. But because we can't use ArrayLists, this code should work fine.

public static int[] randomList(int min, int max, int number) {
    // fills an array with all numbers from min to max
    int[] choices = new int[max - min + 1];
    int lastIndex = choices.length - 1;
    for(int i = min; i <= max; i++) {
        choices[i - min] = i;
    }

    // fills the new array with values from choices
    Random r = new Random();
    int[] randomList = new int[number];
    for(int i = 0; i < number; i++) {
        int index = r.nextInt(lastIndex + 1); 
        randomList[i] = choices[index];
        int copy = choices[lastIndex];
        choices[lastIndex] = randomList[i];
        choices[index] = copy;
        lastIndex--;
    }
    return randomList;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.