I am writing a multi-threaded Java program that generates many random numbers.
Additional Information: These numbers are used to create a list of random numbers from 0 to 99 without repeating and for each number in the range 0-99 in the list (In other words, the list contains 100 unique elements in the range 0-99).
Random Number Generation [things have already tried!]
- I have an ArrayList of numbers from 0 to 100. I generate a random number and use it as an index, which is used to push an element from an
ArrayList . - I used
Collections.shuffle() .
Here is the code for approach 1:
ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < N; i++){ arr.add(i, i); } for(int i=0; i<N; i++){ int indx = rand.nextInt(arr.size()); res.add(arr.get(indx)); arr.remove(indx); }
For the second approach, I replaced the second for loop with Collections.shuffle(arr) .
Since generating a list of random numbers is the most expensive part of my algorithm, I want to optimize it. This leads me to questions:
- What is the fastest way to generate random numbers?
- What is the fastest way to generate a list of random numbers as described above?
PS:
- I found
Collections.shuffle() be slower than the first approach - Someone suggested I use
rngd to generate random numbers from hardware on Unix. Has anyone tried this before? How do you do this?
Ankit
source share