algorithms-sedgewick-wayne icon indicating copy to clipboard operation
algorithms-sedgewick-wayne copied to clipboard

Exercise 1.3.36 suggestion

Open sienic opened this issue 1 year ago • 0 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() {}
}

sienic avatar Nov 16 '22 09:11 sienic