Ivan
Ivan

Reputation: 1256

Quick call to generate array containing number from 0 to N

Simple question here -- mostly about APIs.

I want to iterate through an array in random order.

It is easy enough to:

  1. fill a List with the numbers 0 to N
  2. shuffle the List with Collections.shuffle
  3. Use this shuffled list to guide my array iteration.

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

Answers (5)

www.jensolsson.se
www.jensolsson.se

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

lejlot
lejlot

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

Louis Wasserman
Louis Wasserman

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

Brian Agnew
Brian Agnew

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

jake_feyereisen
jake_feyereisen

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

Related Questions