算法第四版 练习 1.3.34
来源:互联网 发布:仙侠世界cos捏脸数据 编辑:程序博客网 时间:2024/06/06 02:19
RandomBag.java
import java.util.Iterator;import edu.princeton.cs.algs4.StdRandom;public class RandomBag<Item> implements Iterable<Item>{ private Item[] item; private int N; @SuppressWarnings("unchecked") public RandomBag(int cap) { if (cap <= 0) throw new RuntimeException(); item = (Item[])(new Object[cap]); } public boolean isEmpty() { return N == 0; } public boolean isFull() { return N == item.length; } public void resize(int n) { @SuppressWarnings("unchecked") Item[] temp = (Item[])(new Object[n]); for (int i = 0; i < N; ++i) temp[i] = item[i]; item = temp; } public int size() { return N; } public void add(Item data) { if (isFull()) resize(2 * N); item[N++] = data; } public Iterator<Item> iterator() { return new RandomBagIterator(); } private class RandomBagIterator implements Iterator<Item> { private int current = 0; public RandomBagIterator() { // i ----- N - 1 for (int i = 0; i < N; ++i) { int r = i + StdRandom.uniform(N - i); Item temp = (Item) item[i]; item[i] = item[r]; item[r] = temp; } } public boolean hasNext() { return current != N; } public void remove() { } public Item next() { return (Item) item[current++]; } }}
测试:main.java
import edu.princeton.cs.algs4.StdOut;public class Main { public static void main(String[] args) { RandomBag<Integer> rb = new RandomBag<Integer>(6); for (int i = 0; i < 10; ++i) rb.add(i); for (Integer t : rb) StdOut.print(t + " "); }}
阅读全文
1 0
- 算法第四版 练习 1.3.34
- 算法第四版 练习1.3.31
- 算法第四版 练习1.3.33
- 算法第四版 练习1.3.35
- 算法第四版 练习 1.3.39
- 算法第四版 第一章练习
- 算法-第四版-练习1.3.1解答
- 算法-第四版-练习1.3.2解答
- 算法-第四版-练习1.3.3解答
- 算法-第四版-练习1.3.4解答
- 算法-第四版-练习1.3.5解答
- 算法-第四版-练习1.3.6解答
- 算法-第四版-练习1.3.7解答
- 算法-第四版-练习1.3.8解答
- 算法-第四版-练习1.3.9解答
- 算法-第四版-练习1.3.10解答
- 算法-第四版-练习1.3.11解答
- 算法-第四版-练习1.3.12解答
- 【NYOJ
- C++设计模式:策略模式
- css盒子模型
- GIF文件格式详解
- Android获得json和XML
- 算法第四版 练习 1.3.34
- AI将带我们去何方?(上-前言篇)
- WekaAPI的学习(加载数据)
- 309. Best Time to Buy and Sell Stock with Cooldown---C语言
- ThinkPHP简介
- C/C++典型漏洞产生原理与Demo
- JAVA购物管理系统
- HDU 6035 Colorful Tree (树形dp)
- 【南阳 oj 】6-- 喷水装置(一)(贪心算法)