Get Random Number From Array without Repetition

In this blog post, I would like to explain how to get a random number from the ArrayList without repetition.

First, declare an ArrayList(Integer,String,etc). The following code is used to create the ArrayList:

ArrayList<Integer> array= new ArrayList<Integer>();

Now, we wish to declare an Integer array that should contain values, which you wish to choose randomly. In this case I wish to choose the number from the array randomly.
int friend[]={ 1,2,3,4,5};

After declaring the array, we have to add values to the ArrayList. The array.add(int) function is used to add the values in to the ArrayList.
for (int num1 : friend) {
array.add(num1);
}

Declare the random variable using Random Class in Java.
Random r = new Random();

The nextInt(int n) method is used to get a random number between 0 (inclusive) and the specified value
int select = r.nextInt(array.size());

Assign the selected number to a new variable as follows:
int random_friend = array.get(select);

Finally, remove the selected value from the ArrayList (to avoid repetition of the random number in future).
array.remove(select);

The Entire Code

public int getRandomNumber(int friend1[])
{
ArrayList<Integer> array= new ArrayList<Integer>();
int friend[]=friend1; 

for (int num1 : friend) {
array.add(num1);
}

Random r = new Random();
int select = r.nextInt(array.size());
int random_number = array.get(select);
array.remove(select);
return random_number;
}

Congrats, you have got your random number from the ArrayList without repetition.

Leave a Reply

Your email address will not be published. Required fields are marked *