title | date | draft | tags | categories | |||
---|---|---|---|---|---|---|---|
Algorithm4 Java Solution 1.3.34 |
2019-07-04 05:47:10 +0800 |
false |
|
|
Random bag. A random bag stores a collection of items and supports the following API:
Hint : Put the items in an array and randomize their order in the iterator’s constructor.
public RandomArrayIterator() {
// copy an array
copy = (Item[]) new Object[size];
for (int i = 0; i < size; i++) {
copy[i] = a[i];
}
// random order
for (int i = 0; i < size; i++) {
int r = i + StdRandom.uniform(size - i);
Item temp = copy[i];
copy[i] = copy[r];
copy[r] = temp;
}
}