reneargento/algorithms-sedgewick-wayne

Exercise 1.3.36 suggestion

sienic opened this issue · 1 comments

Although in the book they suggest in a previous exercise to shuffle a copy of the array,
I find it cheaper to rather have an indices array of integers, and shuffle them.

private class RandomQueueIterator implements Iterator<Item> {
    int i = 0;
    int[] indices = new int[N];
    public RandomQueueIterator() {
        for (int i = 0; i < N; i++) indices[i] = i;
        // Arrays.setAll(indices, i -> i); // or use this
        for (int i = 0; i < N - 1; i++) {
            int randomIndex = StdRandom.uniformInt(i + 1, N);
            int temp = indices[randomIndex];
            indices[randomIndex] = indices[i];
            indices[i] = temp;
        }
    }
    public boolean hasNext() { return i < N; }
    public Item next() { Item item = arr[indices[i++]]; return item; }
    public void remove() {}
}

Exercise updated: e36b7b9
Thanks for the suggestion!