Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - how to create a random number from an array of values

Tags:

java

random

on the first iteration- I want to create a random number from 0..10

This is how I've implement it-

 int generator= (int)(Math.random() * (10));

On the first iteration I want to create another random number, but without one of the values. For example I would like the random number without the number 4. only 1,2,3,5,6,7,8,9,0

How can I remove one of the values from the numbers 0..10 when I generate a random number?

like image 608
judith Avatar asked Jan 15 '23 04:01

judith


1 Answers

1st Way: -

You can also maintain a List of all the numbers. Then use Collections.shuffle to shuffle the list and get the first element. And remove it.

    List<Integer> list = new ArrayList<Integer>();

    list.add(1); 
    list.add(4);
    list.add(2);
    list.add(3);
    System.out.println("Original List: " + list);

    Collections.shuffle(list);

    System.out.println("Shuffled List: " + list);
    int number1 = list.remove(0);  // Remove the first value
    System.out.println("Number removed: " + number1);

    Collections.shuffle(list);

    System.out.println("Shuffled List: " + list);
    number1 = list.remove(0);
    System.out.println("Number removed: " + number1);

OUTPUT: -

Original List: [1, 4, 2, 3]
Shuffled List: [4, 3, 1, 2]
Number removed: 4
Shuffled List: [1, 3, 2]
Number removed: 1

2nd Way: -

A better way would be to generate a random number from 0 to the size of the list, and get the value of that index and remove it.

int size = list.size();
Random random = new Random();

for (int i = 0; i < size; i++) {    
    int index = random.nextInt(list.size());
    int number1 = list.remove(index);
    System.out.println(number1);
}

NOTE: - If you want to exclude a fixed set of numbers from being generated, then you can have those numbers in a list. And then remove all elements of that list from your list of numbers. And then use any of the approach above.

like image 189
Rohit Jain Avatar answered Jan 17 '23 19:01

Rohit Jain