How to create a array with "n" random integers?
If you want to generate random integer array from an interval, here are the options
// generate 100 random number between 0 to 100
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100)).limit(100).toArray();
//generate 100 random number between 100 to 200
int[] randomIntsArray = IntStream.generate(() -> new Random().nextInt(100) + 100).limit(100).toArray();
You can take input from the user by using a scanner like this -
Scanner input= new Scanner(System.in);
System.out.println("Enter the array size: ");
int n = input.nextInt();
Now create a function generateRandomArray(int n)
like this -
public List<Integer> generateRandomArray(int n){
ArrayList<Integer> list = new ArrayList<Integer>(n);
Random random = new Random();
for (int i = 0; i < n; i++)
{
list.add(random.nextInt(1000));
}
return list;
}
Here - random.nextInt(1000)
will generate a random number from the range 0 to 1000. You can fix the range as you want.
Now you can call the function with the value n
get from the user -
ArrayList<Integer> list1 = generateRandomArray(n);
ArrayList<Integer> list2 = generateRandomArray(n);
Hope it will help.