Skip to content

Latest commit

 

History

History
47 lines (34 loc) · 856 Bytes

File metadata and controls

47 lines (34 loc) · 856 Bytes
title Algorithm4 Java Solution 1.3.34
date 2019-07-04 05:47:10 +0800
draft false
tags
JAVA
categories
TECH
archives

1.3.34

Problem:

Random bag. A random bag stores a collection of items and supports the following API:

2019-07-24-001

Solution:

Hint : Put the items in an array and randomize their order in the iterator’s constructor.

Ex_1_3_34.java

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;
    }
  }

Reference: