lemmetry
lemmetry

Reputation:

Java Challenge for beginners: Generate random numbers in a while loop

This challenge taken from chapter 4 "Java Programming For Absolute Beginners" by Joseph P. Russell.

Write a while loop that generates random numbers between 1 and 100 and stops looping after it generates the same number twice.

My largest concern is that I can't figure out how to keep initializing an array (if you use arrays here at all) because I don't know the size of an array (if that makes any sense).

Can I get some guidance?

Upvotes: 1

Views: 2354

Answers (5)

Jordan
Jordan

Reputation: 32552

Seems to me like the logic would be to initialize a 100-length array, as well as a zero-indexed counter variable. while true, create a random round number between 1 and 100. Check the index of the generated number in the array. If not found, then add the number and increment your counter.

The following is pseudo code.

int nums[] = new int[100];
counter = 0;
while(true) {
    test = random(1, 100);
    if(nums.indexOf(test) != -1) {
        return;
    }

    nums[counter] = test;
    counter++;
}

Upvotes: 0

theMike
theMike

Reputation:

boolean yourLoop = true;
    //you'll need to import java.util.ArrayList;
    ArrayList yourNumber = new ArrayList();

    //condition so your loop will run
        while (yourLoop){

            //get your first number to put in the array list, you need to cast as an int 
            int randNumber = (int)(Math.random() * 100);
            //condition to check if the number is in the array list
            if (yourNumber.contains(randNumber)) {
                //print out the number that matched
                System.out.println(randNumber);
                //break the while loop
                yourLoop = false;
            }
            else {
                //add the number to your array list
                yourNumber.add(randNumber);
                //print out the array list
                System.out.println(yourNumber);
                //get another iteration
                yourLoop = true;
            }

        }

Upvotes: 0

Martijn Verburg
Martijn Verburg

Reputation: 3305

You can also use an implementation of a Java Set, which ensures that there are no duplicate elements (an easy way to detect a duplicate). However, declaring a simple int[] numbers = int[100](); array will also do the trick :-).

Upvotes: 0

Flo
Flo

Reputation: 1387

If "you don't know the size of an array" then you need an "array" witch grows dynamically... this is an ArrayList.

Obviously there are much more efficient methods but I think this will be just fine for now.

Upvotes: 2

Puppy
Puppy

Reputation: 147036

If the random numbers are only generated between 1 and 100, then use an array of size 100. However, in general, the problem is solved by a more generic associative container, e.g. HashMap, where contiguous keys are not required.

Upvotes: 9

Related Questions