How do you generate specific random number?

143 views Asked by At

I need a float or integer, not exactly generated but picked randomly.

Do I need to use and import math.random class?

For example I have 3 integers : 1, 6 and 3. I want one of them to be picked randomly.

6

There are 6 answers

0
Uma Kanth On BEST ANSWER

Generate a random index from the numbers you want and then take the number from the array

int []nums = {1,3,6};
int max = nums.length - 1;
int min = 0;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println(nums[randomNum]);
0
Sergey Kalinichenko On

Make an array of the allowed numbers (i.e. new int[] {1, 6, 3}) and then pick a random int in the range 0..length-of-array. Picking the value at the random index would produce the result that you want.

0
Mordechai On

Say you have an array (hope you know what that is) of your numbers you could do:

int choose = myNumbers[(int)Math.random() * myNumbers.length];
0
Elliott Frisch On

If you want each of your three values, but in a random order, then you might put them in an array. And, shuffle that array, you might use Arrays.asList(T...) and Collections.shuffle(List). Next, iterate the values in the array (perhaps with a for-each loop). Something like

public static void main(String[] args) {
    Integer[] arr = new Integer[] { 1, 6, 3 };
    Collections.shuffle(Arrays.asList(arr));
    for (int i : arr) {
        System.out.println(i);
    }
}

But, if you really need to pick just one random value at a time (say 10 times) then you could use a Random and nextInt(int) and a for loop. That might look something like

public static void main(String[] args) {
    int[] arr = new int[] { 1, 6, 3 };
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        int index = rand.nextInt(arr.length);
        System.out.println(arr[index]);
    }
}
0
Francisco Romero On

You have to create an array with the values that you want to get randomly. Like this:

int [] values = {1,3,6};

And you never have to forget to put:

Random rand = new Random();

Because if you don't put it, the Random function won't works properly.

So, then now you can access to your value randomly, like this:

int numObtained = rand.nextInt((values.length - 0) + 1) + 0;

The final code will be:

int [] values = {1,3,6};
Random rand = new Random();
int numObtained = rand.nextInt((values.length - 0) + 1) + 0;

I expect it helps to you!

0
Ramesh Kumar On

This might help.

int i[] = new int[]{3,4,6, 5, 8, 10, 14}; // given sets of array
int randomIndex = (int) (Math.random() * i.length); // generates a random index
System.out.println("random selected value " + i[randomIndex]);