1.3.34

problem:

random bad. a random bag stores a collection of items and supports the following api:

public class RandomBag<Item> implements Iterable<Item>
            RandomBag()     //create an empty random bag
    boolean isEmpty()       //is the bag empty?
        int size()          //number of items in the bag
       void add(Item item)  //add an item

write a class randombag that implements this api. note that this api is the same as for bag, except for the adjective random, which indicates that the iteration should provide the items in random order (all n! permutations equally likely, for each iterator). hint: put the items in an array and randomize their order in the iterator's constructor.

answer:

import edu.princeton.cs.algs4.*;
import java.util.Iterator;//注意别忘记

public class RandomBag<Item> implements Iterable<Item>
{
    private Item[] a = (Item[]) new Object[1];
    private int N = 0;
    
    public boolean isEmpty()
    {
        return N == 0;
    }
    public int size()
    {
        return N;
    }
    
    public void add(Item item)
    {
        if(N == a.length)
            resize(2 * a.length);
        a[N++] = item;
    }
    
    private void resize(int max)
    {
        Item[] temp = (Item[]) new Object[max];
        for(int i = 0; i < N; i++)
        {
            temp[i] = a[i];
        }
        a = temp;
    }
    
    public Iterator<Item> iterator()
    {
        return new RandomBagIterator();
    }
    
    private class RandomBagIterator implements Iterator<Item>
    {
            private int[] seq = new int [N];//作为元数组的下标
            private int index = 0;
            
            public RandomBagIterator()//打乱下标
            {
                for(int i = 0; i < seq.length; i++)
                {
                    seq[i] = i;
                }
                StdRandom.shuffle(seq);//p30页有原型,randomly shuffle the array a[]
            }
            
            public boolean hasNext()
            {
                return index < N;
            }
            
            public Item next()
            {
                return a[seq[index++]];
            }
            
            public void remove()
            {
            }
     }
        
    public static void main(String[] args)
    {
        RandomBag<String> randombag = new RandomBag<String>();
        randombag.add("w");
        randombag.add("j");
        randombag.add("c");
        for(String string : randombag)
        {
            StdOut.print(string + "\t");
        }
        StdOut.print("\n");
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9069736.html