Reputation: 1256
Simple question here -- mostly about APIs.
I want to iterate through an array in random order.
It is easy enough to:
However, I was wondering if step 1 (generating the list of numbers from 0 to N) exists somewhere in prewritten code.
For instance, could it be a convenience method in guava's XYZ class??
Upvotes: 0
Views: 1124
Reputation: 3073
If you skip step 1 and just do the shuffeling immediately I think you will have the fastest solution.
int range = 1000;
List<Integer> arr = new ArrayList<Integer>(range);
for(int i=0;i<range;i++) {
arr.add((int)(Math.random()*i), new Integer(i));
}
Upvotes: -1
Reputation: 66850
You may want to check out the Apache Commons
which among many other usefull functions, implement the nextPermutation method in RandomDataGenerator
class
This is obviously something much bigger then a method of populating the List
or array
, but commons are really powerfull libraries, which give much more good methods for mathematical computations.
Upvotes: 1
Reputation: 198321
The closest thing in Guava would be
ContiguousSet.create(Range.closedOpen(0, n), DiscreteDomains.integers())
...but, frankly, it is probably more readable just to write the for
loop yourself.
Upvotes: 2
Reputation: 272357
Noting specifically your emphasis on 'quick', I can't imagine there'd be much quicker than
List<Integer> = new ArrayList<Integer>(range);
and then iterating and populating each entry. Note that I set the capacity in order to avoid having the list resize under the covers.
Upvotes: 1
Reputation: 739
Java doesn't allow you to auto-populate your values. See this question for the ways to populate an array in java
"Creating an array of numbers without looping?"
Upvotes: 0