Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a array with "n" random integers?

Create two Integer ArrayLists containing n ​elements each where n​​ will be taken from the user.

so basically if a user inputs '6' two arrays with 6 elements needs to be created. How would I do this?

This is what I have.. but its not even remotely correct.

Scanner input= new Scanner(System.in);
    System.out.println("please enter a integer 'n' ");
    int x= input.nextInt();

    int[] a = { 1, 4, 9, 16 };
    int[] b = { 9, 7, 4, 9, 11 };
like image 222
Malinator Avatar asked Mar 10 '15 17:03

Malinator


People also ask

How do you create an array of random integers?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.

How do you generate an array of random numbers in C++?

To get a random number, we use the rand() method. When invoked, the rand() function in C++ generates a pseudo-random number between 0 and RAND MAX. Whenever this method is used, it utilizes an algorithm that gives a succession of random numbers.


2 Answers

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();
like image 107
Nishad Avatar answered Sep 18 '22 18:09

Nishad


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.

like image 37
Razib Avatar answered Sep 20 '22 18:09

Razib