Lord Bahamut
Lord Bahamut

Reputation: 153

Random number array sorting

I'm having an issue sorting my random number array.

What I'd like to do is make an if statement to make sure arr[0] is always greater than arr[1].

Why? Well, my program generates two random numbers from 0 - 99, and it does simple math problems such as subtraction and division. Since you can't divide 55 / 99 properly, the first arr[0] should always be larger than arr[1].

Here's where I'm at and thanks for your help!

public static int[] randomNumbers(){
    Random obj = new Random();

    int arr[] = new int[2];   //init array to hold 2 numbers

    arr[0] = obj.nextInt(99); //number 1 randomized 0 - 9 // sort array
    arr[1] = obj.nextInt(99); //number 2 randomized 0 - 9

    //do compare to make sure arr[0] is always greater than arr[1]
    //but how???

    return arr;

    /*int rgen = obj.nextInt(10); //first number has to be larger than second 0 - 10
    int rgen1 = obj.nextInt(9); //random 0 - 9
    int randomNumber = rgen + rgen1; //stores the answer*/
}

Upvotes: 0

Views: 209

Answers (2)

Naili
Naili

Reputation: 1602

You are generating number from 0 to 98. If you want to include 99 you should call obj.nextInt(100).

arr[0] = obj.nextInt(100);
if(arr[0]==0)
   arr[1]=0;
else
   arr[1] = obj.nextInt(arr[0]+1);

arr[0] will get a number in [0,100[

If the generated number is 0, arr[1] can be only 0.

Else, arr[1] will get a number in [ 0,arr[0]+1 [ (so [ 0,arr[0] ]);

Note : Passing non-positive number to nextInt() will raise an exception.

Upvotes: 1

Cory Kendall
Cory Kendall

Reputation: 7304

Just generate two numbers, and then switch them if the second is larger.

if (arr[1] > arr[0]) {
    int temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
}

Upvotes: 4

Related Questions