Home Tutorial Java Core Generate array of random numbers without repetition

 
 

Share on Google+Share on Google+
Generate array of random numbers without repetition
Posted on: July 2, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to generate array of random numbers without repetition.

Generate array of random numbers without repetition

In the previous section, you have learnt how to generate an array of random numbers from the given array. The generated array consists of some duplicates. So to overcome this, we have created an application that will generate the array of random numbers without repetition. Here we have allowed the user to enter the elements of array of their choice and display 5 elements from them randomly.

Here is the code:

import java.util.*;

public class RandomNumberExample {
	public static List get(List numbers, int noOfRandomNumbers) {
		List list = new ArrayList(numbers);
		List randomList = new ArrayList();

		Random rd = new Random();
		for (int i = 0; i < noOfRandomNumbers; i++) {
			int index = (int) (rd.nextDouble() * list.size());
			randomList.add(list.get(index));
			list.remove(index);
		}
		return randomList;
	}

	public static void main(String[] args) {
		int arr[] = new int[10];
		Integer in[] = new Integer[10];
		Scanner input = new Scanner(System.in);
		System.out.println("Enter 10 numbers: ");
		for (int i = 0; i < arr.length; i++) {
			arr[i] = input.nextInt();
			in[i] = new Integer(arr[i]);
		}
		System.out.println("Generated Random Numbers: ");
		List randomList = get(Arrays.asList(in), 5);
		for (Integer randomNumber : randomList) {
			System.out.println(randomNumber);
		}
	}
}

Output:

Enter 10 numbers:
1
2
3
4
5
6
7
8
9
10
Generated Random Numbers:
10
1
2
7
4
Advertisement

Related Tags for Generate array of random numbers without repetition:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 2, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com