[
  {
    "path": ".gitignore",
    "content": "# Compiled class file\n*.class\n\n# Log file\n*.log\n\n# BlueJ files\n*.ctxt\n\n# Mobile Tools for Java (J2ME)\n.mtj.tmp/\n\n# Package Files #\n*.jar\n*.war\n*.ear\n*.zip\n*.tar.gz\n*.rar\n\n# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml\nhs_err_pid*\n"
  },
  {
    "path": "README.md",
    "content": "# 《算法（第4版）》笔记及代码\n\n[![作者](https://img.shields.io/badge/%E4%BD%9C%E8%80%85-KyonHuang-7AD6FD.svg)](http://kyonhuang.top)\n\n## 笔记\n\n推荐阅览 html 版本的笔记，由 [docsify](https://docsify.js.org/#/zh-cn/) 动态生成文档网站。\n\n[在线阅览地址](http://kyonhuang.top/Algorithms-notes/)\n\n## 目录\n\n* [《每一节可以再看一遍的题》](https://github.com/bighuang624/Algorithms-notes/blob/master/每一节可以再看一遍的题.md)\n* [《相关问题解决方法》](https://github.com/bighuang624/Algorithms-notes/blob/master/相关问题解决方法.md)\n\n### Fundamentals\n\n* [《1.3_背包、队列和栈》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.3_背包、队列和栈.md)\n* [《1.4_算法分析》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.4_算法分析.md)\n* [《1.5_案例研究：union-find算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.5_案例研究：union-find算法.md)\n\n### Sorting\n\n* [《2.1_初级排序算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.1_初级排序算法.md)\n* [《2.2_归并排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.2_归并排序.md)\n* [《2.3_快速排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.3_快速排序.md)\n* [《2.4_优先队列》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.4_优先队列.md)\n* [《2.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.5_应用.md)\n\n### Searching\n\n* [《3.1_符号表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.1_符号表.md)\n* [《3.2_二叉查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.2_二叉查找树.md)\n* [《3.3_平衡查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.3_平衡查找树.md)\n* [《3.4_散列表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.4_散列表.md)\n* [《3.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.5_应用.md)\n\n### Graphs\n\n* [《4.1_无向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.1_无向图.md)\n* [《4.2_有向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.2_有向图.md)\n* [《4.3_最小生成树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.3_最小生成树.md)\n* [《4.4_最短路径》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.4_最短路径.md)\n\n### Strings\n\n* [《5.2_单词查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.2_单词查找树.md)\n* [《5.3_子字符串查找》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.3_子字符串查找.md)\n\n### Context\n\n* [《6.3_后缀数组》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.3_后缀数组.md)\n* [《6.4_网络流算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.4_网络流算法.md)\n* [《6.5_问题规约》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.5_问题规约.md)\n* [《6.6_不可解性》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.6_不可解性.md)\n\n## 代码\n\n相关代码详见[代码目录](https://github.com/bighuang624/Algorithms-notes/blob/master/code)\n\n## Cheatsheet\n\n[Algorithms and Data Structures Cheatsheet](https://algs4.cs.princeton.edu/cheatsheet/)\n\n![Cheatsheet](https://raw.githubusercontent.com/bighuang624/Algorithms-notes/master/Cheatsheet.png)\n\n## 参考资料\n\n[算法（第4版）课后练习答案及相关问题解决方案 - 孙强Jimmy的技术博客 - CSDN博客](http://blog.csdn.net/u013541140/article/details/53222770)\n\n"
  },
  {
    "path": "code/README.md",
    "content": "# 代码目录\n\n\n### algs4\n\n* [Alphabet.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Alphabet.java)\n* [Bag.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Bag.java)\n* [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinarySearch.java)\n* [BinaryStdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdIn.java)\n* [BinaryStdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdOut.java)\n* [Counter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Counter.java)\n* [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DepthFirstOrder.java)\n* [Draw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Draw.java)\n* [DrawListener.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DrawListener.java)\n* [Heap.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Heap.java)\n* [HexDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/HexDump.java)\n* [In.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/In.java)\n* [IndexMinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/IndexMinPQ.java)\n* [Interval1D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval1D.java)\n* [Interval2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval2D.java)\n* [MinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/MinPQ.java)\n* [Out.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Out.java)\n* [Particle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Particle.java)\n* [Picture.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Picture.java)\n* [PictureDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/PictureDump.java)\n* [Point2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Point2D.java)\n* [Queue.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Queue.java)\n* [SET.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/SET.java)\n* [ST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/ST.java)\n* [Stack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Stack.java)\n* [StdDraw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdDraw.java)\n* [StdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdIn.java)\n* [StdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdOut.java)\n* [StdRandom.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdRandom.java)\n\n### chapter1_1_Programming_Model\n\n* [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BinarySearch.java)\n* [BouncingBall.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BouncingBall.java)\n* [Ex1.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex1.java)\n* [Ex10.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex10.java)\n* [Ex11.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex11.java)\n* [Ex13.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex13.java)\n* [Ex14.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex14.java)\n* [Ex15.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex15.java)\n* [Ex19.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex19.java)\n* [Ex2.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex2.java)\n* [Ex20.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex20.java)\n* [Ex3.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex3.java)\n* [Ex30.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex30.java)\n* [Ex31.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex31.java)\n* [Ex32.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex32.java)\n* [Ex6.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex6.java)\n* [Ex7a.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7a.java)\n* [Ex7b.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7b.java)\n* [Ex7c.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7c.java)\n* [Ex8.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex8.java)\n* [Ex9.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex9.java)\n* [RightTriangle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/RightTriangle.java)\n* [Sattolo.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Sattolo.java)\n* [StdDrawTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/StdDrawTest.java)\n\n### chapter1_2_Data_Abstraction\n\n* [Accumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Accumulator.java)\n* [AccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/AccumulatorTest.java)\n* [Cat.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Cat.java)\n* [Date.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Date.java)\n* [Flips.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Flips.java)\n* [FlipsMax.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/FlipsMax.java)\n* [Interval2DTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Interval2DTest.java)\n* [Rolls.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Rolls.java)\n* [StaticSETofInts.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/StaticSETofInts.java)\n* [VisualAccumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulator.java)\n* [VisualAccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java)\n* [WhiteList.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/WhiteList.java)\n* [in1.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in1.txt)\n* [in2.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in2.txt)\n\n### chapter1_3_Bags_Queues_Stacks\n\n* [ResizingArrayStack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java)\n\n### chapter1_4_Analysis_of_Algorithms\n\n* [DoublingRatio.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java)\n* [DoublingTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java)\n* [Stopwatch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java)\n* [StopwatchTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java)\n* [ThreeSum.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java)\n\n### chapter1_5_Case_Study_Union_Find\n\n* [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/UF.java)\n* [WeightedQuickUnionUF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java)\n\n### chapter2_1_Elementary_Sorts\n\n* [Insertion.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Insertion.java)\n* [Selection.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Selection.java)\n* [Shell.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Shell.java)\n* [SortCompare.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/SortCompare.java)\n\n### chapter2_2_Mergesort\n\n* [Merge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/Merge.java)\n* [MergeBU.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/MergeBU.java)\n\n### chapter2_3_Quicksort\n\n* [Ex25.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Ex25.java)\n* [Quick.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick.java)\n* [Quick3way.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick3way.java)\n\n### chapter2_4_Priority_Queues\n\n* [MaxPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/MaxPQ.java)\n* [TopM.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/TopM.java)\n\n### chapter2_5_Sorting_Applications\n\n\n### chapter3_1_Symbol_Tables\n\n* [BinarySearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/BinarySearchST.java)\n* [FrequencyCounter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/FrequencyCounter.java)\n* [SequentialSearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/SequentialSearchST.java)\n\n### chapter3_2_Binary_Search_Trees\n\n* [BST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_2_Binary_Search_Trees/BST.java)\n\n### chapter3_4_Hash_Tables\n\n* [LinearProbingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/LinearProbingHashST.java)\n* [SeparateChainingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/SeparateChainingHashST.java)\n\n### chapter3_5_Searching_Applications\n\n* [SparseVector.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/SparseVector.java)\n* [WhiteFilter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/WhiteFilter.java)\n\n### chapter4_1_Undirected_Graphs\n\n* [BreadthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java)\n* [CC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/CC.java)\n* [Cycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Cycle.java)\n* [DegreesOfSeparation.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java)\n* [DepthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java)\n* [DepthFirstSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java)\n* [Graph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Graph.java)\n* [SymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/SymbolGraph.java)\n* [TestCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestCC.java)\n* [TestPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestPaths.java)\n* [TestSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSearch.java)\n* [TestSymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java)\n* [TwoColor.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TwoColor.java)\n\n### chapter4_2_Directed_Graphs\n\n* [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DepthFirstOrder.java)\n* [Digraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Digraph.java)\n* [DirectedCycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedCycle.java)\n* [DirectedDFS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedDFS.java)\n* [KosarajuSCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/KosarajuSCC.java)\n* [SymbolDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/SymbolDigraph.java)\n* [Topological.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Topological.java)\n* [TransitiveClosure.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/TransitiveClosure.java)\n\n### chapter4_3_Minimum_Spanning_Tree\n\n* [Edge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/Edge.java)\n* [EdgeWeightedGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java)\n* [KruskalMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java)\n* [LazyPrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java)\n* [PrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java)\n* [TestMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/TestMST.java)\n* [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/UF.java)\n\n### chapter4_4_Shortest_Paths\n\n* [DijkstraSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DijkstraSP.java)\n* [DirectedEdge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DirectedEdge.java)\n* [EdgeWeightedDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java)\n* [SP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/SP.java)\n* [TestSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/TestSP.java)\n\n### chapter5_3_Substring_Search\n\n* [BoyerMoore.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/BoyerMoore.java)\n* [KMP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/KMP.java)\n* [RabinKarp.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/RabinKarp.java)\n\n### chapter6_3_Suffix_Arrays\n\n* [KWIC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/KWIC.java)\n* [LRS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/LRS.java)\n* [SuffixArray.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/SuffixArray.java)\n\n"
  },
  {
    "path": "code/algs4/Alphabet.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Alphabet.java\n *  Execution:    java Alphabet\n *  Dependencies: StdOut.java\n *  \n *  A data type for alphabets, for use with string-processing code\n *  that must convert between an alphabet of size R and the integers\n *  0 through R-1.\n *\n *  Warning: supports only the basic multilingual plane (BMP), i.e,\n *           Unicode characters between U+0000 and U+FFFF.\n *\n ******************************************************************************/\n\npackage algs4;\n\npublic class Alphabet {\n\n    /**\n     *  The binary alphabet { 0, 1 }.\n     */\n    public static final Alphabet BINARY = new Alphabet(\"01\");\n\n    /**\n     *  The octal alphabet { 0, 1, 2, 3, 4, 5, 6, 7 }.\n     */\n    public static final Alphabet OCTAL = new Alphabet(\"01234567\");\n\n    /**\n     *  The decimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.\n     */\n    public static final Alphabet DECIMAL = new Alphabet(\"0123456789\");\n\n    /**\n     *  The hexadecimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F }.\n     */\n    public static final Alphabet HEXADECIMAL = new Alphabet(\"0123456789ABCDEF\");\n\n    /**\n     *  The DNA alphabet { A, C, T, G }.\n     */\n    public static final Alphabet DNA = new Alphabet(\"ACGT\");\n\n    /**\n     *  The lowercase alphabet { a, b, c, ..., z }.\n     */\n    public static final Alphabet LOWERCASE = new Alphabet(\"abcdefghijklmnopqrstuvwxyz\");\n\n    /**\n     *  The uppercase alphabet { A, B, C, ..., Z }.\n     */\n\n    public static final Alphabet UPPERCASE = new Alphabet(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\");\n\n    /**\n     *  The protein alphabet { A, C, D, E, F, G, H, I, K, L, M, N, P, Q, R, S, T, V, W, Y }.\n     */\n    public static final Alphabet PROTEIN = new Alphabet(\"ACDEFGHIKLMNPQRSTVWY\");\n\n    /**\n     *  The base-64 alphabet (64 characters).\n     */\n    public static final Alphabet BASE64 = new Alphabet(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\");\n\n    /**\n     *  The ASCII alphabet (0-127).\n     */\n    public static final Alphabet ASCII = new Alphabet(128);\n\n    /**\n     *  The extended ASCII alphabet (0-255).\n     */\n    public static final Alphabet EXTENDED_ASCII = new Alphabet(256);\n\n    /**\n     *  The Unicode 16 alphabet (0-65,535).\n     */\n    public static final Alphabet UNICODE16      = new Alphabet(65536);\n\n\n    private char[] alphabet;     // the characters in the alphabet\n    private int[] inverse;       // indices\n    private final int R;         // the radix of the alphabet\n\n    /**\n     * Initializes a new alphabet from the given set of characters.\n     *\n     * @param alpha the set of characters\n     */\n    public Alphabet(String alpha) {\n\n        // check that alphabet contains no duplicate chars\n        boolean[] unicode = new boolean[Character.MAX_VALUE];\n        for (int i = 0; i < alpha.length(); i++) {\n            char c = alpha.charAt(i);\n            if (unicode[c])\n                throw new IllegalArgumentException(\"Illegal alphabet: repeated character = '\" + c + \"'\");\n            unicode[c] = true;\n        }\n\n        alphabet = alpha.toCharArray();\n        R = alpha.length();\n        inverse = new int[Character.MAX_VALUE];\n        for (int i = 0; i < inverse.length; i++)\n            inverse[i] = -1;\n\n        // can't use char since R can be as big as 65,536\n        for (int c = 0; c < R; c++)\n            inverse[alphabet[c]] = c;\n    }\n\n    /**\n     * Initializes a new alphabet using characters 0 through R-1.\n     *\n     * @param radix the number of characters in the alphabet (the radix R)\n     */\n    private Alphabet(int radix) {\n        this.R = radix;\n        alphabet = new char[R];\n        inverse = new int[R];\n\n        // can't use char since R can be as big as 65,536\n        for (int i = 0; i < R; i++)\n            alphabet[i] = (char) i;\n        for (int i = 0; i < R; i++)\n            inverse[i] = i;\n    }\n\n    /**\n     * Initializes a new alphabet using characters 0 through 255.\n     */\n    public Alphabet() {\n        this(256);\n    }\n\n    /**\n     * Returns true if the argument is a character in this alphabet.\n     *\n     * @param  c the character\n     * @return {@code true} if {@code c} is a character in this alphabet;\n     *         {@code false} otherwise\n     */\n    public boolean contains(char c) {\n        return inverse[c] != -1;\n    }\n\n    /**\n     * Returns the number of characters in this alphabet (the radix).\n     * \n     * @return the number of characters in this alphabet\n     * @deprecated Replaced by {@link #radix()}.\n     */\n    @Deprecated\n    public int R() {\n        return R;\n    }\n\n    /**\n     * Returns the number of characters in this alphabet (the radix).\n     * \n     * @return the number of characters in this alphabet\n     */\n    public int radix() {\n        return R;\n    }\n\n    /**\n     * Returns the binary logarithm of the number of characters in this alphabet.\n     * \n     * @return the binary logarithm (rounded up) of the number of characters in this alphabet\n     */\n    public int lgR() {\n        int lgR = 0;\n        for (int t = R-1; t >= 1; t /= 2)\n            lgR++;\n        return lgR;\n    }\n\n    /**\n     * Returns the index corresponding to the argument character.\n     * \n     * @param  c the character\n     * @return the index corresponding to the character {@code c}\n     * @throws IllegalArgumentException unless {@code c} is a character in this alphabet\n     */\n    public int toIndex(char c) {\n        if (c >= inverse.length || inverse[c] == -1) {\n            throw new IllegalArgumentException(\"Character \" + c + \" not in alphabet\");\n        }\n        return inverse[c];\n    }\n\n    /**\n     * Returns the indices corresponding to the argument characters.\n     * \n     * @param  s the characters\n     * @return the indices corresponding to the characters {@code s}\n     * @throws IllegalArgumentException unless every character in {@code s}\n     *         is a character in this alphabet\n     */\n    public int[] toIndices(String s) {\n        char[] source = s.toCharArray();\n        int[] target  = new int[s.length()];\n        for (int i = 0; i < source.length; i++)\n            target[i] = toIndex(source[i]);\n        return target;\n    }\n\n    /**\n     * Returns the character corresponding to the argument index.\n     * \n     * @param  index the index\n     * @return the character corresponding to the index {@code index}\n     * @throws IllegalArgumentException unless {@code 0 <= index < R}\n     */\n    public char toChar(int index) {\n        if (index < 0 || index >= R) {\n            throw new IndexOutOfBoundsException(\"Alphabet index out of bounds\");\n        }\n        return alphabet[index];\n    }\n\n    /**\n     * Returns the characters corresponding to the argument indices.\n     * \n     * @param  indices the indices\n     * @return the characters corresponding to the indices {@code indices}\n     * @throws IllegalArgumentException unless {@code 0 < indices[i] < R}\n     *         for every {@code i}\n     */\n    public String toChars(int[] indices) {\n        StringBuilder s = new StringBuilder(indices.length);\n        for (int i = 0; i < indices.length; i++)\n            s.append(toChar(indices[i]));\n        return s.toString();\n    }\n\n    /**\n     * Unit tests the {@code Alphabet} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int[]  encoded1 = Alphabet.BASE64.toIndices(\"NowIsTheTimeForAllGoodMen\");\n        String decoded1 = Alphabet.BASE64.toChars(encoded1);\n        StdOut.println(decoded1);\n \n        int[]  encoded2 = Alphabet.DNA.toIndices(\"AACGAACGGTTTACCCCG\");\n        String decoded2 = Alphabet.DNA.toChars(encoded2);\n        StdOut.println(decoded2);\n\n        int[]  encoded3 = Alphabet.DECIMAL.toIndices(\"01234567890123456789\");\n        String decoded3 = Alphabet.DECIMAL.toChars(encoded3);\n        StdOut.println(decoded3);\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Bag.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Bag.java\n *  Execution:    java Bag < input.txt\n *  Dependencies: StdIn.java StdOut.java\n *\n *  A generic bag or multiset, implemented using a singly-linked list.\n *\n *  % more tobe.txt \n *  to be or not to - be - - that - - - is\n *\n *  % java Bag < tobe.txt\n *  size of bag = 14\n *  is\n *  -\n *  -\n *  -\n *  that\n *  -\n *  -\n *  be\n *  -\n *  to\n *  not\n *  or\n *  be\n *  to\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n *  The {@code Bag} class represents a bag (or multiset) of \n *  generic items. It supports insertion and iterating over the \n *  items in arbitrary order.\n *  <p>\n *  This implementation uses a singly-linked list with a static nested class Node.\n *  See {@link LinkedBag} for the version from the\n *  textbook that uses a non-static nested class.\n *  The <em>add</em>, <em>isEmpty</em>, and <em>size</em> operations\n *  take constant time. Iteration takes time proportional to the number of items.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/13stacks\">Section 1.3</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Item> the generic type of an item in this bag\n */\npublic class Bag<Item> implements Iterable<Item> {\n    private Node<Item> first;    // beginning of bag\n    private int n;               // number of elements in bag\n\n    // helper linked list class\n    private static class Node<Item> {\n        private Item item;\n        private Node<Item> next;\n    }\n\n    /**\n     * Initializes an empty bag.\n     */\n    public Bag() {\n        first = null;\n        n = 0;\n    }\n\n    /**\n     * Returns true if this bag is empty.\n     *\n     * @return {@code true} if this bag is empty;\n     *         {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return first == null;\n    }\n\n    /**\n     * Returns the number of items in this bag.\n     *\n     * @return the number of items in this bag\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Adds the item to this bag.\n     *\n     * @param  item the item to add to this bag\n     */\n    public void add(Item item) {\n        Node<Item> oldfirst = first;\n        first = new Node<Item>();\n        first.item = item;\n        first.next = oldfirst;\n        n++;\n    }\n\n\n    /**\n     * Returns an iterator that iterates over the items in this bag in arbitrary order.\n     *\n     * @return an iterator that iterates over the items in this bag in arbitrary order\n     */\n    public Iterator<Item> iterator()  {\n        return new ListIterator<Item>(first);  \n    }\n\n    // an iterator, doesn't implement remove() since it's optional\n    private class ListIterator<Item> implements Iterator<Item> {\n        private Node<Item> current;\n\n        public ListIterator(Node<Item> first) {\n            current = first;\n        }\n\n        public boolean hasNext()  { return current != null;                     }\n        public void remove()      { throw new UnsupportedOperationException();  }\n\n        public Item next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            Item item = current.item;\n            current = current.next; \n            return item;\n        }\n    }\n\n    /**\n     * Unit tests the {@code Bag} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Bag<String> bag = new Bag<String>();\n        while (!StdIn.isEmpty()) {\n            String item = StdIn.readString();\n            bag.add(item);\n        }\n\n        StdOut.println(\"size of bag = \" + bag.size());\n        for (String s : bag) {\n            StdOut.println(s);\n        }\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/BinarySearch.java",
    "content": "/******************************************************************************\n *  Compilation:  javac BinarySearch.java\n *  Execution:    java BinarySearch whitelist.txt < input.txt\n *  Dependencies: In.java StdIn.java StdOut.java\n *  Data files:   http://algs4.cs.princeton.edu/11model/tinyW.txt\n *                http://algs4.cs.princeton.edu/11model/tinyT.txt\n *                http://algs4.cs.princeton.edu/11model/largeW.txt\n *                http://algs4.cs.princeton.edu/11model/largeT.txt\n *\n *  % java BinarySearch tinyW.txt < tinyT.txt\n *  50\n *  99\n *  13\n *\n *  % java BinarySearch largeW.txt < largeT.txt | more\n *  499569\n *  984875\n *  295754\n *  207807\n *  140925\n *  161828\n *  [367,966 total values]\n *  \n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Arrays;\n\n/**\n *  The {@code BinarySearch} class provides a static method for binary\n *  searching for an integer in a sorted array of integers.\n *  <p>\n *  The <em>indexOf</em> operations takes logarithmic time in the worst case.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/11model\">Section 1.1</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class BinarySearch {\n\n    /**\n     * This class should not be instantiated.\n     */\n    private BinarySearch() { }\n\n    /**\n     * Returns the index of the specified key in the specified array.\n     *\n     * @param  a the array of integers, must be sorted in ascending order\n     * @param  key the search key\n     * @return index of key in array {@code a} if present; {@code -1} otherwise\n     */\n    public static int indexOf(int[] a, int key) {\n        int lo = 0;\n        int hi = a.length - 1;\n        while (lo <= hi) {\n            // Key is in a[lo..hi] or not present.\n            int mid = lo + (hi - lo) / 2;\n            if      (key < a[mid]) hi = mid - 1;\n            else if (key > a[mid]) lo = mid + 1;\n            else return mid;\n        }\n        return -1;\n    }\n\n    /**\n     * Returns the index of the specified key in the specified array.\n     * This function is poorly named because it does not give the <em>rank</em>\n     * if the array has duplicate keys or if the key is not in the array.\n     *\n     * @param  key the search key\n     * @param  a the array of integers, must be sorted in ascending order\n     * @return index of key in array {@code a} if present; {@code -1} otherwise\n     * @deprecated Replaced by {@link #indexOf(int[], int)}.\n     */\n    @Deprecated\n    public static int rank(int key, int[] a) {\n        return indexOf(a, key);\n    }\n\n    /**\n     * Reads in a sequence of integers from the whitelist file, specified as\n     * a command-line argument; reads in integers from standard input;\n     * prints to standard output those integers that do <em>not</em> appear in the file.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n\n        // read the integers from a file\n        In in = new In(args[0]);\n        int[] whitelist = in.readAllInts();\n\n        // sort the array\n        Arrays.sort(whitelist);\n\n        // read integer key from standard input; print if not in whitelist\n        while (!StdIn.isEmpty()) {\n            int key = StdIn.readInt();\n            if (BinarySearch.indexOf(whitelist, key) == -1)\n                StdOut.println(key);\n        }\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/BinaryStdIn.java",
    "content": "/******************************************************************************\n *  Compilation:  javac BinaryStdIn.java\n *  Execution:    java BinaryStdIn < input > output\n *  Dependencies: none             \n *  \n *  Supports reading binary data from standard input.\n *\n *  % java BinaryStdIn < input.jpg > output.jpg\n *  % diff input.jpg output.jpg\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.util.NoSuchElementException;\n\n/**\n *  <i>Binary standard input</i>. This class provides methods for reading\n *  in bits from standard input, either one bit at a time (as a {@code boolean}),\n *  8 bits at a time (as a {@code byte} or {@code char}),\n *  16 bits at a time (as a {@code short}), 32 bits at a time\n *  (as an {@code int} or {@code float}), or 64 bits at a time (as a\n *  {@code double} or {@code long}).\n *  <p>\n *  All primitive types are assumed to be represented using their \n *  standard Java representations, in big-endian (most significant\n *  byte first) order.\n *  <p>\n *  The client should not intermix calls to {@code BinaryStdIn} with calls\n *  to {@code StdIn} or {@code System.in};\n *  otherwise unexpected behavior will result.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class BinaryStdIn {\n    private static BufferedInputStream in = new BufferedInputStream(System.in);\n    private static final int EOF = -1;    // end of file\n\n    private static int buffer;            // one character buffer\n    private static int n;                 // number of bits left in buffer\n\n    // static initializer\n    static {\n        fillBuffer();\n    }\n\n    // don't instantiate\n    private BinaryStdIn() { }\n\n    private static void fillBuffer() {\n        try {\n            buffer = in.read();\n            n = 8;\n        }\n        catch (IOException e) {\n            System.out.println(\"EOF\");\n            buffer = EOF;\n            n = -1;\n        }\n    }\n\n   /**\n     * Close this input stream and release any associated system resources.\n     */\n    public static void close() {\n        try {\n            in.close();\n        }\n        catch (IOException ioe) {\n            throw new IllegalStateException(\"Could not close BinaryStdIn\", ioe);\n        }\n    }\n\n   /**\n     * Returns true if standard input is empty.\n     * @return true if and only if standard input is empty\n     */\n    public static boolean isEmpty() {\n        return buffer == EOF;\n    }\n\n   /**\n     * Reads the next bit of data from standard input and return as a boolean.\n     *\n     * @return the next bit of data from standard input as a {@code boolean}\n     * @throws NoSuchElementException if standard input is empty\n     */\n    public static boolean readBoolean() {\n        if (isEmpty()) throw new NoSuchElementException(\"Reading from empty input stream\");\n        n--;\n        boolean bit = ((buffer >> n) & 1) == 1;\n        if (n == 0) fillBuffer();\n        return bit;\n    }\n\n   /**\n     * Reads the next 8 bits from standard input and return as an 8-bit char.\n     * Note that {@code char} is a 16-bit type;\n     * to read the next 16 bits as a char, use {@code readChar(16)}.\n     *\n     * @return the next 8 bits of data from standard input as a {@code char}\n     * @throws NoSuchElementException if there are fewer than 8 bits available on standard input\n     */\n    public static char readChar() {\n        if (isEmpty()) throw new NoSuchElementException(\"Reading from empty input stream\");\n\n        // special case when aligned byte\n        if (n == 8) {\n            int x = buffer;\n            fillBuffer();\n            return (char) (x & 0xff);\n        }\n\n        // combine last n bits of current buffer with first 8-n bits of new buffer\n        int x = buffer;\n        x <<= (8 - n);\n        int oldN = n;\n        fillBuffer();\n        if (isEmpty()) throw new NoSuchElementException(\"Reading from empty input stream\");\n        n = oldN;\n        x |= (buffer >>> n);\n        return (char) (x & 0xff);\n        // the above code doesn't quite work for the last character if n = 8\n        // because buffer will be -1, so there is a special case for aligned byte\n    }\n\n   /**\n     * Reads the next r bits from standard input and return as an r-bit character.\n     *\n     * @param  r number of bits to read.\n     * @return the next r bits of data from standard input as a {@code char}\n     * @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input\n     * @throws IllegalArgumentException unless {@code 1 <= r <= 16}\n     */\n    public static char readChar(int r) {\n        if (r < 1 || r > 16) throw new IllegalArgumentException(\"Illegal value of r = \" + r);\n\n        // optimize r = 8 case\n        if (r == 8) return readChar();\n\n        char x = 0;\n        for (int i = 0; i < r; i++) {\n            x <<= 1;\n            boolean bit = readBoolean();\n            if (bit) x |= 1;\n        }\n        return x;\n    }\n\n   /**\n     * Reads the remaining bytes of data from standard input and return as a string. \n     *\n     * @return the remaining bytes of data from standard input as a {@code String}\n     * @throws NoSuchElementException if standard input is empty or if the number of bits\n     *         available on standard input is not a multiple of 8 (byte-aligned)\n     */\n    public static String readString() {\n        if (isEmpty()) throw new NoSuchElementException(\"Reading from empty input stream\");\n\n        StringBuilder sb = new StringBuilder();\n        while (!isEmpty()) {\n            char c = readChar();\n            sb.append(c);\n        }\n        return sb.toString();\n    }\n\n\n   /**\n     * Reads the next 16 bits from standard input and return as a 16-bit short.\n     *\n     * @return the next 16 bits of data from standard input as a {@code short}\n     * @throws NoSuchElementException if there are fewer than 16 bits available on standard input\n     */\n    public static short readShort() {\n        short x = 0;\n        for (int i = 0; i < 2; i++) {\n            char c = readChar();\n            x <<= 8;\n            x |= c;\n        }\n        return x;\n    }\n\n   /**\n     * Reads the next 32 bits from standard input and return as a 32-bit int.\n     *\n     * @return the next 32 bits of data from standard input as a {@code int}\n     * @throws NoSuchElementException if there are fewer than 32 bits available on standard input\n     */\n    public static int readInt() {\n        int x = 0;\n        for (int i = 0; i < 4; i++) {\n            char c = readChar();\n            x <<= 8;\n            x |= c;\n        }\n        return x;\n    }\n\n   /**\n     * Reads the next r bits from standard input and return as an r-bit int.\n     *\n     * @param  r number of bits to read.\n     * @return the next r bits of data from standard input as a {@code int}\n     * @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input\n     * @throws IllegalArgumentException unless {@code 1 <= r <= 32}\n     */\n    public static int readInt(int r) {\n        if (r < 1 || r > 32) throw new IllegalArgumentException(\"Illegal value of r = \" + r);\n\n        // optimize r = 32 case\n        if (r == 32) return readInt();\n\n        int x = 0;\n        for (int i = 0; i < r; i++) {\n            x <<= 1;\n            boolean bit = readBoolean();\n            if (bit) x |= 1;\n        }\n        return x;\n    }\n\n   /**\n     * Reads the next 64 bits from standard input and return as a 64-bit long.\n     *\n     * @return the next 64 bits of data from standard input as a {@code long}\n     * @throws NoSuchElementException if there are fewer than 64 bits available on standard input\n     */\n    public static long readLong() {\n        long x = 0;\n        for (int i = 0; i < 8; i++) {\n            char c = readChar();\n            x <<= 8;\n            x |= c;\n        }\n        return x;\n    }\n\n\n   /**\n     * Reads the next 64 bits from standard input and return as a 64-bit double.\n     *\n     * @return the next 64 bits of data from standard input as a {@code double}\n     * @throws NoSuchElementException if there are fewer than 64 bits available on standard input\n     */\n    public static double readDouble() {\n        return Double.longBitsToDouble(readLong());\n    }\n\n   /**\n     * Reads the next 32 bits from standard input and return as a 32-bit float.\n     *\n     * @return the next 32 bits of data from standard input as a {@code float}\n     * @throws NoSuchElementException if there are fewer than 32 bits available on standard input\n     */\n    public static float readFloat() {\n        return Float.intBitsToFloat(readInt());\n    }\n\n\n   /**\n     * Reads the next 8 bits from standard input and return as an 8-bit byte.\n     *\n     * @return the next 8 bits of data from standard input as a {@code byte}\n     * @throws NoSuchElementException if there are fewer than 8 bits available on standard input\n     */\n    public static byte readByte() {\n        char c = readChar();\n        return (byte) (c & 0xff);\n    }\n    \n   /**\n     * Test client. Reads in a binary input file from standard input and writes\n     * it to standard output.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n\n        // read one 8-bit char at a time\n        while (!BinaryStdIn.isEmpty()) {\n            char c = BinaryStdIn.readChar();\n            BinaryStdOut.write(c);\n        }\n        BinaryStdOut.flush();\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/BinaryStdOut.java",
    "content": "/******************************************************************************\n *  Compilation:  javac BinaryStdOut.java\n *  Execution:    java BinaryStdOut\n *  Dependencies: none\n *\n *  Write binary data to standard output, either one 1-bit boolean,\n *  one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float,\n *  or one 64-bit long at a time.\n *\n *  The bytes written are not aligned.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.io.BufferedOutputStream;\nimport java.io.IOException;\n\n/**\n *  <i>Binary standard output</i>. This class provides methods for converting\n *  primtive type variables ({@code boolean}, {@code byte}, {@code char},\n *  {@code int}, {@code long}, {@code float}, and {@code double})\n *  to sequences of bits and writing them to standard output.\n *  Uses big-endian (most-significant byte first).\n *  <p>\n *  The client must {@code flush()} the output stream when finished writing bits.\n *  <p>\n *  The client should not intermixing calls to {@code BinaryStdOut} with calls\n *  to {@code StdOut} or {@code System.out}; otherwise unexpected behavior \n *  will result.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class BinaryStdOut {\n    private static BufferedOutputStream out = new BufferedOutputStream(System.out);\n\n    private static int buffer;     // 8-bit buffer of bits to write out\n    private static int n;          // number of bits remaining in buffer\n\n    // don't instantiate\n    private BinaryStdOut() { }\n\n   /**\n     * Write the specified bit to standard output.\n     */\n    private static void writeBit(boolean bit) {\n        // add bit to buffer\n        buffer <<= 1;\n        if (bit) buffer |= 1;\n\n        // if buffer is full (8 bits), write out as a single byte\n        n++;\n        if (n == 8) clearBuffer();\n    } \n\n   /**\n     * Write the 8-bit byte to standard output.\n     */\n    private static void writeByte(int x) {\n        assert x >= 0 && x < 256;\n\n        // optimized if byte-aligned\n        if (n == 0) {\n            try {\n                out.write(x);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n            return;\n        }\n\n        // otherwise write one bit at a time\n        for (int i = 0; i < 8; i++) {\n            boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;\n            writeBit(bit);\n        }\n    }\n\n    // write out any remaining bits in buffer to standard output, padding with 0s\n    private static void clearBuffer() {\n        if (n == 0) return;\n        if (n > 0) buffer <<= (8 - n);\n        try {\n            out.write(buffer);\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n        n = 0;\n        buffer = 0;\n    }\n\n   /**\n     * Flush standard output, padding 0s if number of bits written so far\n     * is not a multiple of 8.\n     */\n    public static void flush() {\n        clearBuffer();\n        try {\n            out.flush();\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n   /**\n     * Flush and close standard output. Once standard output is closed, you can no\n     * longer write bits to it.\n     */\n    public static void close() {\n        flush();\n        try {\n            out.close();\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n\n   /**\n     * Write the specified bit to standard output.\n     * @param x the {@code boolean} to write.\n     */\n    public static void write(boolean x) {\n        writeBit(x);\n    } \n\n   /**\n     * Write the 8-bit byte to standard output.\n     * @param x the {@code byte} to write.\n     */\n    public static void write(byte x) {\n        writeByte(x & 0xff);\n    }\n\n   /**\n     * Write the 32-bit int to standard output.\n     * @param x the {@code int} to write.\n     */\n    public static void write(int x) {\n        writeByte((x >>> 24) & 0xff);\n        writeByte((x >>> 16) & 0xff);\n        writeByte((x >>>  8) & 0xff);\n        writeByte((x >>>  0) & 0xff);\n    }\n\n   /**\n     * Write the r-bit int to standard output.\n     * @param x the {@code int} to write.\n     * @param r the number of relevant bits in the char.\n     * @throws IllegalArgumentException if {@code r} is not between 1 and 32.\n     * @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.\n     */\n    public static void write(int x, int r) {\n        if (r == 32) {\n            write(x);\n            return;\n        }\n        if (r < 1 || r > 32)        throw new IllegalArgumentException(\"Illegal value for r = \" + r);\n        if (x < 0 || x >= (1 << r)) throw new IllegalArgumentException(\"Illegal \" + r + \"-bit char = \" + x);\n        for (int i = 0; i < r; i++) {\n            boolean bit = ((x >>> (r - i - 1)) & 1) == 1;\n            writeBit(bit);\n        }\n    }\n\n\n\n\n\n   /**\n     * Write the 64-bit double to standard output.\n     * @param x the {@code double} to write.\n     */\n    public static void write(double x) {\n        write(Double.doubleToRawLongBits(x));\n    }\n\n   /**\n     * Write the 64-bit long to standard output.\n     * @param x the {@code long} to write.\n     */\n    public static void write(long x) {\n        writeByte((int) ((x >>> 56) & 0xff));\n        writeByte((int) ((x >>> 48) & 0xff));\n        writeByte((int) ((x >>> 40) & 0xff));\n        writeByte((int) ((x >>> 32) & 0xff));\n        writeByte((int) ((x >>> 24) & 0xff));\n        writeByte((int) ((x >>> 16) & 0xff));\n        writeByte((int) ((x >>>  8) & 0xff));\n        writeByte((int) ((x >>>  0) & 0xff));\n    }\n\n   /**\n     * Write the 32-bit float to standard output.\n     * @param x the {@code float} to write.\n     */\n    public static void write(float x) {\n        write(Float.floatToRawIntBits(x));\n    }\n\n   /**\n     * Write the 16-bit int to standard output.\n     * @param x the {@code short} to write.\n     */\n    public static void write(short x) {\n        writeByte((x >>>  8) & 0xff);\n        writeByte((x >>>  0) & 0xff);\n    }\n\n   /**\n     * Write the 8-bit char to standard output.\n     * @param x the {@code char} to write.\n     * @throws IllegalArgumentException if {@code x} is not betwen 0 and 255.\n     */\n    public static void write(char x) {\n        if (x < 0 || x >= 256) throw new IllegalArgumentException(\"Illegal 8-bit char = \" + x);\n        writeByte(x);\n    }\n\n   /**\n     * Write the r-bit char to standard output.\n     * @param x the {@code char} to write.\n     * @param r the number of relevant bits in the char.\n     * @throws IllegalArgumentException if {@code r} is not between 1 and 16.\n     * @throws IllegalArgumentException if {@code x} is not between 0 and 2<sup>r</sup> - 1.\n     */\n    public static void write(char x, int r) {\n        if (r == 8) {\n            write(x);\n            return;\n        }\n        if (r < 1 || r > 16) throw new IllegalArgumentException(\"Illegal value for r = \" + r);\n        if (x >= (1 << r))   throw new IllegalArgumentException(\"Illegal \" + r + \"-bit char = \" + x);\n        for (int i = 0; i < r; i++) {\n            boolean bit = ((x >>> (r - i - 1)) & 1) == 1;\n            writeBit(bit);\n        }\n    }\n\n   /**\n     * Write the string of 8-bit characters to standard output.\n     * @param s the {@code String} to write.\n     * @throws IllegalArgumentException if any character in the string is not\n     * between 0 and 255.\n     */\n    public static void write(String s) {\n        for (int i = 0; i < s.length(); i++)\n            write(s.charAt(i));\n    }\n\n   /**\n     * Write the String of r-bit characters to standard output.\n     * @param s the {@code String} to write.\n     * @param r the number of relevants bits in each character.\n     * @throws IllegalArgumentException if r is not between 1 and 16.\n     * @throws IllegalArgumentException if any character in the string is not\n     * between 0 and 2<sup>r</sup> - 1.\n     */\n    public static void write(String s, int r) {\n        for (int i = 0; i < s.length(); i++)\n            write(s.charAt(i), r);\n    }\n\n   /**\n     * Test client.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int m = Integer.parseInt(args[0]);\n\n        // write n integers to binary standard output\n        for (int i = 0; i < m; i++) {\n            BinaryStdOut.write(i);\n        }\n        BinaryStdOut.flush();\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Counter.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Counter.java\n *  Execution:    java Counter n trials\n *  Dependencies: StdRandom.java StdOut.java\n *\n *  A mutable data type for an integer counter.\n *\n *  The test clients create n counters and performs trials increment\n *  operations on random counters.\n *\n * java Counter 6 600000\n *  100140 counter0\n *  100273 counter1\n *  99848 counter2\n *  100129 counter3\n *  99973 counter4\n *  99637 counter5\n *\n ******************************************************************************/\n\npackage algs4;\n\n/**\n *  The {@code Counter} class is a mutable data type to encapsulate a counter.\n *  <p>\n *  For additional documentation,\n *  see <a href=\"http://algs4.cs.princeton.edu/12oop\">Section 1.2</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Counter implements Comparable<Counter> {\n\n    private final String name;     // counter name\n    private int count = 0;         // current value\n\n    /**\n     * Initializes a new counter starting at 0, with the given id.\n     *\n     * @param id the name of the counter\n     */\n    public Counter(String id) {\n        name = id;\n    } \n\n    /**\n     * Increments the counter by 1.\n     */\n    public void increment() {\n        count++;\n    } \n\n    /**\n     * Returns the current value of this counter.\n     *\n     * @return the current value of this counter\n     */\n    public int tally() {\n        return count;\n    } \n\n    /**\n     * Returns a string representation of this counter.\n     *\n     * @return a string representation of this counter\n     */\n    public String toString() {\n        return count + \" \" + name;\n    } \n\n    /**\n     * Compares this counter to the specified counter.\n     *\n     * @param  that the other counter\n     * @return {@code 0} if the value of this counter equals\n     *         the value of that counter; a negative integer if\n     *         the value of this counter is less than the value of\n     *         that counter; and a positive integer if the value\n     *         of this counter is greater than the value of that\n     *         counter\n     */\n    @Override\n    public int compareTo(Counter that) {\n        if      (this.count < that.count) return -1;\n        else if (this.count > that.count) return +1;\n        else                              return  0;\n    }\n\n\n    /**\n     * Reads two command-line integers n and trials; creates n counters;\n     * increments trials counters at random; and prints results.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) { \n        int n = Integer.parseInt(args[0]);\n        int trials = Integer.parseInt(args[1]);\n\n        // create n counters\n        Counter[] hits = new Counter[n];\n        for (int i = 0; i < n; i++) {\n            hits[i] = new Counter(\"counter\" + i);\n        }\n\n        // increment trials counters at random\n        for (int t = 0; t < trials; t++) {\n            hits[StdRandom.uniform(n)].increment();\n        }\n\n        // print results\n        for (int i = 0; i < n; i++) {\n            StdOut.println(hits[i]);\n        }\n    } \n} \n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/DepthFirstOrder.java",
    "content": "///******************************************************************************\n// *  Compilation:  javac DepthFirstOrder.java\n// *  Execution:    java DepthFirstOrder digraph.txt\n// *  Dependencies: Digraph.java Queue.java Stack.java StdOut.java\n// *                EdgeWeightedDigraph.java DirectedEdge.java\n// *  Data files:   http://algs4.cs.princeton.edu/42digraph/tinyDAG.txt\n// *                http://algs4.cs.princeton.edu/42digraph/tinyDG.txt\n// *\n// *  Compute preorder and postorder for a digraph or edge-weighted digraph.\n// *  Runs in O(E + V) time.\n// *\n// *  % java DepthFirstOrder tinyDAG.txt\n// *     v  pre post\n// *  --------------\n// *     0    0    8\n// *     1    3    2\n// *     2    9   10\n// *     3   10    9\n// *     4    2    0\n// *     5    1    1\n// *     6    4    7\n// *     7   11   11\n// *     8   12   12\n// *     9    5    6\n// *    10    8    5\n// *    11    6    4\n// *    12    7    3\n// *  Preorder:  0 5 4 1 6 9 11 12 10 2 3 7 8 \n// *  Postorder: 4 5 1 12 11 10 9 6 0 3 2 7 8 \n// *  Reverse postorder: 8 7 2 3 0 6 9 10 11 12 1 5 4 \n// *\n// ******************************************************************************/\n//\n//package algs4;\n//\n//import com.jimmysun.algorithms.chapter4_2.Digraph;\n//import com.jimmysun.algorithms.chapter4_4.DirectedEdge;\n//import com.jimmysun.algorithms.chapter4_4.EdgeWeightedDigraph;\n//\n///**\n// *  The {@code DepthFirstOrder} class represents a data type for \n// *  determining depth-first search ordering of the vertices in a digraph\n// *  or edge-weighted digraph, including preorder, postorder, and reverse postorder.\n// *  <p>\n// *  This implementation uses depth-first search.\n// *  The constructor takes time proportional to <em>V</em> + <em>E</em>\n// *  (in the worst case),\n// *  where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.\n// *  Afterwards, the <em>preorder</em>, <em>postorder</em>, and <em>reverse postorder</em>\n// *  operation takes take time proportional to <em>V</em>.\n// *  <p>\n// *  For additional documentation,\n// *  see <a href=\"http://algs4.cs.princeton.edu/42digraph\">Section 4.2</a> of\n// *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n// *\n// *  @author Robert Sedgewick\n// *  @author Kevin Wayne\n// */\n//public class DepthFirstOrder {\n//    private boolean[] marked;          // marked[v] = has v been marked in dfs?\n//    private int[] pre;                 // pre[v]    = preorder  number of v\n//    private int[] post;                // post[v]   = postorder number of v\n//    private Queue<Integer> preorder;   // vertices in preorder\n//    private Queue<Integer> postorder;  // vertices in postorder\n//    private int preCounter;            // counter or preorder numbering\n//    private int postCounter;           // counter for postorder numbering\n//\n//    /**\n//     * Determines a depth-first order for the digraph {@code G}.\n//     * @param G the digraph\n//     */\n//    public DepthFirstOrder(Digraph G) {\n//        pre    = new int[G.V()];\n//        post   = new int[G.V()];\n//        postorder = new Queue<Integer>();\n//        preorder  = new Queue<Integer>();\n//        marked    = new boolean[G.V()];\n//        for (int v = 0; v < G.V(); v++)\n//            if (!marked[v]) dfs(G, v);\n//\n//        assert check();\n//    }\n//\n//    /**\n//     * Determines a depth-first order for the edge-weighted digraph {@code G}.\n//     * @param G the edge-weighted digraph\n//     */\n//    public DepthFirstOrder(EdgeWeightedDigraph G) {\n//        pre    = new int[G.V()];\n//        post   = new int[G.V()];\n//        postorder = new Queue<Integer>();\n//        preorder  = new Queue<Integer>();\n//        marked    = new boolean[G.V()];\n//        for (int v = 0; v < G.V(); v++)\n//            if (!marked[v]) dfs(G, v);\n//    }\n//\n//    // run DFS in digraph G from vertex v and compute preorder/postorder\n//    private void dfs(Digraph G, int v) {\n//        marked[v] = true;\n//        pre[v] = preCounter++;\n//        preorder.enqueue(v);\n//        for (int w : G.adj(v)) {\n//            if (!marked[w]) {\n//                dfs(G, w);\n//            }\n//        }\n//        postorder.enqueue(v);\n//        post[v] = postCounter++;\n//    }\n//\n//    // run DFS in edge-weighted digraph G from vertex v and compute preorder/postorder\n//    private void dfs(EdgeWeightedDigraph G, int v) {\n//        marked[v] = true;\n//        pre[v] = preCounter++;\n//        preorder.enqueue(v);\n//        for (DirectedEdge e : G.adj(v)) {\n//            int w = e.to();\n//            if (!marked[w]) {\n//                dfs(G, w);\n//            }\n//        }\n//        postorder.enqueue(v);\n//        post[v] = postCounter++;\n//    }\n//\n//    /**\n//     * Returns the preorder number of vertex {@code v}.\n//     * @param  v the vertex\n//     * @return the preorder number of vertex {@code v}\n//     * @throws IllegalArgumentException unless {@code 0 <= v < V}\n//     */\n//    public int pre(int v) {\n//        validateVertex(v);\n//        return pre[v];\n//    }\n//\n//    /**\n//     * Returns the postorder number of vertex {@code v}.\n//     * @param  v the vertex\n//     * @return the postorder number of vertex {@code v}\n//     * @throws IllegalArgumentException unless {@code 0 <= v < V}\n//     */\n//    public int post(int v) {\n//        validateVertex(v);\n//        return post[v];\n//    }\n//\n//    /**\n//     * Returns the vertices in postorder.\n//     * @return the vertices in postorder, as an iterable of vertices\n//     */\n//    public Iterable<Integer> post() {\n//        return postorder;\n//    }\n//\n//    /**\n//     * Returns the vertices in preorder.\n//     * @return the vertices in preorder, as an iterable of vertices\n//     */\n//    public Iterable<Integer> pre() {\n//        return preorder;\n//    }\n//\n//    /**\n//     * Returns the vertices in reverse postorder.\n//     * @return the vertices in reverse postorder, as an iterable of vertices\n//     */\n//    public Iterable<Integer> reversePost() {\n//        Stack<Integer> reverse = new Stack<Integer>();\n//        for (int v : postorder)\n//            reverse.push(v);\n//        return reverse;\n//    }\n//\n//\n//    // check that pre() and post() are consistent with pre(v) and post(v)\n//    private boolean check() {\n//\n//        // check that post(v) is consistent with post()\n//        int r = 0;\n//        for (int v : post()) {\n//            if (post(v) != r) {\n//                StdOut.println(\"post(v) and post() inconsistent\");\n//                return false;\n//            }\n//            r++;\n//        }\n//\n//        // check that pre(v) is consistent with pre()\n//        r = 0;\n//        for (int v : pre()) {\n//            if (pre(v) != r) {\n//                StdOut.println(\"pre(v) and pre() inconsistent\");\n//                return false;\n//            }\n//            r++;\n//        }\n//\n//        return true;\n//    }\n//\n//    // throw an IllegalArgumentException unless {@code 0 <= v < V}\n//    private void validateVertex(int v) {\n//        int V = marked.length;\n//        if (v < 0 || v >= V)\n//            throw new IllegalArgumentException(\"vertex \" + v + \" is not between 0 and \" + (V-1));\n//    }\n//\n//    /**\n//     * Unit tests the {@code DepthFirstOrder} data type.\n//     *\n//     * @param args the command-line arguments\n//     */\n//    public static void main(String[] args) {\n//        In in = new In(args[0]);\n//        Digraph G = new Digraph(in);\n//\n//        DepthFirstOrder dfs = new DepthFirstOrder(G);\n//        StdOut.println(\"   v  pre post\");\n//        StdOut.println(\"--------------\");\n//        for (int v = 0; v < G.V(); v++) {\n//            StdOut.printf(\"%4d %4d %4d\\n\", v, dfs.pre(v), dfs.post(v));\n//        }\n//\n//        StdOut.print(\"Preorder:  \");\n//        for (int v : dfs.pre()) {\n//            StdOut.print(v + \" \");\n//        }\n//        StdOut.println();\n//\n//        StdOut.print(\"Postorder: \");\n//        for (int v : dfs.post()) {\n//            StdOut.print(v + \" \");\n//        }\n//        StdOut.println();\n//\n//        StdOut.print(\"Reverse postorder: \");\n//        for (int v : dfs.reversePost()) {\n//            StdOut.print(v + \" \");\n//        }\n//        StdOut.println();\n//\n//\n//    }\n//\n//}\n//\n///******************************************************************************\n// *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n// *\n// *  This file is part of algs4.jar, which accompanies the textbook\n// *\n// *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n// *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n// *      http://algs4.cs.princeton.edu\n// *\n// *\n// *  algs4.jar is free software: you can redistribute it and/or modify\n// *  it under the terms of the GNU General Public License as published by\n// *  the Free Software Foundation, either version 3 of the License, or\n// *  (at your option) any later version.\n// *\n// *  algs4.jar is distributed in the hope that it will be useful,\n// *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n// *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// *  GNU General Public License for more details.\n// *\n// *  You should have received a copy of the GNU General Public License\n// *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n// ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Draw.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Draw.java\n *  Execution:    java Draw\n *  Dependencies: none\n *\n *  Drawing library. This class provides a basic capability for creating\n *  drawings with your programs. It uses a simple graphics model that\n *  allows you to create drawings consisting of points, lines, and curves\n *  in a window on your computer and to save the drawings to a file.\n *  This is the object-oriented version of standard draw; it supports\n *  multiple indepedent drawing windows.\n *\n *  Todo\n *  ----\n *    -  Add support for gradient fill, etc.\n *\n *  Remarks\n *  -------\n *    -  don't use AffineTransform for rescaling since it inverts\n *       images and strings\n *    -  careful using setFont in inner loop within an animation -\n *       it can cause flicker\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.awt.BasicStroke;\nimport java.awt.Color;\nimport java.awt.FileDialog;\nimport java.awt.Font;\nimport java.awt.FontMetrics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.RenderingHints;\nimport java.awt.Toolkit;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport java.awt.geom.Arc2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.geom.GeneralPath;\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Rectangle2D;\n\nimport java.awt.image.BufferedImage;\nimport java.awt.image.DirectColorModel;\nimport java.awt.image.WritableRaster;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport java.net.URL;\n\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.TreeSet;\n\nimport javax.imageio.ImageIO;\n\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.KeyStroke;\n\n/**\n *  <i>Draw</i>. This class provides a basic capability for\n *  creating drawings with your programs. It uses a simple graphics model that\n *  allows you to create drawings consisting of points, lines, and curves\n *  in a window on your computer and to save the drawings to a file.\n *  This is the object-oriented version of standard draw; it supports\n *  multiple indepedent drawing windows.\n *  <p>\n *  For additional documentation, see <a href=\"http://introcs.cs.princeton.edu/31datatype\">Section 3.1</a> of\n *  <i>Computer Science: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class Draw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {\n\n    /**\n     *  The color black.\n     */\n    public static final Color BLACK = Color.BLACK;\n\n    /**\n     *  The color blue.\n     */\n    public static final Color BLUE = Color.BLUE;\n\n    /**\n     *  The color cyan.\n     */\n    public static final Color CYAN = Color.CYAN;\n\n    /**\n     *  The color dark gray.\n     */\n    public static final Color DARK_GRAY = Color.DARK_GRAY;\n\n    /**\n     *  The color gray.\n     */\n    public static final Color GRAY = Color.GRAY;\n\n    /**\n     *  The color green.\n     */\n    public static final Color GREEN  = Color.GREEN;\n\n    /**\n     *  The color light gray.\n     */\n    public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;\n\n    /**\n     *  The color magenta.\n     */\n    public static final Color MAGENTA = Color.MAGENTA;\n\n    /**\n     *  The color orange.\n     */\n    public static final Color ORANGE = Color.ORANGE;\n\n    /**\n     *  The color pink.\n     */\n    public static final Color PINK = Color.PINK;\n\n    /**\n     *  The color red.\n     */\n    public static final Color RED = Color.RED;\n\n    /**\n     *  The color white.\n     */\n    public static final Color WHITE = Color.WHITE;\n\n    /**\n     *  The color yellow.\n     */\n    public static final Color YELLOW = Color.YELLOW;\n\n    /**\n     * Shade of blue used in Introduction to Programming in Java.\n     * It is Pantone 300U. The RGB values are approximately (9, 90, 166).\n     */\n    public static final Color BOOK_BLUE = new Color(9, 90, 166);\n\n    /**\n     * Shade of light blue used in Introduction to Programming in Java.\n     * The RGB values are approximately (103, 198, 243).\n     */\n    public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);\n    \n    /**\n     * Shade of red used in <em>Algorithms, 4th edition</em>.\n     * It is Pantone 1805U. The RGB values are approximately (150, 35, 31).\n     */\n    public static final Color BOOK_RED = new Color(150, 35, 31);\n\n    // default colors\n    private static final Color DEFAULT_PEN_COLOR   = BLACK;\n    private static final Color DEFAULT_CLEAR_COLOR = WHITE;\n\n    // boundary of drawing canvas, 0% border\n    private static final double BORDER = 0.0;\n    private static final double DEFAULT_XMIN = 0.0;\n    private static final double DEFAULT_XMAX = 1.0;\n    private static final double DEFAULT_YMIN = 0.0;\n    private static final double DEFAULT_YMAX = 1.0;\n\n    // default canvas size is SIZE-by-SIZE\n    private static final int DEFAULT_SIZE = 512;\n\n    // default pen radius\n    private static final double DEFAULT_PEN_RADIUS = 0.002;\n\n    // default font\n    private static final Font DEFAULT_FONT = new Font(\"SansSerif\", Font.PLAIN, 16);\n\n    // current pen color\n    private Color penColor;\n\n    // canvas size\n    private int width  = DEFAULT_SIZE;\n    private int height = DEFAULT_SIZE;\n\n    // current pen radius\n    private double penRadius;\n\n    // show we draw immediately or wait until next show?\n    private boolean defer = false;\n\n    private double xmin, ymin, xmax, ymax;\n\n    // name of window\n    private String name = \"Draw\";\n\n    // for synchronization\n    private final Object mouseLock = new Object();\n    private final Object keyLock = new Object();\n\n    // current font\n    private Font font;\n\n    // the JLabel for drawing\n    private JLabel draw;\n\n    // double buffered graphics\n    private BufferedImage offscreenImage, onscreenImage;\n    private Graphics2D offscreen, onscreen;\n\n    // the frame for drawing to the screen\n    private JFrame frame = new JFrame();\n\n    // mouse state\n    private boolean mousePressed = false;\n    private double mouseX = 0;\n    private double mouseY = 0;\n\n    // keyboard state\n    private final LinkedList<Character> keysTyped = new LinkedList<Character>();\n    private final TreeSet<Integer> keysDown = new TreeSet<Integer>();\n\n    // event-based listeners\n    private final ArrayList<DrawListener> listeners = new ArrayList<DrawListener>();\n\n\n    /**\n     * Initializes an empty drawing object with the given name.\n     *\n     * @param name the title of the drawing window.\n     */\n    public Draw(String name) {\n        this.name = name;\n        init();\n    }\n\n    /**\n     * Initializes an empty drawing object.\n     */\n    public Draw() {\n        init();\n    }\n\n    private void init() {\n        if (frame != null) frame.setVisible(false);\n        frame = new JFrame();\n        offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n        onscreenImage  = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n        offscreen = offscreenImage.createGraphics();\n        onscreen  = onscreenImage.createGraphics();\n        setXscale();\n        setYscale();\n        offscreen.setColor(DEFAULT_CLEAR_COLOR);\n        offscreen.fillRect(0, 0, width, height);\n        setPenColor();\n        setPenRadius();\n        setFont();\n        clear();\n\n        // add antialiasing\n        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,\n                                                  RenderingHints.VALUE_ANTIALIAS_ON);\n        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);\n        offscreen.addRenderingHints(hints);\n\n        // frame stuff\n        ImageIcon icon = new ImageIcon(onscreenImage);\n        draw = new JLabel(icon);\n\n        draw.addMouseListener(this);\n        draw.addMouseMotionListener(this);\n\n        frame.setContentPane(draw);\n        frame.addKeyListener(this);    // JLabel cannot get keyboard focus\n        frame.setResizable(false);\n        // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            // closes all windows\n        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      // closes only current window\n        frame.setTitle(name);\n        frame.setJMenuBar(createMenuBar());\n        frame.pack();\n        frame.requestFocusInWindow();\n        frame.setVisible(true);\n    }\n\n\n    /**\n     * Sets the upper-left hand corner of the drawing window to be (x, y), where (0, 0) is upper left.\n     *\n     * @param  x the number of pixels from the left\n     * @param  y the number of pixels from the top\n     * @throws IllegalArgumentException if the width or height is 0 or negative\n     */\n    public void setLocationOnScreen(int x, int y) {\n        if (x <= 0 || y <= 0) throw new IllegalArgumentException();\n        frame.setLocation(x, y);\n    }\n\n    /**\n     * Sets the default close operation.\n     *\n     * @param  value the value, typically {@code JFrame.EXIT_ON_CLOSE}\n     *         (close all windows) or {@code JFrame.DISPOSE_ON_CLOSE}\n     *         (close current window)\n     */\n    public void setDefaultCloseOperation(int value) {\n        frame.setDefaultCloseOperation(value);\n    }\n       \n\n    /**\n     * Sets the canvas (drawing area) to be <em>width</em>-by-<em>height</em> pixels.\n     * This also erases the current drawing and resets the coordinate system, pen radius,\n     * pen color, and font back to their default values.\n     * Ordinarly, this method is called once, at the very beginning of a program.\n     *\n     * @param  canvasWidth the width as a number of pixels\n     * @param  canvasHeight the height as a number of pixels\n     * @throws IllegalArgumentException unless both {@code canvasWidth}\n     *         and {@code canvasHeight} are positive\n     */\n    public void setCanvasSize(int canvasWidth, int canvasHeight) {\n        if (canvasWidth < 1 || canvasHeight < 1) {\n            throw new IllegalArgumentException(\"width and height must be positive\");\n        }\n        width = canvasWidth;\n        height = canvasHeight;\n        init();\n    }\n\n\n    // create the menu bar (changed to private)\n    private JMenuBar createMenuBar() {\n        JMenuBar menuBar = new JMenuBar();\n        JMenu menu = new JMenu(\"File\");\n        menuBar.add(menu);\n        JMenuItem menuItem1 = new JMenuItem(\" Save...   \");\n        menuItem1.addActionListener(this);\n        menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,\n                                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));\n        menu.add(menuItem1);\n        return menuBar;\n    }\n\n\n   /***************************************************************************\n    *  User and screen coordinate systems.\n    ***************************************************************************/\n\n    /**\n     * Sets the x-scale to be the default (between 0.0 and 1.0).\n     */\n    public void setXscale() {\n        setXscale(DEFAULT_XMIN, DEFAULT_XMAX);\n    }\n\n    /**\n     * Sets the y-scale to be the default (between 0.0 and 1.0).\n     */\n    public void setYscale() {\n        setYscale(DEFAULT_YMIN, DEFAULT_YMAX);\n    }\n\n    /**\n     * Sets the x-scale.\n     *\n     * @param min the minimum value of the x-scale\n     * @param max the maximum value of the x-scale\n     */\n    public void setXscale(double min, double max) {\n        double size = max - min;\n        xmin = min - BORDER * size;\n        xmax = max + BORDER * size;\n    }\n\n    /**\n     * Sets the y-scale.\n     *\n     * @param min the minimum value of the y-scale\n     * @param max the maximum value of the y-scale\n     */\n    public void setYscale(double min, double max) {\n        double size = max - min;\n        ymin = min - BORDER * size;\n        ymax = max + BORDER * size;\n    }\n\n    // helper functions that scale from user coordinates to screen coordinates and back\n    private double  scaleX(double x) { return width  * (x - xmin) / (xmax - xmin); }\n    private double  scaleY(double y) { return height * (ymax - y) / (ymax - ymin); }\n    private double factorX(double w) { return w * width  / Math.abs(xmax - xmin);  }\n    private double factorY(double h) { return h * height / Math.abs(ymax - ymin);  }\n    private double   userX(double x) { return xmin + x * (xmax - xmin) / width;    }\n    private double   userY(double y) { return ymax - y * (ymax - ymin) / height;   }\n\n\n    /**\n     * Clears the screen to the default color (white).\n     */\n    public void clear() {\n        clear(DEFAULT_CLEAR_COLOR);\n    }\n\n    /**\n     * Clears the screen to the given color.\n     *\n     * @param color the color to make the background\n     */\n    public void clear(Color color) {\n        offscreen.setColor(color);\n        offscreen.fillRect(0, 0, width, height);\n        offscreen.setColor(penColor);\n        draw();\n    }\n\n    /**\n     * Gets the current pen radius.\n     *\n     * @return the current pen radius\n     */\n    public double getPenRadius() {\n        return penRadius;\n    }\n\n    /**\n     * Sets the pen size to the default (.002).\n     */\n    public void setPenRadius() {\n        setPenRadius(DEFAULT_PEN_RADIUS);\n    }\n\n    /**\n     * Sets the radius of the pen to the given size.\n     *\n     * @param  r the radius of the pen\n     * @throws IllegalArgumentException if r is negative\n     */\n    public void setPenRadius(double r) {\n        if (r < 0) throw new IllegalArgumentException(\"pen radius must be positive\");\n        penRadius = r * DEFAULT_SIZE;\n        BasicStroke stroke = new BasicStroke((float) penRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\n        // BasicStroke stroke = new BasicStroke((float) penRadius);\n        offscreen.setStroke(stroke);\n    }\n\n    /**\n     * Gets the current pen color.\n     *\n     * @return the current pen color\n     */\n    public Color getPenColor() {\n        return penColor;\n    }\n\n    /**\n     * Sets the pen color to the default color (black).\n     */\n    public void setPenColor() {\n        setPenColor(DEFAULT_PEN_COLOR);\n    }\n\n    /**\n     * Sets the pen color to the given color.\n     *\n     * @param color the color to make the pen\n     */\n    public void setPenColor(Color color) {\n        penColor = color;\n        offscreen.setColor(penColor);\n    }\n\n    /**\n     * Sets the pen color to the given RGB color.\n     *\n     * @param  red the amount of red (between 0 and 255)\n     * @param  green the amount of green (between 0 and 255)\n     * @param  blue the amount of blue (between 0 and 255)\n     * @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range\n     */\n    public void setPenColor(int red, int green, int blue) {\n        if (red   < 0 || red   >= 256) throw new IllegalArgumentException(\"amount of red must be between 0 and 255\");\n        if (green < 0 || green >= 256) throw new IllegalArgumentException(\"amount of red must be between 0 and 255\");\n        if (blue  < 0 || blue  >= 256) throw new IllegalArgumentException(\"amount of red must be between 0 and 255\");\n        setPenColor(new Color(red, green, blue));\n    }\n\n\n    /**\n     * Turns on xor mode.\n     */\n    public void xorOn() {\n        offscreen.setXORMode(DEFAULT_CLEAR_COLOR);\n    }\n\n    /**\n     * Turns off xor mode.\n     */\n    public void xorOff() {\n        offscreen.setPaintMode();\n    }\n\n    /**\n     * Gets the current {@code JLabel} for use in some other GUI.\n     *\n     * @return the current {@code JLabel}\n     */\n    public JLabel getJLabel() {\n        return draw;\n    }\n\n    /**\n     * Gets the current font.\n     *\n     * @return the current font\n     */\n    public Font getFont() {\n        return font;\n    }\n\n    /**\n     * Sets the font to the default font (sans serif, 16 point).\n     */\n    public void setFont() {\n        setFont(DEFAULT_FONT);\n    }\n\n    /**\n     * Sets the font to the given value.\n     *\n     * @param font the font\n     */\n    public void setFont(Font font) {\n        this.font = font;\n    }\n\n\n   /***************************************************************************\n    *  Drawing geometric shapes.\n    ***************************************************************************/\n\n    /**\n     * Draws a line from (x0, y0) to (x1, y1).\n     *\n     * @param x0 the x-coordinate of the starting point\n     * @param y0 the y-coordinate of the starting point\n     * @param x1 the x-coordinate of the destination point\n     * @param y1 the y-coordinate of the destination point\n     */\n    public void line(double x0, double y0, double x1, double y1) {\n        offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));\n        draw();\n    }\n\n    /**\n     * Draws one pixel at (x, y).\n     *\n     * @param x the x-coordinate of the pixel\n     * @param y the y-coordinate of the pixel\n     */\n    private void pixel(double x, double y) {\n        offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);\n    }\n\n    /**\n     * Draws a point at (x, y).\n     *\n     * @param x the x-coordinate of the point\n     * @param y the y-coordinate of the point\n     */\n    public void point(double x, double y) {\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double r = penRadius;\n        // double ws = factorX(2*r);\n        // double hs = factorY(2*r);\n        // if (ws <= 1 && hs <= 1) pixel(x, y);\n        if (r <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - r/2, ys - r/2, r, r));\n        draw();\n    }\n\n    /**\n     * Draws a circle of radius r, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the circle\n     * @param  y the y-coordinate of the center of the circle\n     * @param  r the radius of the circle\n     * @throws IllegalArgumentException if the radius of the circle is negative\n     */\n    public void circle(double x, double y, double r) {\n        if (r < 0) throw new IllegalArgumentException(\"circle radius can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*r);\n        double hs = factorY(2*r);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled circle of radius r, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the circle\n     * @param  y the y-coordinate of the center of the circle\n     * @param  r the radius of the circle\n     * @throws IllegalArgumentException if the radius of the circle is negative\n     */\n    public void filledCircle(double x, double y, double r) {\n        if (r < 0) throw new IllegalArgumentException(\"circle radius can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*r);\n        double hs = factorY(2*r);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws an ellipse with given semimajor and semiminor axes, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the ellipse\n     * @param  y the y-coordinate of the center of the ellipse\n     * @param  semiMajorAxis is the semimajor axis of the ellipse\n     * @param  semiMinorAxis is the semiminor axis of the ellipse\n     * @throws IllegalArgumentException if either of the axes are negative\n     */\n    public void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {\n        if (semiMajorAxis < 0) throw new IllegalArgumentException(\"ellipse semimajor axis can't be negative\");\n        if (semiMinorAxis < 0) throw new IllegalArgumentException(\"ellipse semiminor axis can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*semiMajorAxis);\n        double hs = factorY(2*semiMinorAxis);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws an ellipse with given semimajor and semiminor axes, centered on (x, y).\n     * @param  x the x-coordinate of the center of the ellipse\n     * @param  y the y-coordinate of the center of the ellipse\n     * @param  semiMajorAxis is the semimajor axis of the ellipse\n     * @param  semiMinorAxis is the semiminor axis of the ellipse\n     * @throws IllegalArgumentException if either of the axes are negative\n     */\n    public void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {\n        if (semiMajorAxis < 0) throw new IllegalArgumentException(\"ellipse semimajor axis can't be negative\");\n        if (semiMinorAxis < 0) throw new IllegalArgumentException(\"ellipse semiminor axis can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*semiMajorAxis);\n        double hs = factorY(2*semiMinorAxis);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws an arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).\n     *\n     * @param  x the x-coordinate of the center of the circle\n     * @param  y the y-coordinate of the center of the circle\n     * @param  r the radius of the circle\n     * @param  angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.\n     * @param  angle2 the angle at the end of the arc. For example, if\n     *         you want a 90 degree arc, then angle2 should be angle1 + 90.\n     * @throws IllegalArgumentException if the radius of the circle is negative\n     */\n    public void arc(double x, double y, double r, double angle1, double angle2) {\n        if (r < 0) throw new IllegalArgumentException(\"arc radius can't be negative\");\n        while (angle2 < angle1) angle2 += 360;\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*r);\n        double hs = factorY(2*r);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));\n        draw();\n    }\n\n    /**\n     * Draws a square of side length 2r, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the square\n     * @param  y the y-coordinate of the center of the square\n     * @param  r radius is half the length of any side of the square\n     * @throws IllegalArgumentException if r is negative\n     */\n    public void square(double x, double y, double r) {\n        if (r < 0) throw new IllegalArgumentException(\"square side length can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*r);\n        double hs = factorY(2*r);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled square of side length 2r, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the square\n     * @param  y the y-coordinate of the center of the square\n     * @param  r radius is half the length of any side of the square\n     * @throws IllegalArgumentException if r is negative\n     */\n    public void filledSquare(double x, double y, double r) {\n        if (r < 0) throw new IllegalArgumentException(\"square side length can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*r);\n        double hs = factorY(2*r);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws a rectangle of given half width and half height, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the rectangle\n     * @param  y the y-coordinate of the center of the rectangle\n     * @param  halfWidth is half the width of the rectangle\n     * @param  halfHeight is half the height of the rectangle\n     * @throws IllegalArgumentException if halfWidth or halfHeight is negative\n     */\n    public void rectangle(double x, double y, double halfWidth, double halfHeight) {\n        if (halfWidth  < 0) throw new IllegalArgumentException(\"half width can't be negative\");\n        if (halfHeight < 0) throw new IllegalArgumentException(\"half height can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfWidth);\n        double hs = factorY(2*halfHeight);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled rectangle of given half width and half height, centered on (x, y).\n     *\n     * @param  x the x-coordinate of the center of the rectangle\n     * @param  y the y-coordinate of the center of the rectangle\n     * @param  halfWidth is half the width of the rectangle\n     * @param  halfHeight is half the height of the rectangle\n     * @throws IllegalArgumentException if halfWidth or halfHeight is negative\n     */\n    public void filledRectangle(double x, double y, double halfWidth, double halfHeight) {\n        if (halfWidth  < 0) throw new IllegalArgumentException(\"half width can't be negative\");\n        if (halfHeight < 0) throw new IllegalArgumentException(\"half height can't be negative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfWidth);\n        double hs = factorY(2*halfHeight);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a polygon with the given (x[i], y[i]) coordinates.\n     *\n     * @param x an array of all the x-coordindates of the polygon\n     * @param y an array of all the y-coordindates of the polygon\n     */\n    public void polygon(double[] x, double[] y) {\n        int n = x.length;\n        GeneralPath path = new GeneralPath();\n        path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));\n        for (int i = 0; i < n; i++)\n            path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));\n        path.closePath();\n        offscreen.draw(path);\n        draw();\n    }\n\n    /**\n     * Draws a filled polygon with the given (x[i], y[i]) coordinates.\n     *\n     * @param x an array of all the x-coordindates of the polygon\n     * @param y an array of all the y-coordindates of the polygon\n     */\n    public void filledPolygon(double[] x, double[] y) {\n        int n = x.length;\n        GeneralPath path = new GeneralPath();\n        path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));\n        for (int i = 0; i < n; i++)\n            path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));\n        path.closePath();\n        offscreen.fill(path);\n        draw();\n    }\n\n\n\n   /***************************************************************************\n    *  Drawing images.\n    ***************************************************************************/\n\n    private static BufferedImage getImage(String filename) {\n\n        // from a file or URL\n        try {\n            URL url = new URL(filename);\n            return ImageIO.read(url);\n        } \n        catch (IOException e) {\n            // ignore\n        }\n\n        // in case file is inside a .jar (classpath relative to StdDraw)\n        try {\n            URL url = StdDraw.class.getResource(filename);\n            return ImageIO.read(url);\n        } \n        catch (IOException e) {\n            // ignore\n        }\n\n        // in case file is inside a .jar (classpath relative to root of jar)\n        try {\n            URL url = StdDraw.class.getResource(\"/\" + filename);\n            return ImageIO.read(url);\n        } \n        catch (IOException e) {\n            // ignore\n        }\n        throw new IllegalArgumentException(\"image \" + filename + \" not found\");\n    }\n\n    /**\n     * Draws picture (gif, jpg, or png) centered on (x, y).\n     *\n     * @param  x the center x-coordinate of the image\n     * @param  y the center y-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @throws IllegalArgumentException if the image is corrupt\n     * @throws IllegalArgumentException if {@code filename} is {@code null}\n     */\n    public void picture(double x, double y, String filename) {\n        if (filename == null) throw new IllegalArgumentException(\"filename argument is null\");\n        BufferedImage image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int ws = image.getWidth();\n        int hs = image.getHeight();\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);\n        draw();\n    }\n\n    /**\n     * Draws picture (gif, jpg, or png) centered on (x, y),\n     * rotated given number of degrees.\n     *\n     * @param  x the center x-coordinate of the image\n     * @param  y the center y-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  degrees is the number of degrees to rotate counterclockwise\n     * @throws IllegalArgumentException if the image is corrupt\n     * @throws IllegalArgumentException if {@code filename} is {@code null}\n     */\n    public void picture(double x, double y, String filename, double degrees) {\n        if (filename == null) throw new IllegalArgumentException(\"filename argument is null\");\n        BufferedImage image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int ws = image.getWidth();\n        int hs = image.getHeight();\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n\n        draw();\n    }\n\n    /**\n     * Draws picture (gif, jpg, or png) centered on (x, y), rescaled to w-by-h.\n     *\n     * @param  x the center x coordinate of the image\n     * @param  y the center y coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  w the width of the image\n     * @param  h the height of the image\n     * @throws IllegalArgumentException if the image is corrupt\n     * @throws IllegalArgumentException if {@code filename} is {@code null}\n     */\n    public void picture(double x, double y, String filename, double w, double h) {\n        if (filename == null) throw new IllegalArgumentException(\"filename argument is null\");\n        Image image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(w);\n        double hs = factorY(h);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else {\n            offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),\n                                       (int) Math.round(ys - hs/2.0),\n                                       (int) Math.round(ws),\n                                       (int) Math.round(hs), null);\n        }\n        draw();\n    }\n\n\n    /**\n     * Draws picture (gif, jpg, or png) centered on (x, y), rotated\n     * given number of degrees, rescaled to w-by-h.\n     *\n     * @param  x the center x-coordinate of the image\n     * @param  y the center y-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  w the width of the image\n     * @param  h the height of the image\n     * @param  degrees is the number of degrees to rotate counterclockwise\n     * @throws IllegalArgumentException if the image is corrupt\n     * @throws IllegalArgumentException if {@code filename} is {@code null}\n     */\n    public void picture(double x, double y, String filename, double w, double h, double degrees) {\n        if (filename == null) throw new IllegalArgumentException(\"filename argument is null\");\n        Image image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(w);\n        double hs = factorY(h);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),\n                                   (int) Math.round(ys - hs/2.0),\n                                   (int) Math.round(ws),\n                                   (int) Math.round(hs), null);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n\n        draw();\n    }\n\n\n   /***************************************************************************\n    *  Drawing text.\n    ***************************************************************************/\n\n    /**\n     * Writes the given text string in the current font, centered on (x, y).\n     *\n     * @param x the center x-coordinate of the text\n     * @param y the center y-coordinate of the text\n     * @param s the text\n     */\n    public void text(double x, double y, String s) {\n        offscreen.setFont(font);\n        FontMetrics metrics = offscreen.getFontMetrics();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int ws = metrics.stringWidth(s);\n        int hs = metrics.getDescent();\n        offscreen.drawString(s, (float) (xs - ws/2.0), (float) (ys + hs));\n        draw();\n    }\n\n    /**\n     * Writes the given text string in the current font, centered on (x, y) and\n     * rotated by the specified number of degrees.\n     *\n     * @param x the center x-coordinate of the text\n     * @param y the center y-coordinate of the text\n     * @param s the text\n     * @param degrees is the number of degrees to rotate counterclockwise\n     */\n    public void text(double x, double y, String s, double degrees) {\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        text(x, y, s);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n    }\n\n    /**\n     * Writes the given text string in the current font, left-aligned at (x, y).\n     *\n     * @param x the x-coordinate of the text\n     * @param y the y-coordinate of the text\n     * @param s the text\n     */\n    public void textLeft(double x, double y, String s) {\n        offscreen.setFont(font);\n        FontMetrics metrics = offscreen.getFontMetrics();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        // int ws = metrics.stringWidth(s);\n        int hs = metrics.getDescent();\n        offscreen.drawString(s, (float) xs, (float) (ys + hs));\n        draw();\n    }\n\n\n    /**\n     * Displays on screen, pause for {@code t} milliseconds, and turn on\n     * <em>animation mode</em>.\n     * Subsequent calls to drawing methods such as {@code line()}, {@code circle()},\n     * and {@code square()} will not be displayed on screen until the next call to {@code show()}.\n     * This is useful for producing animations (clear the screen, draw a bunch of shapes,\n     * display on screen for a fixed amount of time, and repeat). It also speeds up\n     * drawing a huge number of shapes (call {@code show(0)} to defer drawing\n     * on screen, draw the shapes, and call {@code show(0)} to display them all\n     * on screen at once).\n     *\n     * @param t number of milliseconds\n     */\n    public void show(int t) {\n        defer = false;\n        draw();\n        try {\n            Thread.sleep(t);\n        }\n        catch (InterruptedException e) {\n            System.out.println(\"Error sleeping\");\n        }\n        defer = true;\n    }\n\n\n    /**\n     * Displays on-screen and turn off animation mode.\n     * Subsequent calls to drawing methods such as {@code line()}, {@code circle()},\n     * and {@code square()} will be displayed on screen when called. This is the default.\n     */\n    public void show() {\n        defer = false;\n        draw();\n    }\n\n    // draw onscreen if defer is false\n    private void draw() {\n        if (defer) return;\n        onscreen.drawImage(offscreenImage, 0, 0, null);\n        frame.repaint();\n    }\n\n    /**\n     * Saves this drawing to a file.\n     *\n     * @param  filename the name of the file (with suffix png, jpg, or gif)\n     */\n    public void save(String filename) {\n        File file = new File(filename);\n        String suffix = filename.substring(filename.lastIndexOf('.') + 1);\n\n        // png files\n        if (\"png\".equalsIgnoreCase(suffix)) {\n            try {\n                ImageIO.write(offscreenImage, suffix, file);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        // need to change from ARGB to RGB for jpeg\n        // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727\n        else if (\"jpg\".equalsIgnoreCase(suffix)) {\n            WritableRaster raster = offscreenImage.getRaster();\n            WritableRaster newRaster;\n            newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});\n            DirectColorModel cm = (DirectColorModel) offscreenImage.getColorModel();\n            DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),\n                                                          cm.getRedMask(),\n                                                          cm.getGreenMask(),\n                                                          cm.getBlueMask());\n            BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false,  null);\n            try {\n                ImageIO.write(rgbBuffer, suffix, file);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        else {\n            System.out.println(\"Invalid image file type: \" + suffix);\n        }\n    }\n\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void actionPerformed(ActionEvent e) {\n        FileDialog chooser = new FileDialog(frame, \"Use a .png or .jpg extension\", FileDialog.SAVE);\n        chooser.setVisible(true);\n        String filename = chooser.getFile();\n        if (filename != null) {\n            save(chooser.getDirectory() + File.separator + chooser.getFile());\n        }\n    }\n\n\n\n   /***************************************************************************\n    *  Event-based interactions.\n    ***************************************************************************/\n\n    /**\n     * Adds a {@link DrawListener} to listen to keyboard and mouse events.\n     *\n     * @param listener the {\\tt DrawListener} argument\n     */\n    public void addListener(DrawListener listener) {\n        // ensure there is a window for listenting to events\n        show();\n        listeners.add(listener);\n        frame.addKeyListener(this);\n        frame.addMouseListener(this);\n        frame.addMouseMotionListener(this);\n        frame.setFocusable(true); \n    }\n\n\n\n\n   /***************************************************************************\n    *  Mouse interactions.\n    ***************************************************************************/\n\n    /**\n     * Returns true if the mouse is being pressed.\n     *\n     * @return {@code true} if the mouse is being pressed;\n     *         {@code false} otherwise\n     */\n    public boolean mousePressed() {\n        synchronized (mouseLock) {\n            return mousePressed;\n        }\n    }\n\n    /**\n     * Returns the x-coordinate of the mouse.\n     * @return the x-coordinate of the mouse\n     */\n    public double mouseX() {\n        synchronized (mouseLock) {\n            return mouseX;\n        }\n    }\n\n    /**\n     * Returns the y-coordinate of the mouse.\n     *\n     * @return the y-coordinate of the mouse\n     */\n    public double mouseY() {\n        synchronized (mouseLock) {\n            return mouseY;\n        }\n    }\n\n\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseClicked(MouseEvent e) {\n        // this body is intentionally left empty\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseEntered(MouseEvent e) {\n        // this body is intentionally left empty\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseExited(MouseEvent e) {\n        // this body is intentionally left empty\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mousePressed(MouseEvent e) {\n        synchronized (mouseLock) {\n            mouseX = userX(e.getX());\n            mouseY = userY(e.getY());\n            mousePressed = true;\n        }\n        if (e.getButton() == MouseEvent.BUTTON1) {\n            for (DrawListener listener : listeners)\n                listener.mousePressed(userX(e.getX()), userY(e.getY()));\n        }\n\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseReleased(MouseEvent e) {\n        synchronized (mouseLock) {\n            mousePressed = false;\n        }\n        if (e.getButton() == MouseEvent.BUTTON1) {\n            for (DrawListener listener : listeners)\n                listener.mouseReleased(userX(e.getX()), userY(e.getY()));\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseDragged(MouseEvent e)  {\n        synchronized (mouseLock) {\n            mouseX = userX(e.getX());\n            mouseY = userY(e.getY());\n        }\n        // doesn't seem to work if a button is specified\n        for (DrawListener listener : listeners)\n            listener.mouseDragged(userX(e.getX()), userY(e.getY()));\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseMoved(MouseEvent e) {\n        synchronized (mouseLock) {\n            mouseX = userX(e.getX());\n            mouseY = userY(e.getY());\n        }\n    }\n\n\n   /***************************************************************************\n    *  Keyboard interactions.\n    ***************************************************************************/\n\n    /**\n     * Returns true if the user has typed a key.\n     *\n     * @return {@code true} if the user has typed a key; {@code false} otherwise\n     */\n    public boolean hasNextKeyTyped() {\n        synchronized (keyLock) {\n            return !keysTyped.isEmpty();\n        }\n    }\n\n    /**\n     * The next key typed by the user.\n     *\n     * @return the next key typed by the user\n     */\n    public char nextKeyTyped() {\n        synchronized (keyLock) {\n            return keysTyped.removeLast();\n        }\n    }\n\n   /**\n     * Returns true if the keycode is being pressed.\n     * <p>\n     * This method takes as an argument the keycode (corresponding to a physical key).\n     * It can handle action keys (such as F1 and arrow keys) and modifier keys\n     * (such as shift and control).\n     * See {@link KeyEvent} for a description of key codes.\n     *\n     * @param  keycode the keycode to check\n     * @return {@code true} if {@code keycode} is currently being pressed;\n     *         {@code false} otherwise\n     */\n    public boolean isKeyPressed(int keycode) {\n        synchronized (keyLock) {\n            return keysDown.contains(keycode);\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyTyped(KeyEvent e) {\n        synchronized (keyLock) {\n            keysTyped.addFirst(e.getKeyChar());\n        }\n\n        // notify all listeners\n        for (DrawListener listener : listeners)\n            listener.keyTyped(e.getKeyChar());\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyPressed(KeyEvent e) {\n        synchronized (keyLock) {\n            keysDown.add(e.getKeyCode());\n        }\n\n        // notify all listeners\n        for (DrawListener listener : listeners)\n            listener.keyPressed(e.getKeyCode());\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyReleased(KeyEvent e) {\n        synchronized (keyLock) {\n            keysDown.remove(e.getKeyCode());\n        }\n\n        // notify all listeners\n        for (DrawListener listener : listeners)\n            listener.keyPressed(e.getKeyCode());\n    }\n\n\n\n\n    /**\n     * Test client.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n\n        // create one drawing window\n        Draw draw1 = new Draw(\"Test client 1\");\n        draw1.square(.2, .8, .1);\n        draw1.filledSquare(.8, .8, .2);\n        draw1.circle(.8, .2, .2);\n        draw1.setPenColor(Draw.MAGENTA);\n        draw1.setPenRadius(.02);\n        draw1.arc(.8, .2, .1, 200, 45);\n\n\n        // create another one\n        Draw draw2 = new Draw(\"Test client 2\");\n        draw2.setCanvasSize(900, 200);\n        // draw a blue diamond\n        draw2.setPenRadius();\n        draw2.setPenColor(Draw.BLUE);\n        double[] x = { .1, .2, .3, .2 };\n        double[] y = { .2, .3, .2, .1 };\n        draw2.filledPolygon(x, y);\n\n        // text\n        draw2.setPenColor(Draw.BLACK);\n        draw2.text(0.2, 0.5, \"bdfdfdfdlack text\");\n        draw2.setPenColor(Draw.WHITE);\n        draw2.text(0.8, 0.8, \"white text\");\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/DrawListener.java",
    "content": "/******************************************************************************\n *  Compilation:  javac DrawListener.java\n *  Execution:    none\n *  Dependencies: none\n *\n *  Interface that accompanies Draw.java.\n ******************************************************************************/\n\npackage algs4;\n\npublic interface DrawListener {\n\n    /**\n     * Invoked when the mouse has been pressed.\n     *\n     * @param x the x-coordinate of the mouse\n     * @param y the y-coordinate of the mouse\n     */\n    void mousePressed(double x, double y);\n\n    /**\n     * Invoked when the mouse has been dragged.\n     *\n     * @param x the x-coordinate of the mouse\n     * @param y the y-coordinate of the mouse\n     */\n    void mouseDragged(double x, double y);\n\n    /**\n     * Invoked when the mouse has been released.\n     *\n     * @param x the x-coordinate of the mouse\n     * @param y the y-coordinate of the mouse\n     */\n    void mouseReleased(double x, double y);\n\n    /**\n     * Invoked when a key has been typed.\n     *\n     * @param c the character typed\n     */\n    void keyTyped(char c);\n\n    /**\n     * Invoked when a key has been pressed.\n     *\n     * @param keycode the key combination pressed\n     */\n    void keyPressed(int keycode);\n\n    /**\n     * Invoked when a key has been released.\n     *\n     * @param keycode the key combination released\n     */\n    void keyReleased(int keycode);\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Heap.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Heap.java\n *  Execution:    java Heap < input.txt\n *  Dependencies: StdOut.java StdIn.java\n *  Data files:   http://algs4.cs.princeton.edu/24pq/tiny.txt\n *                http://algs4.cs.princeton.edu/24pq/words3.txt\n *  \n *  Sorts a sequence of strings from standard input using heapsort.\n *\n *  % more tiny.txt\n *  S O R T E X A M P L E\n *\n *  % java Heap < tiny.txt\n *  A E E L M O P R S T X                 [ one string per line ]\n *\n *  % more words3.txt\n *  bed bug dad yes zoo ... all bad yet\n *\n *  % java Heap < words3.txt\n *  all bad bed bug dad ... yes yet zoo   [ one string per line ]\n *\n ******************************************************************************/\n\npackage algs4;\n\n/**\n *  The {@code Heap} class provides a static methods for heapsorting\n *  an array.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/24pq\">Section 2.4</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Heap {\n\n    // This class should not be instantiated.\n    private Heap() { }\n\n    /**\n     * Rearranges the array in ascending order, using the natural order.\n     * @param pq the array to be sorted\n     */\n    public static void sort(Comparable[] pq) {\n        int n = pq.length;\n        for (int k = n/2; k >= 1; k--)\n            sink(pq, k, n);\n        while (n > 1) {\n            exch(pq, 1, n--);\n            sink(pq, 1, n);\n        }\n    }\n\n   /***************************************************************************\n    * Helper functions to restore the heap invariant.\n    ***************************************************************************/\n\n    private static void sink(Comparable[] pq, int k, int n) {\n        while (2*k <= n) {\n            int j = 2*k;\n            if (j < n && less(pq, j, j+1)) j++;\n            if (!less(pq, k, j)) break;\n            exch(pq, k, j);\n            k = j;\n        }\n    }\n\n   /***************************************************************************\n    * Helper functions for comparisons and swaps.\n    * Indices are \"off-by-one\" to support 1-based indexing.\n    ***************************************************************************/\n    private static boolean less(Comparable[] pq, int i, int j) {\n        return pq[i-1].compareTo(pq[j-1]) < 0;\n    }\n\n    private static void exch(Object[] pq, int i, int j) {\n        Object swap = pq[i-1];\n        pq[i-1] = pq[j-1];\n        pq[j-1] = swap;\n    }\n\n    // is v < w ?\n    private static boolean less(Comparable v, Comparable w) {\n        return v.compareTo(w) < 0;\n    }\n        \n\n   /***************************************************************************\n    *  Check if array is sorted - useful for debugging.\n    ***************************************************************************/\n    private static boolean isSorted(Comparable[] a) {\n        for (int i = 1; i < a.length; i++)\n            if (less(a[i], a[i-1])) return false;\n        return true;\n    }\n\n\n    // print array to standard output\n    private static void show(Comparable[] a) {\n        for (int i = 0; i < a.length; i++) {\n            StdOut.println(a[i]);\n        }\n    }\n\n    /**\n     * Reads in a sequence of strings from standard input; heapsorts them; \n     * and prints them to standard output in ascending order. \n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        String[] a = StdIn.readAllStrings();\n        Heap.sort(a);\n        show(a);\n        assert isSorted(a);\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/HexDump.java",
    "content": "/******************************************************************************\n *  Compilation:  javac HexDump.java\n *  Execution:    java HexDump < file\n *  Dependencies: BinaryStdIn.java StdOut.java\n *  Data file:    http://algs4.cs.princeton.edu/55compression/abra.txt\n *  \n *  Reads in a binary file and writes out the bytes in hex, 16 per line.\n *\n *  % more abra.txt\n *  ABRACADABRA!\n *\n *  % java HexDump 16 < abra.txt\n *  41 42 52 41 43 41 44 41 42 52 41 21\n *  96 bits\n *\n *\n *  Remark\n *  --------------------------\n *   - Similar to the Unix utilities od (octal dump) or hexdump (hexadecimal dump).\n *\n *  % od -t x1 < abra.txt \n *  0000000 41 42 52 41 43 41 44 41 42 52 41 21\n *  0000014\n *\n ******************************************************************************/\n\npackage algs4;\n\n/**\n *  The {@code HexDump} class provides a client for displaying the contents\n *  of a binary file in hexadecimal.\n *  <p>\n *  For additional documentation,\n *  see <a href=\"http://algs4.cs.princeton.edu/55compress\">Section 5.5</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *  <p>\n *  See also {@link BinaryDump} and {@link PictureDump}.\n *  For more full-featured versions, see the Unix utilities\n *  {@code od} (octal dump) and {@code hexdump} (hexadecimal dump).\n *  <p>\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class HexDump {\n\n    // Do not instantiate.\n    private HexDump() { }\n\n    /**\n     * Reads in a sequence of bytes from standard input and writes\n     * them to standard output using hexademical notation, k hex digits\n     * per line, where k is given as a command-line integer (defaults\n     * to 16 if no integer is specified); also writes the number\n     * of bits.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int bytesPerLine = 16;\n        if (args.length == 1) {\n            bytesPerLine = Integer.parseInt(args[0]);\n        }\n\n        int i;\n        for (i = 0; !BinaryStdIn.isEmpty(); i++) {\n            if (bytesPerLine == 0) {\n                BinaryStdIn.readChar();\n                continue;\n            }\n            if (i == 0) StdOut.printf(\"\");\n            else if (i % bytesPerLine == 0) StdOut.printf(\"\\n\", i);\n            else StdOut.print(\" \");\n            char c = BinaryStdIn.readChar();\n            StdOut.printf(\"%02x\", c & 0xff);\n        }\n        if (bytesPerLine != 0) StdOut.println();\n        StdOut.println((i*8) + \" bits\");\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/In.java",
    "content": "/******************************************************************************\n *  Compilation:  javac In.java\n *  Execution:    java In   (basic test --- see source for required files)\n *  Dependencies: none\n *\n *  Reads in data of various types from standard input, files, and URLs.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.io.BufferedInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.net.Socket;\n// import java.net.HttpURLConnection;\nimport java.net.URLConnection;\nimport java.util.ArrayList;\nimport java.util.InputMismatchException;\nimport java.util.Locale;\nimport java.util.NoSuchElementException;\nimport java.util.Scanner;\nimport java.util.regex.Pattern;\n\n/**\n *  <i>Input</i>. This class provides methods for reading strings\n *  and numbers from standard input, file input, URLs, and sockets. \n *  <p>\n *  The Locale used is: language = English, country = US. This is consistent\n *  with the formatting conventions with Java floating-point literals,\n *  command-line arguments (via {@link Double#parseDouble(String)})\n *  and standard output. \n *  <p>\n *  For additional documentation, see \n *  <a href=\"http://introcs.cs.princeton.edu/31datatype\">Section 3.1</a> of\n *  <i>Computer Science: An Interdisciplinary Approach</i> \n *  by Robert Sedgewick and Kevin Wayne.\n *  <p>\n *  Like {@link Scanner}, reading a token also consumes preceding Java\n *  whitespace, reading a full line consumes\n *  the following end-of-line delimeter, while reading a character consumes\n *  nothing extra. \n *  <p>\n *  Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines\n *  consist of \\n, \\r, \\r\\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;\n *  see <a href=\"http://www.docjar.com/html/api/java/util/Scanner.java.html\">\n *  Scanner.java</a> (NB: Java 6u23 and earlier uses only \\r, \\r, \\r\\n).\n *\n *  @author David Pritchard\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class In {\n    \n    ///// begin: section (1 of 2) of code duplicated from In to StdIn.\n    \n    // assume Unicode UTF-8 encoding\n    private static final String CHARSET_NAME = \"UTF-8\";\n\n    // assume language = English, country = US for consistency with System.out.\n    private static final Locale LOCALE = Locale.US;\n\n    // the default token separator; we maintain the invariant that this value \n    // is held by the scanner's delimiter between calls\n    private static final Pattern WHITESPACE_PATTERN\n        = Pattern.compile(\"\\\\p{javaWhitespace}+\");\n\n    // makes whitespace characters significant \n    private static final Pattern EMPTY_PATTERN\n        = Pattern.compile(\"\");\n\n    // used to read the entire input. source:\n    // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html\n    private static final Pattern EVERYTHING_PATTERN\n        = Pattern.compile(\"\\\\A\");\n\n    //// end: section (1 of 2) of code duplicated from In to StdIn.\n\n    private Scanner scanner;\n\n   /**\n     * Initializes an input stream from standard input.\n     */\n    public In() {\n        scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);\n        scanner.useLocale(LOCALE);\n    }\n\n   /**\n     * Initializes an input stream from a socket.\n     *\n     * @param  socket the socket\n     * @throws IllegalArgumentException if cannot open {@code socket}\n     * @throws IllegalArgumentException if {@code socket} is {@code null}\n     */\n    public In(Socket socket) {\n        if (socket == null) throw new IllegalArgumentException(\"socket argument is null\");\n        try {\n            InputStream is = socket.getInputStream();\n            scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);\n            scanner.useLocale(LOCALE);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"Could not open \" + socket, ioe);\n        }\n    }\n\n   /**\n     * Initializes an input stream from a URL.\n     *\n     * @param  url the URL\n     * @throws IllegalArgumentException if cannot open {@code url}\n     * @throws IllegalArgumentException if {@code url} is {@code null}\n     */\n    public In(URL url) {\n        if (url == null) throw new IllegalArgumentException(\"url argument is null\");\n        try {\n            URLConnection site = url.openConnection();\n            InputStream is     = site.getInputStream();\n            scanner            = new Scanner(new BufferedInputStream(is), CHARSET_NAME);\n            scanner.useLocale(LOCALE);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"Could not open \" + url, ioe);\n        }\n    }\n\n   /**\n     * Initializes an input stream from a file.\n     *\n     * @param  file the file\n     * @throws IllegalArgumentException if cannot open {@code file}\n     * @throws IllegalArgumentException if {@code file} is {@code null}\n     */\n    public In(File file) {\n        if (file == null) throw new IllegalArgumentException(\"file argument is null\");\n        try {\n            // for consistency with StdIn, wrap with BufferedInputStream instead of use\n            // file as argument to Scanner\n            FileInputStream fis = new FileInputStream(file);\n            scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);\n            scanner.useLocale(LOCALE);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"Could not open \" + file, ioe);\n        }\n    }\n\n\n   /**\n     * Initializes an input stream from a filename or web page name.\n     *\n     * @param  name the filename or web page name\n     * @throws IllegalArgumentException if cannot open {@code name} as\n     *         a file or URL\n     * @throws IllegalArgumentException if {@code name} is {@code null}\n     */\n    public In(String name) {\n        if (name == null) throw new IllegalArgumentException(\"argument is null\");\n        try {\n            // first try to read file from local file system\n            File file = new File(name);\n            if (file.exists()) {\n                // for consistency with StdIn, wrap with BufferedInputStream instead of use\n                // file as argument to Scanner\n                FileInputStream fis = new FileInputStream(file);\n                scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);\n                scanner.useLocale(LOCALE);\n                return;\n            }\n\n            // next try for files included in jar\n            URL url = getClass().getResource(name);\n\n            // or URL from web\n            if (url == null) {\n                url = new URL(name);\n            }\n\n            URLConnection site = url.openConnection();\n\n            // in order to set User-Agent, replace above line with these two\n            // HttpURLConnection site = (HttpURLConnection) url.openConnection();\n            // site.addRequestProperty(\"User-Agent\", \"Mozilla/4.76\");\n\n            InputStream is     = site.getInputStream();\n            scanner            = new Scanner(new BufferedInputStream(is), CHARSET_NAME);\n            scanner.useLocale(LOCALE);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"Could not open \" + name, ioe);\n        }\n    }\n\n    /**\n     * Initializes an input stream from a given {@link Scanner} source; use with \n     * {@code new Scanner(String)} to read from a string.\n     * <p>\n     * Note that this does not create a defensive copy, so the\n     * scanner will be mutated as you read on. \n     *\n     * @param  scanner the scanner\n     * @throws IllegalArgumentException if {@code scanner} is {@code null}\n     */\n    public In(Scanner scanner) {\n        if (scanner == null) throw new IllegalArgumentException(\"scanner argument is null\");\n        this.scanner = scanner;\n    }\n\n    /**\n     * Returns true if this input stream exists.\n     *\n     * @return {@code true} if this input stream exists; {@code false} otherwise\n     */\n    public boolean exists()  {\n        return scanner != null;\n    }\n    \n    ////  begin: section (2 of 2) of code duplicated from In to StdIn,\n    ////  with all methods changed from \"public\" to \"public static\".\n\n   /**\n     * Returns true if input stream is empty (except possibly whitespace).\n     * Use this to know whether the next call to {@link #readString()}, \n     * {@link #readDouble()}, etc will succeed.\n     *\n     * @return {@code true} if this input stream is empty (except possibly whitespace);\n     *         {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return !scanner.hasNext();\n    }\n\n   /** \n     * Returns true if this input stream has a next line.\n     * Use this method to know whether the\n     * next call to {@link #readLine()} will succeed.\n     * This method is functionally equivalent to {@link #hasNextChar()}.\n     *\n     * @return {@code true} if this input stream has more input (including whitespace);\n     *         {@code false} otherwise\n     */\n    public boolean hasNextLine() {\n        return scanner.hasNextLine();\n    }\n\n    /**\n     * Returns true if this input stream has more inputy (including whitespace).\n     * Use this method to know whether the next call to {@link #readChar()} will succeed.\n     * This method is functionally equivalent to {@link #hasNextLine()}.\n     * \n     * @return {@code true} if this input stream has more input (including whitespace);\n     *         {@code false} otherwise   \n     */\n    public boolean hasNextChar() {\n        scanner.useDelimiter(EMPTY_PATTERN);\n        boolean result = scanner.hasNext();\n        scanner.useDelimiter(WHITESPACE_PATTERN);\n        return result;\n    }\n\n\n   /**\n     * Reads and returns the next line in this input stream.\n     *\n     * @return the next line in this input stream; {@code null} if no such line\n     */\n    public String readLine() {\n        String line;\n        try {\n            line = scanner.nextLine();\n        }\n        catch (NoSuchElementException e) {\n            line = null;\n        }\n        return line;\n    }\n\n    /**\n     * Reads and returns the next character in this input stream.\n     *\n     * @return the next character in this input stream\n     */\n    public char readChar() {\n        scanner.useDelimiter(EMPTY_PATTERN);\n        String ch = scanner.next();\n        assert ch.length() == 1 : \"Internal (Std)In.readChar() error!\"\n            + \" Please contact the authors.\";\n        scanner.useDelimiter(WHITESPACE_PATTERN);\n        return ch.charAt(0);\n    }  \n\n\n   /**\n     * Reads and returns the remainder of this input stream, as a string.\n     *\n     * @return the remainder of this input stream, as a string\n     */\n    public String readAll() {\n        if (!scanner.hasNextLine())\n            return \"\";\n\n        String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();\n        // not that important to reset delimeter, since now scanner is empty\n        scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway\n        return result;\n    }\n\n\n   /**\n     * Reads the next token from this input stream and returns it as a {@code String}.\n     *\n     * @return the next {@code String} in this input stream\n     */\n    public String readString() {\n        return scanner.next();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code int},\n     * and returns the {@code int}.\n     *\n     * @return the next {@code int} in this input stream\n     */\n    public int readInt() {\n        return scanner.nextInt();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code double},\n     * and returns the {@code double}.\n     *\n     * @return the next {@code double} in this input stream\n     */\n    public double readDouble() {\n        return scanner.nextDouble();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code float},\n     * and returns the {@code float}.\n     *\n     * @return the next {@code float} in this input stream\n     */\n    public float readFloat() {\n        return scanner.nextFloat();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code long},\n     * and returns the {@code long}.\n     *\n     * @return the next {@code long} in this input stream\n     */\n    public long readLong() {\n        return scanner.nextLong();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code short},\n     * and returns the {@code short}.\n     *\n     * @return the next {@code short} in this input stream\n     */\n    public short readShort() {\n        return scanner.nextShort();\n    }\n\n   /**\n     * Reads the next token from this input stream, parses it as a {@code byte},\n     * and returns the {@code byte}.\n     * <p>\n     * To read binary data, use {@link BinaryIn}.\n     *\n     * @return the next {@code byte} in this input stream\n     */\n    public byte readByte() {\n        return scanner.nextByte();\n    }\n\n    /**\n     * Reads the next token from this input stream, parses it as a {@code boolean}\n     * (interpreting either {@code \"true\"} or {@code \"1\"} as {@code true},\n     * and either {@code \"false\"} or {@code \"0\"} as {@code false}).\n     *\n     * @return the next {@code boolean} in this input stream\n     */\n    public boolean readBoolean() {\n        String s = readString();\n        if (\"true\".equalsIgnoreCase(s))  return true;\n        if (\"false\".equalsIgnoreCase(s)) return false;\n        if (\"1\".equals(s))               return true;\n        if (\"0\".equals(s))               return false;\n        throw new InputMismatchException();\n    }\n\n    /**\n     * Reads all remaining tokens from this input stream and returns them as\n     * an array of strings.\n     *\n     * @return all remaining tokens in this input stream, as an array of strings\n     */\n    public String[] readAllStrings() {\n        // we could use readAll.trim().split(), but that's not consistent\n        // since trim() uses characters 0x00..0x20 as whitespace\n        String[] tokens = WHITESPACE_PATTERN.split(readAll());\n        if (tokens.length == 0 || tokens[0].length() > 0)\n            return tokens;\n        String[] decapitokens = new String[tokens.length-1];\n        for (int i = 0; i < tokens.length-1; i++)\n            decapitokens[i] = tokens[i+1];\n        return decapitokens;\n    }\n\n    /**\n     * Reads all remaining lines from this input stream and returns them as\n     * an array of strings.\n     *\n     * @return all remaining lines in this input stream, as an array of strings\n     */\n    public String[] readAllLines() {\n        ArrayList<String> lines = new ArrayList<String>();\n        while (hasNextLine()) {\n            lines.add(readLine());\n        }\n        return lines.toArray(new String[lines.size()]);\n    }\n\n\n    /**\n     * Reads all remaining tokens from this input stream, parses them as integers,\n     * and returns them as an array of integers.\n     *\n     * @return all remaining lines in this input stream, as an array of integers\n     */\n    public int[] readAllInts() {\n        String[] fields = readAllStrings();\n        int[] vals = new int[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Integer.parseInt(fields[i]);\n        return vals;\n    }\n\n    /**\n     * Reads all remaining tokens from this input stream, parses them as longs,\n     * and returns them as an array of longs.\n     *\n     * @return all remaining lines in this input stream, as an array of longs\n     */\n    public long[] readAllLongs() {\n        String[] fields = readAllStrings();\n        long[] vals = new long[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Long.parseLong(fields[i]);\n        return vals;\n    }\n\n    /**\n     * Reads all remaining tokens from this input stream, parses them as doubles,\n     * and returns them as an array of doubles.\n     *\n     * @return all remaining lines in this input stream, as an array of doubles\n     */\n    public double[] readAllDoubles() {\n        String[] fields = readAllStrings();\n        double[] vals = new double[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Double.parseDouble(fields[i]);\n        return vals;\n    }\n    \n    ///// end: section (2 of 2) of code duplicated from In to StdIn */\n\n   /**\n     * Closes this input stream.\n     */\n    public void close() {\n        scanner.close();  \n    }\n\n    /**\n     * Reads all integers from a file and returns them as\n     * an array of integers.\n     *\n     * @param      filename the name of the file\n     * @return     the integers in the file\n     * @deprecated Replaced by {@code new In(filename)}.{@link #readAllInts()}.\n     */\n    @Deprecated\n    public static int[] readInts(String filename) {\n        return new In(filename).readAllInts();\n    }\n\n   /**\n     * Reads all doubles from a file and returns them as\n     * an array of doubles.\n     *\n     * @param      filename the name of the file\n     * @return     the doubles in the file\n     * @deprecated Replaced by {@code new In(filename)}.{@link #readAllDoubles()}.\n     */\n    @Deprecated\n    public static double[] readDoubles(String filename) {\n        return new In(filename).readAllDoubles();\n    }\n\n   /**\n     * Reads all strings from a file and returns them as\n     * an array of strings.\n     *\n     * @param      filename the name of the file\n     * @return     the strings in the file\n     * @deprecated Replaced by {@code new In(filename)}.{@link #readAllStrings()}.\n     */\n    @Deprecated\n    public static String[] readStrings(String filename) {\n        return new In(filename).readAllStrings();\n    }\n\n    /**\n     * Reads all integers from standard input and returns them\n     * an array of integers.\n     *\n     * @return     the integers on standard input\n     * @deprecated Replaced by {@link StdIn#readAllInts()}.\n     */\n    @Deprecated\n    public static int[] readInts() {\n        return new In().readAllInts();\n    }\n\n   /**\n     * Reads all doubles from standard input and returns them as\n     * an array of doubles.\n     *\n     * @return     the doubles on standard input\n     * @deprecated Replaced by {@link StdIn#readAllDoubles()}.\n     */\n    @Deprecated\n    public static double[] readDoubles() {\n        return new In().readAllDoubles();\n    }\n\n   /**\n     * Reads all strings from standard input and returns them as\n     *  an array of strings.\n     *\n     * @return     the strings on standard input\n     * @deprecated Replaced by {@link StdIn#readAllStrings()}.\n     */\n    @Deprecated\n    public static String[] readStrings() {\n        return new In().readAllStrings();\n    }\n    \n   /**\n     * Unit tests the {@code In} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        In in;\n        String urlName = \"http://introcs.cs.princeton.edu/stdlib/InTest.txt\";\n\n        // read from a URL\n        System.out.println(\"readAll() from URL \" + urlName);\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(urlName);\n            System.out.println(in.readAll());\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n        // read one line at a time from URL\n        System.out.println(\"readLine() from URL \" + urlName);\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(urlName);\n            while (!in.isEmpty()) {\n                String s = in.readLine();\n                System.out.println(s);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n        // read one string at a time from URL\n        System.out.println(\"readString() from URL \" + urlName);\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(urlName);\n            while (!in.isEmpty()) {\n                String s = in.readString();\n                System.out.println(s);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n\n        // read one line at a time from file in current directory\n        System.out.println(\"readLine() from current directory\");\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(\"./InTest.txt\");\n            while (!in.isEmpty()) {\n                String s = in.readLine();\n                System.out.println(s);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n\n        // read one line at a time from file using relative path\n        System.out.println(\"readLine() from relative path\");\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(\"../stdlib/InTest.txt\");\n            while (!in.isEmpty()) {\n                String s = in.readLine();\n                System.out.println(s);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n        // read one char at a time\n        System.out.println(\"readChar() from file\");\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(\"InTest.txt\");\n            while (!in.isEmpty()) {\n                char c = in.readChar();\n                System.out.print(c);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n        System.out.println();\n\n        // read one line at a time from absolute OS X / Linux path\n        System.out.println(\"readLine() from absolute OS X / Linux path\");\n        System.out.println(\"---------------------------------------------------------------------------\");\n        in = new In(\"/n/fs/introcs/www/java/stdlib/InTest.txt\");\n        try {\n            while (!in.isEmpty()) {\n                String s = in.readLine();\n                System.out.println(s);\n            }\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n\n        // read one line at a time from absolute Windows path\n        System.out.println(\"readLine() from absolute Windows path\");\n        System.out.println(\"---------------------------------------------------------------------------\");\n        try {\n            in = new In(\"G:\\\\www\\\\introcs\\\\stdlib\\\\InTest.txt\");\n            while (!in.isEmpty()) {\n                String s = in.readLine();\n                System.out.println(s);\n            }\n            System.out.println();\n        }\n        catch (IllegalArgumentException e) {\n            System.out.println(e);\n        }\n        System.out.println();\n\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/IndexMinPQ.java",
    "content": "/******************************************************************************\n *  Compilation:  javac IndexMinPQ.java\n *  Execution:    java IndexMinPQ\n *  Dependencies: StdOut.java\n *\n *  Minimum-oriented indexed PQ implementation using a binary heap.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n *  The {@code IndexMinPQ} class represents an indexed priority queue of generic keys.\n *  It supports the usual <em>insert</em> and <em>delete-the-minimum</em>\n *  operations, along with <em>delete</em> and <em>change-the-key</em> \n *  methods. In order to let the client refer to keys on the priority queue,\n *  an integer between {@code 0} and {@code maxN - 1}\n *  is associated with each key—the client uses this integer to specify\n *  which key to delete or change.\n *  It also supports methods for peeking at the minimum key,\n *  testing if the priority queue is empty, and iterating through\n *  the keys.\n *  <p>\n *  This implementation uses a binary heap along with an array to associate\n *  keys with integers in the given range.\n *  The <em>insert</em>, <em>delete-the-minimum</em>, <em>delete</em>,\n *  <em>change-key</em>, <em>decrease-key</em>, and <em>increase-key</em>\n *  operations take logarithmic time.\n *  The <em>is-empty</em>, <em>size</em>, <em>min-index</em>, <em>min-key</em>,\n *  and <em>key-of</em> operations take constant time.\n *  Construction takes time proportional to the specified capacity.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/24pq\">Section 2.4</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Key> the generic type of key on this priority queue\n */\npublic class IndexMinPQ<Key extends Comparable<Key>> implements Iterable<Integer> {\n    private int maxN;        // maximum number of elements on PQ\n    private int n;           // number of elements on PQ\n    private int[] pq;        // binary heap using 1-based indexing\n    private int[] qp;        // inverse of pq - qp[pq[i]] = pq[qp[i]] = i\n    private Key[] keys;      // keys[i] = priority of i\n\n    /**\n     * Initializes an empty indexed priority queue with indices between {@code 0}\n     * and {@code maxN - 1}.\n     * @param  maxN the keys on this priority queue are index from {@code 0}\n     *         {@code maxN - 1}\n     * @throws IllegalArgumentException if {@code maxN < 0}\n     */\n    public IndexMinPQ(int maxN) {\n        if (maxN < 0) throw new IllegalArgumentException();\n        this.maxN = maxN;\n        n = 0;\n        keys = (Key[]) new Comparable[maxN + 1];    // make this of length maxN??\n        pq   = new int[maxN + 1];\n        qp   = new int[maxN + 1];                   // make this of length maxN??\n        for (int i = 0; i <= maxN; i++)\n            qp[i] = -1;\n    }\n\n    /**\n     * Returns true if this priority queue is empty.\n     *\n     * @return {@code true} if this priority queue is empty;\n     *         {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return n == 0;\n    }\n\n    /**\n     * Is {@code i} an index on this priority queue?\n     *\n     * @param  i an index\n     * @return {@code true} if {@code i} is an index on this priority queue;\n     *         {@code false} otherwise\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     */\n    public boolean contains(int i) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        return qp[i] != -1;\n    }\n\n    /**\n     * Returns the number of keys on this priority queue.\n     *\n     * @return the number of keys on this priority queue\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Associates key with index {@code i}.\n     *\n     * @param  i an index\n     * @param  key the key to associate with index {@code i}\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws IllegalArgumentException if there already is an item associated\n     *         with index {@code i}\n     */\n    public void insert(int i, Key key) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (contains(i)) throw new IllegalArgumentException(\"index is already in the priority queue\");\n        n++;\n        qp[i] = n;\n        pq[n] = i;\n        keys[i] = key;\n        swim(n);\n    }\n\n    /**\n     * Returns an index associated with a minimum key.\n     *\n     * @return an index associated with a minimum key\n     * @throws NoSuchElementException if this priority queue is empty\n     */\n    public int minIndex() {\n        if (n == 0) throw new NoSuchElementException(\"Priority queue underflow\");\n        return pq[1];\n    }\n\n    /**\n     * Returns a minimum key.\n     *\n     * @return a minimum key\n     * @throws NoSuchElementException if this priority queue is empty\n     */\n    public Key minKey() {\n        if (n == 0) throw new NoSuchElementException(\"Priority queue underflow\");\n        return keys[pq[1]];\n    }\n\n    /**\n     * Removes a minimum key and returns its associated index.\n     * @return an index associated with a minimum key\n     * @throws NoSuchElementException if this priority queue is empty\n     */\n    public int delMin() {\n        if (n == 0) throw new NoSuchElementException(\"Priority queue underflow\");\n        int min = pq[1];\n        exch(1, n--);\n        sink(1);\n        assert min == pq[n+1];\n        qp[min] = -1;        // delete\n        keys[min] = null;    // to help with garbage collection\n        pq[n+1] = -1;        // not needed\n        return min;\n    }\n\n    /**\n     * Returns the key associated with index {@code i}.\n     *\n     * @param  i the index of the key to return\n     * @return the key associated with index {@code i}\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws NoSuchElementException no key is associated with index {@code i}\n     */\n    public Key keyOf(int i) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (!contains(i)) throw new NoSuchElementException(\"index is not in the priority queue\");\n        else return keys[i];\n    }\n\n    /**\n     * Change the key associated with index {@code i} to the specified value.\n     *\n     * @param  i the index of the key to change\n     * @param  key change the key associated with index {@code i} to this key\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws NoSuchElementException no key is associated with index {@code i}\n     */\n    public void changeKey(int i, Key key) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (!contains(i)) throw new NoSuchElementException(\"index is not in the priority queue\");\n        keys[i] = key;\n        swim(qp[i]);\n        sink(qp[i]);\n    }\n\n    /**\n     * Change the key associated with index {@code i} to the specified value.\n     *\n     * @param  i the index of the key to change\n     * @param  key change the key associated with index {@code i} to this key\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @deprecated Replaced by {@code changeKey(int, Key)}.\n     */\n    @Deprecated\n    public void change(int i, Key key) {\n        changeKey(i, key);\n    }\n\n    /**\n     * Decrease the key associated with index {@code i} to the specified value.\n     *\n     * @param  i the index of the key to decrease\n     * @param  key decrease the key associated with index {@code i} to this key\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws IllegalArgumentException if {@code key >= keyOf(i)}\n     * @throws NoSuchElementException no key is associated with index {@code i}\n     */\n    public void decreaseKey(int i, Key key) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (!contains(i)) throw new NoSuchElementException(\"index is not in the priority queue\");\n        if (keys[i].compareTo(key) <= 0)\n            throw new IllegalArgumentException(\"Calling decreaseKey() with given argument would not strictly decrease the key\");\n        keys[i] = key;\n        swim(qp[i]);\n    }\n\n    /**\n     * Increase the key associated with index {@code i} to the specified value.\n     *\n     * @param  i the index of the key to increase\n     * @param  key increase the key associated with index {@code i} to this key\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws IllegalArgumentException if {@code key <= keyOf(i)}\n     * @throws NoSuchElementException no key is associated with index {@code i}\n     */\n    public void increaseKey(int i, Key key) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (!contains(i)) throw new NoSuchElementException(\"index is not in the priority queue\");\n        if (keys[i].compareTo(key) >= 0)\n            throw new IllegalArgumentException(\"Calling increaseKey() with given argument would not strictly increase the key\");\n        keys[i] = key;\n        sink(qp[i]);\n    }\n\n    /**\n     * Remove the key associated with index {@code i}.\n     *\n     * @param  i the index of the key to remove\n     * @throws IndexOutOfBoundsException unless {@code 0 <= i < maxN}\n     * @throws NoSuchElementException no key is associated with index {@code i}\n     */\n    public void delete(int i) {\n        if (i < 0 || i >= maxN) throw new IndexOutOfBoundsException();\n        if (!contains(i)) throw new NoSuchElementException(\"index is not in the priority queue\");\n        int index = qp[i];\n        exch(index, n--);\n        swim(index);\n        sink(index);\n        keys[i] = null;\n        qp[i] = -1;\n    }\n\n\n   /***************************************************************************\n    * General helper functions.\n    ***************************************************************************/\n    private boolean greater(int i, int j) {\n        return keys[pq[i]].compareTo(keys[pq[j]]) > 0;\n    }\n\n    private void exch(int i, int j) {\n        int swap = pq[i];\n        pq[i] = pq[j];\n        pq[j] = swap;\n        qp[pq[i]] = i;\n        qp[pq[j]] = j;\n    }\n\n\n   /***************************************************************************\n    * Heap helper functions.\n    ***************************************************************************/\n    private void swim(int k) {\n        while (k > 1 && greater(k/2, k)) {\n            exch(k, k/2);\n            k = k/2;\n        }\n    }\n\n    private void sink(int k) {\n        while (2*k <= n) {\n            int j = 2*k;\n            if (j < n && greater(j, j+1)) j++;\n            if (!greater(k, j)) break;\n            exch(k, j);\n            k = j;\n        }\n    }\n\n\n   /***************************************************************************\n    * Iterators.\n    ***************************************************************************/\n\n    /**\n     * Returns an iterator that iterates over the keys on the\n     * priority queue in ascending order.\n     * The iterator doesn't implement {@code remove()} since it's optional.\n     *\n     * @return an iterator that iterates over the keys in ascending order\n     */\n    public Iterator<Integer> iterator() { return new HeapIterator(); }\n\n    private class HeapIterator implements Iterator<Integer> {\n        // create a new pq\n        private IndexMinPQ<Key> copy;\n\n        // add all elements to copy of heap\n        // takes linear time since already in heap order so no keys move\n        public HeapIterator() {\n            copy = new IndexMinPQ<Key>(pq.length - 1);\n            for (int i = 1; i <= n; i++)\n                copy.insert(pq[i], keys[pq[i]]);\n        }\n\n        public boolean hasNext()  { return !copy.isEmpty();                     }\n        public void remove()      { throw new UnsupportedOperationException();  }\n\n        public Integer next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            return copy.delMin();\n        }\n    }\n\n\n    /**\n     * Unit tests the {@code IndexMinPQ} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        // insert a bunch of strings\n        String[] strings = { \"it\", \"was\", \"the\", \"best\", \"of\", \"times\", \"it\", \"was\", \"the\", \"worst\" };\n\n        IndexMinPQ<String> pq = new IndexMinPQ<String>(strings.length);\n        for (int i = 0; i < strings.length; i++) {\n            pq.insert(i, strings[i]);\n        }\n\n        // delete and print each key\n        while (!pq.isEmpty()) {\n            int i = pq.delMin();\n            StdOut.println(i + \" \" + strings[i]);\n        }\n        StdOut.println();\n\n        // reinsert the same strings\n        for (int i = 0; i < strings.length; i++) {\n            pq.insert(i, strings[i]);\n        }\n\n        // print each key using the iterator\n        for (int i : pq) {\n            StdOut.println(i + \" \" + strings[i]);\n        }\n        while (!pq.isEmpty()) {\n            pq.delMin();\n        }\n\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Interval1D.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Interval1D.java\n *  Execution:    java Interval1D\n *  Dependencies: StdOut.java\n *  \n *  1-dimensional interval data type.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n/**\n *  The {@code Interval1D} class represents a one-dimensional interval.\n *  The interval is <em>closed</em>—it contains both endpoints.\n *  Intervals are immutable: their values cannot be changed after they are created.\n *  The class {@code Interval1D} includes methods for checking whether\n *  an interval contains a point and determining whether two intervals intersect.\n *  <p>\n *  For additional documentation, \n *  see <a href=\"http://algs4.cs.princeton.edu/12oop\">Section 1.2</a> of \n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. \n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Interval1D {\n\n    /**\n     * Compares two intervals by min endpoint.\n     */\n    public static final Comparator<Interval1D> MIN_ENDPOINT_ORDER  = new MinEndpointComparator();\n\n    /**\n     * Compares two intervals by max endpoint.\n     */\n    public static final Comparator<Interval1D> MAX_ENDPOINT_ORDER = new MaxEndpointComparator();\n\n    /**\n     * Compares two intervals by length.\n     */\n    public static final Comparator<Interval1D> LENGTH_ORDER = new LengthComparator();\n\n    private final double min;\n    private final double max;\n\n    /**\n     * Initializes a closed interval [min, max].\n     *\n     * @param  min the smaller endpoint\n     * @param  max the larger endpoint\n     * @throws IllegalArgumentException if the min endpoint is greater than the max endpoint\n     * @throws IllegalArgumentException if either {@code min} or {@code max}\n     *         is {@code Double.NaN}, {@code Double.POSITIVE_INFINITY} or\n     *         {@code Double.NEGATIVE_INFINITY}\n\n     */\n    public Interval1D(double min, double max) {\n        if (Double.isInfinite(min) || Double.isInfinite(max))\n            throw new IllegalArgumentException(\"Endpoints must be finite\");\n        if (Double.isNaN(min) || Double.isNaN(max))\n            throw new IllegalArgumentException(\"Endpoints cannot be NaN\");\n\n        // convert -0.0 to +0.0\n        if (min == 0.0) min = 0.0;\n        if (max == 0.0) max = 0.0;\n\n        if (min <= max) {\n            this.min = min;\n            this.max = max;\n        }\n        else throw new IllegalArgumentException(\"Illegal interval\");\n    }\n\n    /**\n     * Returns the left endpoint of this interval.\n     *\n     * @return the left endpoint of this interval\n     * @deprecated Replaced by {@link #min()}.\n     */\n    @Deprecated\n    public double left() { \n        return min;\n    }\n\n    /**\n     * Returns the right endpoint of this interval.\n     * @return the right endpoint of this interval\n     * @deprecated Replaced by {@link #max()}.\n     */\n    @Deprecated\n    public double right() { \n        return max;\n    }\n\n    /**\n     * Returns the min endpoint of this interval.\n     *\n     * @return the min endpoint of this interval\n     */\n    public double min() { \n        return min;\n    }\n\n    /**\n     * Returns the max endpoint of this interval.\n     *\n     * @return the max endpoint of this interval\n     */\n    public double max() { \n        return max;\n    }\n\n    /**\n     * Returns true if this interval intersects the specified interval.\n     *\n     * @param  that the other interval\n     * @return {@code true} if this interval intersects the argument interval;\n     *         {@code false} otherwise\n     */\n    public boolean intersects(Interval1D that) {\n        if (this.max < that.min) return false;\n        if (that.max < this.min) return false;\n        return true;\n    }\n\n    /**\n     * Returns true if this interval contains the specified value.\n     *\n     * @param x the value\n     * @return {@code true} if this interval contains the value {@code x};\n     *         {@code false} otherwise\n     */\n    public boolean contains(double x) {\n        return (min <= x) && (x <= max);\n    }\n\n    /**\n     * Returns the length of this interval.\n     *\n     * @return the length of this interval (max - min)\n     */\n    public double length() {\n        return max - min;\n    }\n\n    /**\n     * Returns a string representation of this interval.\n     *\n     * @return a string representation of this interval in the form [min, max]\n     */\n    public String toString() {\n        return \"[\" + min + \", \" + max + \"]\";\n    }\n\n    /**\n     * Compares this transaction to the specified object.\n     *\n     * @param  other the other interval\n     * @return {@code true} if this interval equals the other interval;\n     *         {@code false} otherwise\n     */\n    public boolean equals(Object other) {\n        if (other == this) return true;\n        if (other == null) return false;\n        if (other.getClass() != this.getClass()) return false;\n        Interval1D that = (Interval1D) other;\n        return this.min == that.min && this.max == that.max;\n    }\n\n    /**\n     * Returns an integer hash code for this interval.\n     *\n     * @return an integer hash code for this interval\n     */\n    public int hashCode() {\n        int hash1 = ((Double) min).hashCode();\n        int hash2 = ((Double) max).hashCode();\n        return 31*hash1 + hash2;\n    }\n\n    // ascending order of min endpoint, breaking ties by max endpoint\n    private static class MinEndpointComparator implements Comparator<Interval1D> {\n        public int compare(Interval1D a, Interval1D b) {\n            if      (a.min < b.min) return -1;\n            else if (a.min > b.min) return +1;\n            else if (a.max < b.max) return -1;\n            else if (a.max > b.max) return +1;\n            else                    return  0;\n        }\n    }\n\n    // ascending order of max endpoint, breaking ties by min endpoint\n    private static class MaxEndpointComparator implements Comparator<Interval1D> {\n        public int compare(Interval1D a, Interval1D b) {\n            if      (a.min < b.max) return -1;\n            else if (a.min > b.max) return +1;\n            else if (a.min < b.min) return -1;\n            else if (a.min > b.min) return +1;\n            else                    return  0;\n        }\n    }\n\n    // ascending order of length\n    private static class LengthComparator implements Comparator<Interval1D> {\n        public int compare(Interval1D a, Interval1D b) {\n            double alen = a.length();\n            double blen = b.length();\n            if      (alen < blen) return -1;\n            else if (alen > blen) return +1;\n            else                  return  0;\n        }\n    }\n\n\n\n\n    /**\n     * Unit tests the {@code Interval1D} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Interval1D[] intervals = new Interval1D[4];\n        intervals[0] = new Interval1D(15.0, 33.0);\n        intervals[1] = new Interval1D(45.0, 60.0);\n        intervals[2] = new Interval1D(20.0, 70.0);\n        intervals[3] = new Interval1D(46.0, 55.0);\n\n        StdOut.println(\"Unsorted\");\n        for (int i = 0; i < intervals.length; i++)\n            StdOut.println(intervals[i]);\n        StdOut.println();\n        \n        StdOut.println(\"Sort by min endpoint\");\n        Arrays.sort(intervals, Interval1D.MIN_ENDPOINT_ORDER);\n        for (int i = 0; i < intervals.length; i++)\n            StdOut.println(intervals[i]);\n        StdOut.println();\n\n        StdOut.println(\"Sort by max endpoint\");\n        Arrays.sort(intervals, Interval1D.MAX_ENDPOINT_ORDER);\n        for (int i = 0; i < intervals.length; i++)\n            StdOut.println(intervals[i]);\n        StdOut.println();\n\n        StdOut.println(\"Sort by length\");\n        Arrays.sort(intervals, Interval1D.LENGTH_ORDER);\n        for (int i = 0; i < intervals.length; i++)\n            StdOut.println(intervals[i]);\n        StdOut.println();\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Interval2D.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Interval2D.java\n *  Execution:    java Interval2D\n *  Dependencies: StdOut.java Interval1D.java StdDraw.java\n *  \n *  2-dimensional interval data type.\n *\n ******************************************************************************/\n\npackage algs4;\n\n/**\n *  The {@code Interval2D} class represents a closed two-dimensional interval,\n *  which represents all points (x, y) with both {@code xmin <= x <= xmax} and\n *  {@code ymin <= y <= ymax}.\n *  Two-dimensional intervals are immutable: their values cannot be changed\n *  after they are created.\n *  The class {@code Interval2D} includes methods for checking whether\n *  a two-dimensional interval contains a point and determining whether\n *  two two-dimensional intervals intersect.\n *  <p>\n *  For additional documentation, \n *  see <a href=\"http://algs4.cs.princeton.edu/12oop\">Section 1.2</a> of \n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. \n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Interval2D {\n    private final Interval1D x;\n    private final Interval1D y;\n\n    /**\n     * Initializes a two-dimensional interval.\n     * @param x the one-dimensional interval of x-coordinates\n     * @param y the one-dimensional interval of y-coordinates\n     */\n    public Interval2D(Interval1D x, Interval1D y) {\n        this.x = x;\n        this.y = y;\n    }\n\n    /**\n     * Does this two-dimensional interval intersect that two-dimensional interval?\n     * @param that the other two-dimensional interval\n     * @return true if this two-dimensional interval intersects\n     *    that two-dimensional interval; false otherwise\n     */\n    public boolean intersects(Interval2D that) {\n        if (!this.x.intersects(that.x)) return false;\n        if (!this.y.intersects(that.y)) return false;\n        return true;\n    }\n\n    /**\n     * Does this two-dimensional interval contain the point p?\n     * @param p the two-dimensional point\n     * @return true if this two-dimensional interval contains the point p; false otherwise\n     */\n    public boolean contains(Point2D p) {\n        return x.contains(p.x())  && y.contains(p.y());\n    }\n\n    /**\n     * Returns the area of this two-dimensional interval.\n     * @return the area of this two-dimensional interval\n     */\n    public double area() {\n        return x.length() * y.length();\n    }\n        \n    /**\n     * Returns a string representation of this two-dimensional interval.\n     * @return a string representation of this two-dimensional interval\n     *    in the form [xmin, xmax] x [ymin, ymax]\n     */\n    public String toString() {\n        return x + \" x \" + y;\n    }\n\n    /**\n     * Does this interval equal the other interval?\n     * @param other the other interval\n     * @return true if this interval equals the other interval; false otherwise\n     */\n    public boolean equals(Object other) {\n        if (other == this) return true;\n        if (other == null) return false;\n        if (other.getClass() != this.getClass()) return false;\n        Interval2D that = (Interval2D) other;\n        return this.x.equals(that.x) && this.y.equals(that.y);\n    }\n\n \n    /**\n     * Returns an integer hash code for this interval.  \n     * @return an integer hash code for this interval \n     */\n    public int hashCode() {\n        int hash1 = x.hashCode();\n        int hash2 = y.hashCode();\n        return 31*hash1 + hash2;\n    }\n\n    /**\n     * Draws this two-dimensional interval to standard draw.\n     */\n    public void draw() {\n        double xc = (x.min() + x.max()) / 2.0;\n        double yc = (y.min() + y.max()) / 2.0;\n        StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0);\n    }\n\n    /**\n     * Unit tests the {@code Interval2D} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        double xmin = Double.parseDouble(args[0]);\n        double xmax = Double.parseDouble(args[1]);\n        double ymin = Double.parseDouble(args[2]);\n        double ymax = Double.parseDouble(args[3]);\n        int trials = Integer.parseInt(args[4]);\n\n        Interval1D xInterval = new Interval1D(xmin, xmax);\n        Interval1D yInterval = new Interval1D(ymin, ymax);\n        Interval2D box = new Interval2D(xInterval, yInterval);\n        box.draw();\n\n        Counter counter = new Counter(\"hits\");\n        for (int t = 0; t < trials; t++) {\n            double x = StdRandom.uniform(0.0, 1.0);\n            double y = StdRandom.uniform(0.0, 1.0);\n            Point2D point = new Point2D(x, y);\n\n            if (box.contains(point)) counter.increment();\n            else                     point.draw();\n        }\n\n        StdOut.println(counter);\n        StdOut.printf(\"box area = %.2f\\n\", box.area());\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/MinPQ.java",
    "content": "/******************************************************************************\n *  Compilation:  javac MinPQ.java\n *  Execution:    java MinPQ < input.txt\n *  Dependencies: StdIn.java StdOut.java\n *  Data files:   http://algs4.cs.princeton.edu/24pq/tinyPQ.txt\n *  \n *  Generic min priority queue implementation with a binary heap.\n *  Can be used with a comparator instead of the natural order.\n *\n *  % java MinPQ < tinyPQ.txt\n *  E A E (6 left on pq)\n *\n *  We use a one-based array to simplify parent and child calculations.\n *\n *  Can be optimized by replacing full exchanges with half exchanges\n *  (ala insertion sort).\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n *  The {@code MinPQ} class represents a priority queue of generic keys.\n *  It supports the usual <em>insert</em> and <em>delete-the-minimum</em>\n *  operations, along with methods for peeking at the minimum key,\n *  testing if the priority queue is empty, and iterating through\n *  the keys.\n *  <p>\n *  This implementation uses a binary heap.\n *  The <em>insert</em> and <em>delete-the-minimum</em> operations take\n *  logarithmic amortized time.\n *  The <em>min</em>, <em>size</em>, and <em>is-empty</em> operations take constant time.\n *  Construction takes time proportional to the specified capacity or the number of\n *  items used to initialize the data structure.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/24pq\">Section 2.4</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Key> the generic type of key on this priority queue\n */\npublic class MinPQ<Key> implements Iterable<Key> {\n    private Key[] pq;                    // store items at indices 1 to n\n    private int n;                       // number of items on priority queue\n    private Comparator<Key> comparator;  // optional comparator\n\n    /**\n     * Initializes an empty priority queue with the given initial capacity.\n     *\n     * @param  initCapacity the initial capacity of this priority queue\n     */\n    public MinPQ(int initCapacity) {\n        pq = (Key[]) new Object[initCapacity + 1];\n        n = 0;\n    }\n\n    /**\n     * Initializes an empty priority queue.\n     */\n    public MinPQ() {\n        this(1);\n    }\n\n    /**\n     * Initializes an empty priority queue with the given initial capacity,\n     * using the given comparator.\n     *\n     * @param  initCapacity the initial capacity of this priority queue\n     * @param  comparator the order to use when comparing keys\n     */\n    public MinPQ(int initCapacity, Comparator<Key> comparator) {\n        this.comparator = comparator;\n        pq = (Key[]) new Object[initCapacity + 1];\n        n = 0;\n    }\n\n    /**\n     * Initializes an empty priority queue using the given comparator.\n     *\n     * @param  comparator the order to use when comparing keys\n     */\n    public MinPQ(Comparator<Key> comparator) {\n        this(1, comparator);\n    }\n\n    /**\n     * Initializes a priority queue from the array of keys.\n     * <p>\n     * Takes time proportional to the number of keys, using sink-based heap construction.\n     *\n     * @param  keys the array of keys\n     */\n    public MinPQ(Key[] keys) {\n        n = keys.length;\n        pq = (Key[]) new Object[keys.length + 1];\n        for (int i = 0; i < n; i++)\n            pq[i+1] = keys[i];\n        for (int k = n/2; k >= 1; k--)\n            sink(k);\n        assert isMinHeap();\n    }\n\n    /**\n     * Returns true if this priority queue is empty.\n     *\n     * @return {@code true} if this priority queue is empty;\n     *         {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return n == 0;\n    }\n\n    /**\n     * Returns the number of keys on this priority queue.\n     *\n     * @return the number of keys on this priority queue\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Returns a smallest key on this priority queue.\n     *\n     * @return a smallest key on this priority queue\n     * @throws NoSuchElementException if this priority queue is empty\n     */\n    public Key min() {\n        if (isEmpty()) throw new NoSuchElementException(\"Priority queue underflow\");\n        return pq[1];\n    }\n\n    // helper function to double the size of the heap array\n    private void resize(int capacity) {\n        assert capacity > n;\n        Key[] temp = (Key[]) new Object[capacity];\n        for (int i = 1; i <= n; i++) {\n            temp[i] = pq[i];\n        }\n        pq = temp;\n    }\n\n    /**\n     * Adds a new key to this priority queue.\n     *\n     * @param  x the key to add to this priority queue\n     */\n    public void insert(Key x) {\n        // double size of array if necessary\n        if (n == pq.length - 1) resize(2 * pq.length);\n\n        // add x, and percolate it up to maintain heap invariant\n        pq[++n] = x;\n        swim(n);\n        assert isMinHeap();\n    }\n\n    /**\n     * Removes and returns a smallest key on this priority queue.\n     *\n     * @return a smallest key on this priority queue\n     * @throws NoSuchElementException if this priority queue is empty\n     */\n    public Key delMin() {\n        if (isEmpty()) throw new NoSuchElementException(\"Priority queue underflow\");\n        exch(1, n);\n        Key min = pq[n--];\n        sink(1);\n        pq[n+1] = null;         // avoid loitering and help with garbage collection\n        if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length  / 2);\n        assert isMinHeap();\n        return min;\n    }\n\n\n   /***************************************************************************\n    * Helper functions to restore the heap invariant.\n    ***************************************************************************/\n\n    private void swim(int k) {\n        while (k > 1 && greater(k/2, k)) {\n            exch(k, k/2);\n            k = k/2;\n        }\n    }\n\n    private void sink(int k) {\n        while (2*k <= n) {\n            int j = 2*k;\n            if (j < n && greater(j, j+1)) j++;\n            if (!greater(k, j)) break;\n            exch(k, j);\n            k = j;\n        }\n    }\n\n   /***************************************************************************\n    * Helper functions for compares and swaps.\n    ***************************************************************************/\n    private boolean greater(int i, int j) {\n        if (comparator == null) {\n            return ((Comparable<Key>) pq[i]).compareTo(pq[j]) > 0;\n        }\n        else {\n            return comparator.compare(pq[i], pq[j]) > 0;\n        }\n    }\n\n    private void exch(int i, int j) {\n        Key swap = pq[i];\n        pq[i] = pq[j];\n        pq[j] = swap;\n    }\n\n    // is pq[1..N] a min heap?\n    private boolean isMinHeap() {\n        return isMinHeap(1);\n    }\n\n    // is subtree of pq[1..n] rooted at k a min heap?\n    private boolean isMinHeap(int k) {\n        if (k > n) return true;\n        int left = 2*k;\n        int right = 2*k + 1;\n        if (left  <= n && greater(k, left))  return false;\n        if (right <= n && greater(k, right)) return false;\n        return isMinHeap(left) && isMinHeap(right);\n    }\n\n\n    /**\n     * Returns an iterator that iterates over the keys on this priority queue\n     * in ascending order.\n     * <p>\n     * The iterator doesn't implement {@code remove()} since it's optional.\n     *\n     * @return an iterator that iterates over the keys in ascending order\n     */\n    public Iterator<Key> iterator() { return new HeapIterator(); }\n\n    private class HeapIterator implements Iterator<Key> {\n        // create a new pq\n        private MinPQ<Key> copy;\n\n        // add all items to copy of heap\n        // takes linear time since already in heap order so no keys move\n        public HeapIterator() {\n            if (comparator == null) copy = new MinPQ<Key>(size());\n            else                    copy = new MinPQ<Key>(size(), comparator);\n            for (int i = 1; i <= n; i++)\n                copy.insert(pq[i]);\n        }\n\n        public boolean hasNext()  { return !copy.isEmpty();                     }\n        public void remove()      { throw new UnsupportedOperationException();  }\n\n        public Key next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            return copy.delMin();\n        }\n    }\n\n    /**\n     * Unit tests the {@code MinPQ} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        MinPQ<String> pq = new MinPQ<String>();\n        while (!StdIn.isEmpty()) {\n            String item = StdIn.readString();\n            if (!item.equals(\"-\")) pq.insert(item);\n            else if (!pq.isEmpty()) StdOut.print(pq.delMin() + \" \");\n        }\n        StdOut.println(\"(\" + pq.size() + \" left on pq)\");\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Out.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Out.java\n *  Execution:    java Out\n *  Dependencies: none\n *\n *  Writes data of various types to: stdout, file, or socket.\n *\n ******************************************************************************/\n\npackage algs4;\n\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.net.Socket;\nimport java.util.Locale;\n\n/**\n *  This class provides methods for writing strings and numbers to\n *  various output streams, including standard output, file, and sockets.\n *  <p>\n *  For additional documentation, see\n *  <a href=\"http://introcs.cs.princeton.edu/31datatype\">Section 3.1</a> of\n *  <i>Computer Science: An Interdisciplinary Approach</i>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Out {\n\n    // force Unicode UTF-8 encoding; otherwise it's system dependent\n    private static final String CHARSET_NAME = \"UTF-8\";\n\n    // assume language = English, country = US for consistency with In\n    private static final Locale LOCALE = Locale.US;\n\n    private PrintWriter out;\n\n   /**\n     * Initializes an output stream from a {@link OutputStream}.\n     *\n     * @param  os the {@code OutputStream}\n     */\n    public Out(OutputStream os) {\n        try {\n            OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);\n            out = new PrintWriter(osw, true);\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n   /**\n     * Initializes an output stream from standard output.\n     */\n    public Out() {\n        this(System.out);\n    }\n\n   /**\n     * Initializes an output stream from a socket.\n     *\n     * @param  socket the socket\n     */\n    public Out(Socket socket) {\n        try {\n            OutputStream os = socket.getOutputStream();\n            OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);\n            out = new PrintWriter(osw, true);\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n   /**\n     * Initializes an output stream from a file.\n     *\n     * @param  filename the name of the file\n     */\n    public Out(String filename) {\n        try {\n            OutputStream os = new FileOutputStream(filename);\n            OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);\n            out = new PrintWriter(osw, true);\n        }\n        catch (IOException e) {\n            e.printStackTrace();\n        }\n    }\n\n   /**\n     * Closes the output stream.\n     */\n    public void close() {\n        out.close();\n    }\n\n   /**\n     * Terminates the current line by printing the line-separator string.\n     */\n    public void println() {\n        out.println();\n    }\n\n   /**\n     * Prints an object to this output stream and then terminates the line.\n     *\n     * @param x the object to print\n     */\n    public void println(Object x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a boolean to this output stream and then terminates the line.\n     *\n     * @param x the boolean to print\n     */\n    public void println(boolean x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a character to this output stream and then terminates the line.\n     *\n     * @param x the character to print\n     */\n    public void println(char x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a double to this output stream and then terminates the line.\n     *\n     * @param x the double to print\n     */\n    public void println(double x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a float to this output stream and then terminates the line.\n     *\n     * @param x the float to print\n     */\n    public void println(float x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints an integer to this output stream and then terminates the line.\n     *\n     * @param x the integer to print\n     */\n    public void println(int x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a long to this output stream and then terminates the line.\n     *\n     * @param x the long to print\n     */\n    public void println(long x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a byte to this output stream and then terminates the line.\n     * <p>\n     * To write binary data, see {@link BinaryOut}.\n     *\n     * @param x the byte to print\n     */\n    public void println(byte x) {\n        out.println(x);\n    }\n\n\n\n   /**\n     * Flushes this output stream.\n     */\n    public void print() {\n        out.flush();\n    }\n\n   /**\n     * Prints an object to this output stream and flushes this output stream.\n     * \n     * @param x the object to print\n     */\n    public void print(Object x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a boolean to this output stream and flushes this output stream.\n     * \n     * @param x the boolean to print\n     */\n    public void print(boolean x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a character to this output stream and flushes this output stream.\n     * \n     * @param x the character to print\n     */\n    public void print(char x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a double to this output stream and flushes this output stream.\n     * \n     * @param x the double to print\n     */\n    public void print(double x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a float to this output stream and flushes this output stream.\n     * \n     * @param x the float to print\n     */\n    public void print(float x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints an integer to this output stream and flushes this output stream.\n     * \n     * @param x the integer to print\n     */\n    public void print(int x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a long integer to this output stream and flushes this output stream.\n     * \n     * @param x the long integer to print\n     */\n    public void print(long x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a byte to this output stream and flushes this output stream.\n     * \n     * @param x the byte to print\n     */\n    public void print(byte x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a formatted string to this output stream, using the specified format\n     * string and arguments, and then flushes this output stream.\n     *\n     * @param format the format string\n     * @param args   the arguments accompanying the format string\n     */\n    public void printf(String format, Object... args) {\n        out.printf(LOCALE, format, args);\n        out.flush();\n    }\n\n   /**\n     * Prints a formatted string to this output stream, using the specified\n     * locale, format string, and arguments, and then flushes this output stream.\n     *\n     * @param locale the locale\n     * @param format the format string\n     * @param args   the arguments accompanying the format string\n     */\n    public void printf(Locale locale, String format, Object... args) {\n        out.printf(locale, format, args);\n        out.flush();\n    }\n\n\n   /**\n     * A test client.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Out out;\n\n        // write to stdout\n        out = new Out();\n        out.println(\"Test 1\");\n        out.close();\n\n        // write to a file\n        out = new Out(\"test.txt\");\n        out.println(\"Test 2\");\n        out.close();\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Particle.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Particle.java\n *  Execution:    none\n *  Dependencies: StdDraw.java\n *      \n *  A particle moving in the unit box with a given position, velocity,\n *  radius, and mass.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.awt.Color;\n\n/**\n *  The {@code Particle} class represents a particle moving in the unit box,\n *  with a given position, velocity, radius, and mass. Methods are provided\n *  for moving the particle and for predicting and resolvling elastic\n *  collisions with vertical walls, horizontal walls, and other particles.\n *  This data type is mutable because the position and velocity change.\n *  <p>\n *  For additional documentation, \n *  see <a href=\"http://algs4.cs.princeton.edu/61event\">Section 6.1</a> of \n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. \n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class Particle {\n    private static final double INFINITY = Double.POSITIVE_INFINITY;\n\n    private double rx, ry;        // position\n    private double vx, vy;        // velocity\n    private int count;            // number of collisions so far\n    private final double radius;  // radius\n    private final double mass;    // mass\n    private final Color color;    // color\n\n\n    /**\n     * Initializes a particle with the specified position, velocity, radius, mass, and color.\n     *\n     * @param  rx <em>x</em>-coordinate of position\n     * @param  ry <em>y</em>-coordinate of position\n     * @param  vx <em>x</em>-coordinate of velocity\n     * @param  vy <em>y</em>-coordinate of velocity\n     * @param  radius the radius\n     * @param  mass the mass\n     * @param  color the color\n     */\n    public Particle(double rx, double ry, double vx, double vy, double radius, double mass, Color color) {\n        this.vx = vx;\n        this.vy = vy;\n        this.rx = rx;\n        this.ry = ry;\n        this.radius = radius;\n        this.mass   = mass;\n        this.color  = color;\n    }\n         \n    /**\n     * Initializes a particle with a random position and velocity.\n     * The position is uniform in the unit box; the velocity in\n     * either direciton is chosen uniformly at random.\n     */\n    public Particle() {\n        rx     = StdRandom.uniform(0.0, 1.0);\n        ry     = StdRandom.uniform(0.0, 1.0);\n        vx     = StdRandom.uniform(-0.005, 0.005);\n        vy     = StdRandom.uniform(-0.005, 0.005);\n        radius = 0.01;\n        mass   = 0.5;\n        color  = Color.BLACK;\n    }\n\n    /**\n     * Moves this particle in a straight line (based on its velocity)\n     * for the specified amount of time.\n     *\n     * @param  dt the amount of time\n     */\n    public void move(double dt) {\n        rx += vx * dt;\n        ry += vy * dt;\n    }\n\n    /**\n     * Draws this particle to standard draw.\n     */\n    public void draw() {\n        StdDraw.setPenColor(color);\n        StdDraw.filledCircle(rx, ry, radius);\n    }\n\n    /**\n     * Returns the number of collisions involving this particle with\n     * vertical walls, horizontal walls, or other particles.\n     * This is equal to the number of calls to {@link #bounceOff},\n     * {@link #bounceOffVerticalWall}, and\n     * {@link #bounceOffHorizontalWall}.\n     *\n     * @return the number of collisions involving this particle with\n     *         vertical walls, horizontal walls, or other particles\n     */\n    public int count() {\n        return count;\n    }\n\n    /**\n     * Returns the amount of time for this particle to collide with the specified\n     * particle, assuming no interening collisions.\n     *\n     * @param  that the other particle\n     * @return the amount of time for this particle to collide with the specified\n     *         particle, assuming no interening collisions; \n     *         {@code Double.POSITIVE_INFINITY} if the particles will not collide\n     */\n    public double timeToHit(Particle that) {\n        if (this == that) return INFINITY;\n        double dx  = that.rx - this.rx;\n        double dy  = that.ry - this.ry;\n        double dvx = that.vx - this.vx;\n        double dvy = that.vy - this.vy;\n        double dvdr = dx*dvx + dy*dvy;\n        if (dvdr > 0) return INFINITY;\n        double dvdv = dvx*dvx + dvy*dvy;\n        double drdr = dx*dx + dy*dy;\n        double sigma = this.radius + that.radius;\n        double d = (dvdr*dvdr) - dvdv * (drdr - sigma*sigma);\n        // if (drdr < sigma*sigma) StdOut.println(\"overlapping particles\");\n        if (d < 0) return INFINITY;\n        return -(dvdr + Math.sqrt(d)) / dvdv;\n    }\n\n    /**\n     * Returns the amount of time for this particle to collide with a vertical\n     * wall, assuming no interening collisions.\n     *\n     * @return the amount of time for this particle to collide with a vertical wall,\n     *         assuming no interening collisions; \n     *         {@code Double.POSITIVE_INFINITY} if the particle will not collide\n     *         with a vertical wall\n     */\n    public double timeToHitVerticalWall() {\n        if      (vx > 0) return (1.0 - rx - radius) / vx;\n        else if (vx < 0) return (radius - rx) / vx;  \n        else             return INFINITY;\n    }\n\n    /**\n     * Returns the amount of time for this particle to collide with a horizontal\n     * wall, assuming no interening collisions.\n     *\n     * @return the amount of time for this particle to collide with a horizontal wall,\n     *         assuming no interening collisions; \n     *         {@code Double.POSITIVE_INFINITY} if the particle will not collide\n     *         with a horizontal wall\n     */\n    public double timeToHitHorizontalWall() {\n        if      (vy > 0) return (1.0 - ry - radius) / vy;\n        else if (vy < 0) return (radius - ry) / vy;\n        else             return INFINITY;\n    }\n\n    /**\n     * Updates the velocities of this particle and the specified particle according\n     * to the laws of elastic collision. Assumes that the particles are colliding\n     * at this instant.\n     *\n     * @param  that the other particle\n     */\n    public void bounceOff(Particle that) {\n        double dx  = that.rx - this.rx;\n        double dy  = that.ry - this.ry;\n        double dvx = that.vx - this.vx;\n        double dvy = that.vy - this.vy;\n        double dvdr = dx*dvx + dy*dvy;             // dv dot dr\n        double dist = this.radius + that.radius;   // distance between particle centers at collison\n\n        // magnitude of normal force\n        double magnitude = 2 * this.mass * that.mass * dvdr / ((this.mass + that.mass) * dist);\n\n        // normal force, and in x and y directions\n        double fx = magnitude * dx / dist;\n        double fy = magnitude * dy / dist;\n\n        // update velocities according to normal force\n        this.vx += fx / this.mass;\n        this.vy += fy / this.mass;\n        that.vx -= fx / that.mass;\n        that.vy -= fy / that.mass;\n\n        // update collision counts\n        this.count++;\n        that.count++;\n    }\n\n    /**\n     * Updates the velocity of this particle upon collision with a vertical\n     * wall (by reflecting the velocity in the <em>x</em>-direction).\n     * Assumes that the particle is colliding with a vertical wall at this instant.\n     */\n    public void bounceOffVerticalWall() {\n        vx = -vx;\n        count++;\n    }\n\n    /**\n     * Updates the velocity of this particle upon collision with a horizontal\n     * wall (by reflecting the velocity in the <em>y</em>-direction).\n     * Assumes that the particle is colliding with a horizontal wall at this instant.\n     */\n    public void bounceOffHorizontalWall() {\n        vy = -vy;\n        count++;\n    }\n\n    /**\n     * Returns the kinetic energy of this particle.\n     * The kinetic energy is given by the formula 1/2 <em>m</em> <em>v</em><sup>2</sup>,\n     * where <em>m</em> is the mass of this particle and <em>v</em> is its velocity.\n     *\n     * @return the kinetic energy of this particle\n     */\n    public double kineticEnergy() {\n        return 0.5 * mass * (vx*vx + vy*vy);\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Picture.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Picture.java\n *  Execution:    java Picture imagename\n *  Dependencies: none\n *\n *  Data type for manipulating individual pixels of an image. The original\n *  image can be read from a file in jpg, gif, or png format, or the\n *  user can create a blank image of a given size. Includes methods for\n *  displaying the image in a window on the screen or saving to a file.\n *\n *  % java Picture mandrill.jpg\n *\n *  Remarks\n *  -------\n *   - pixel (x, y) is column x and row y, where (0, 0) is upper left\n *\n *   - see also GrayPicture.java for a grayscale version\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.awt.Color;\nimport java.awt.FileDialog;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URL;\nimport javax.imageio.ImageIO;\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.KeyStroke;\n\n\n/**\n *  This class provides methods for manipulating individual pixels of\n *  an image. The original image can be read from a {@code .jpg}, {@code .gif},\n *  or {@code .png} file or the user can create a blank image of a given size.\n *  This class includes methods for displaying the image in a window on\n *  the screen or saving it to a file.\n *  <p>\n *  Pixel (<em>col</em>, <em>row</em>) is column <em>col</em> and row <em>row</em>.\n *  By default, the origin (0, 0) is the pixel in the top-left corner,\n *  which is a common convention in image processing.\n *  The method {@code setOriginLowerLeft()} change the origin to the lower left.\n *  <p>\n *  For additional documentation, see\n *  <a href=\"http://introcs.cs.princeton.edu/31datatype\">Section 3.1</a> of\n *  <i>Computer Science: An Interdisciplinary Approach</i>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class Picture implements ActionListener {\n    private BufferedImage image;               // the rasterized image\n    private JFrame frame;                      // on-screen view\n    private String filename;                   // name of file\n    private boolean isOriginUpperLeft = true;  // location of origin\n    private final int width, height;           // width and height\n\n   /**\n     * Initializes a blank {@code width}-by-{@code height} picture, with {@code width} columns\n     * and {@code height} rows, where each pixel is black.\n     *\n     * @param width the width of the picture\n     * @param height the height of the picture\n     * @throws IllegalArgumentException if {@code width} is negative\n     * @throws IllegalArgumentException if {@code height} is negative\n     */\n    public Picture(int width, int height) {\n        if (width  < 0) throw new IllegalArgumentException(\"width must be nonnegative\");\n        if (height < 0) throw new IllegalArgumentException(\"height must be nonnegative\");\n        this.width  = width;\n        this.height = height;\n        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n        // set to TYPE_INT_ARGB to support transparency\n        filename = width + \"-by-\" + height;\n    }\n\n   /**\n     * Initializes a new picture that is a deep copy of the argument picture.\n     *\n     * @param picture the picture to copy\n     */\n    public Picture(Picture picture) {\n        width  = picture.width();\n        height = picture.height();\n        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n        filename = picture.filename;\n        for (int col = 0; col < width(); col++)\n            for (int row = 0; row < height(); row++)\n                image.setRGB(col, row, picture.get(col, row).getRGB());\n    }\n\n   /**\n     * Initializes a picture by reading from a file or URL.\n     *\n     * @param filename the name of the file (.png, .gif, or .jpg) or URL.\n     * @throws IllegalArgumentException if cannot read image\n     */\n    public Picture(String filename) {\n        this.filename = filename;\n        try {\n            // try to read from file in working directory\n            File file = new File(filename);\n            if (file.isFile()) {\n                image = ImageIO.read(file);\n            }\n\n            // now try to read from file in same directory as this .class file\n            else {\n                URL url = getClass().getResource(filename);\n                if (url == null) {\n                    url = new URL(filename);\n                }\n                image = ImageIO.read(url);\n            }\n\n            if (image == null) {\n                throw new IllegalArgumentException(\"could not read image file: \" + filename);\n            }\n\n            width  = image.getWidth(null);\n            height = image.getHeight(null);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"could not open image file: \" + filename, ioe);\n        }\n    }\n\n   /**\n     * Initializes a picture by reading in a .png, .gif, or .jpg from a file.\n     *\n     * @param file the file\n     * @throws IllegalArgumentException if cannot read image\n     */\n    public Picture(File file) {\n        try {\n            image = ImageIO.read(file);\n        }\n        catch (IOException ioe) {\n            throw new IllegalArgumentException(\"could not open file: \" + file, ioe);\n        }\n        if (image == null) {\n            throw new IllegalArgumentException(\"could not read file: \" + file);\n        }\n        width  = image.getWidth(null);\n        height = image.getHeight(null);\n        filename = file.getName();\n    }\n\n   /**\n     * Returns a JLabel containing this picture, for embedding in a JPanel,\n     * JFrame or other GUI widget.\n     *\n     * @return the {@code JLabel}\n     */\n    public JLabel getJLabel() {\n        if (image == null) return null;         // no image available\n        ImageIcon icon = new ImageIcon(image);\n        return new JLabel(icon);\n    }\n\n   /**\n     * Sets the origin to be the upper left pixel. This is the default.\n     */\n    public void setOriginUpperLeft() {\n        isOriginUpperLeft = true;\n    }\n\n   /**\n     * Sets the origin to be the lower left pixel.\n     */\n    public void setOriginLowerLeft() {\n        isOriginUpperLeft = false;\n    }\n\n   /**\n     * Displays the picture in a window on the screen.\n     */\n    public void show() {\n\n        // create the GUI for viewing the image if needed\n        if (frame == null) {\n            frame = new JFrame();\n\n            JMenuBar menuBar = new JMenuBar();\n            JMenu menu = new JMenu(\"File\");\n            menuBar.add(menu);\n            JMenuItem menuItem1 = new JMenuItem(\" Save...   \");\n            menuItem1.addActionListener(this);\n            menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,\n                                     Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));\n            menu.add(menuItem1);\n            frame.setJMenuBar(menuBar);\n\n\n\n            frame.setContentPane(getJLabel());\n            // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n            frame.setTitle(filename);\n            frame.setResizable(false);\n            frame.pack();\n            frame.setVisible(true);\n        }\n\n        // draw\n        frame.repaint();\n    }\n\n   /**\n     * Returns the height of the picture.\n     *\n     * @return the height of the picture (in pixels)\n     */\n    public int height() {\n        return height;\n    }\n\n   /**\n     * Returns the width of the picture.\n     *\n     * @return the width of the picture (in pixels)\n     */\n    public int width() {\n        return width;\n    }\n\n    private void validateRow(int row) {\n        if (row < 0 || row >= height())\n            throw new IndexOutOfBoundsException(\"row must be between 0 and \" + (height() - 1) + \": \" + row);\n    }\n\n    private void validateCol(int col) {\n        if (col < 0 || col >= width())\n            throw new IndexOutOfBoundsException(\"col must be between 0 and \" + (width() - 1) + \": \" + col);\n    }\n\n   /**\n     * Returns the color of pixel ({@code col}, {@code row}).\n     *\n     * @param col the column index\n     * @param row the row index\n     * @return the color of pixel ({@code col}, {@code row})\n     * @throws IndexOutOfBoundsException unless both {@code 0 <= col < width} and {@code 0 <= row < height}\n     */\n    public Color get(int col, int row) {\n        validateCol(col);\n        validateRow(row);\n        if (isOriginUpperLeft) return new Color(image.getRGB(col, row));\n        else                   return new Color(image.getRGB(col, height - row - 1));\n    }\n\n   /**\n     * Sets the color of pixel ({@code col}, {@code row}) to given color.\n     *\n     * @param col the column index\n     * @param row the row index\n     * @param color the color\n     * @throws IndexOutOfBoundsException unless both {@code 0 <= col < width} and {@code 0 <= row < height}\n     * @throws IllegalArgumentException if {@code color} is {@code null}\n     */\n    public void set(int col, int row, Color color) {\n        validateCol(col);\n        validateRow(row);\n        if (color == null) throw new IllegalArgumentException(\"color argument is null\");\n        if (isOriginUpperLeft) image.setRGB(col, row, color.getRGB());\n        else                   image.setRGB(col, height - row - 1, color.getRGB());\n    }\n\n   /**\n     * Returns true if this picture is equal to the argument picture.\n     *\n     * @param other the other picture\n     * @return {@code true} if this picture is the same dimension as {@code other}\n     *         and if all pixels have the same color; {@code false} otherwise\n     */\n    public boolean equals(Object other) {\n        if (other == this) return true;\n        if (other == null) return false;\n        if (other.getClass() != this.getClass()) return false;\n        Picture that = (Picture) other;\n        if (this.width()  != that.width())  return false;\n        if (this.height() != that.height()) return false;\n        for (int col = 0; col < width(); col++)\n            for (int row = 0; row < height(); row++)\n                if (!this.get(col, row).equals(that.get(col, row))) return false;\n        return true;\n    }\n\n    /**\n     * This operation is not supported because pictures are mutable.\n     *\n     * @return does not return a value\n     * @throws UnsupportedOperationException if called\n     */\n    public int hashCode() {\n        throw new UnsupportedOperationException(\"hashCode() is not supported because pictures are mutable\");\n    }\n\n   /**\n     * Saves the picture to a file in a standard image format.\n     * The filetype must be .png or .jpg.\n     *\n     * @param name the name of the file\n     */\n    public void save(String name) {\n        save(new File(name));\n    }\n\n   /**\n     * Saves the picture to a file in a PNG or JPEG image format.\n     *\n     * @param file the file\n     */\n    public void save(File file) {\n        filename = file.getName();\n        if (frame != null) frame.setTitle(filename);\n        String suffix = filename.substring(filename.lastIndexOf('.') + 1);\n        if (\"jpg\".equalsIgnoreCase(suffix) || \"png\".equalsIgnoreCase(suffix)) {\n            try {\n                ImageIO.write(image, suffix, file);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n        else {\n            System.out.println(\"Error: filename must end in .jpg or .png\");\n        }\n    }\n\n   /**\n     * Opens a save dialog box when the user selects \"Save As\" from the menu.\n     */\n    @Override\n    public void actionPerformed(ActionEvent e) {\n        FileDialog chooser = new FileDialog(frame,\n                             \"Use a .png or .jpg extension\", FileDialog.SAVE);\n        chooser.setVisible(true);\n        if (chooser.getFile() != null) {\n            save(chooser.getDirectory() + File.separator + chooser.getFile());\n        }\n    }\n\n\n   /**\n     * Unit tests this {@code Picture} data type.\n     * Reads a picture specified by the command-line argument,\n     * and shows it in a window on the screen.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Picture picture = new Picture(args[0]);\n        System.out.printf(\"%d-by-%d\\n\", picture.width(), picture.height());\n        picture.show();\n    }\n\n}\n\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/PictureDump.java",
    "content": "/******************************************************************************\n *  Compilation:  javac PictureDump.java\n *  Execution:    java PictureDump width height < file\n *  Dependencies: BinaryStdIn.java Picture.java\n *  Data file:    http://introcs.cs.princeton.edu/stdlib/abra.txt\n *  \n *  Reads in a binary file and writes out the bits as w-by-h picture,\n *  with the 1 bits in black and the 0 bits in white.\n *\n *  % more abra.txt \n *  ABRACADABRA!\n *\n *  % java PictureDump 16 6 < abra.txt\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.awt.Color;\n\n\n/**\n *  The {@code PictureDump} class provides a client for displaying the contents\n *  of a binary file as a black-and-white picture.\n *  <p>\n *  For additional documentation,\n *  see <a href=\"http://algs4.cs.princeton.edu/55compress\">Section 5.5</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *  <p>\n *  See also {@link BinaryDump} and {@link HexDump}.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic class PictureDump {\n\n    // Do not instantiate.\n    private PictureDump() { }\n\n    /**\n     * Reads in a sequence of bytes from standard input and draws\n     * them to standard drawing output as a width-by-height picture,\n     * using black for 1 and white for 0 (and red for any leftover\n     * pixels).\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int width = Integer.parseInt(args[0]);\n        int height = Integer.parseInt(args[1]);\n        Picture picture = new Picture(width, height);\n        for (int row = 0; row < height; row++) {\n            for (int col = 0; col < width; col++) {\n                if (!BinaryStdIn.isEmpty()) {\n                    boolean bit = BinaryStdIn.readBoolean();\n                    if (bit) picture.set(col, row, Color.BLACK);\n                    else     picture.set(col, row, Color.WHITE);\n                }\n                else {\n                    picture.set(col, row, Color.RED);\n                }\n            }\n        }\n        picture.show();\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Point2D.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Point2D.java\n *  Execution:    java Point2D x0 y0 N\n *  Dependencies: StdDraw.java StdRandom.java\n *\n *  Immutable point data type for points in the plane.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n\n/**\n *  The {@code Point} class is an immutable data type to encapsulate a\n *  two-dimensional point with real-value coordinates.\n *  <p>\n *  Note: in order to deal with the difference behavior of double and \n *  Double with respect to -0.0 and +0.0, the Point2D constructor converts\n *  any coordinates that are -0.0 to +0.0.\n *  <p>\n *  For additional documentation, \n *  see <a href=\"http://algs4.cs.princeton.edu/12oop\">Section 1.2</a> of \n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. \n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class Point2D implements Comparable<Point2D> {\n\n    /**\n     * Compares two points by x-coordinate.\n     */\n    public static final Comparator<Point2D> X_ORDER = new XOrder();\n\n    /**\n     * Compares two points by y-coordinate.\n     */\n    public static final Comparator<Point2D> Y_ORDER = new YOrder();\n\n    /**\n     * Compares two points by polar radius.\n     */\n    public static final Comparator<Point2D> R_ORDER = new ROrder();\n\n    private final double x;    // x coordinate\n    private final double y;    // y coordinate\n\n    /**\n     * Initializes a new point (x, y).\n     * @param x the x-coordinate\n     * @param y the y-coordinate\n     * @throws IllegalArgumentException if either {@code x} or {@code y}\n     *    is {@code Double.NaN}, {@code Double.POSITIVE_INFINITY} or\n     *    {@code Double.NEGATIVE_INFINITY}\n     */\n    public Point2D(double x, double y) {\n        if (Double.isInfinite(x) || Double.isInfinite(y))\n            throw new IllegalArgumentException(\"Coordinates must be finite\");\n        if (Double.isNaN(x) || Double.isNaN(y))\n            throw new IllegalArgumentException(\"Coordinates cannot be NaN\");\n        if (x == 0.0) this.x = 0.0;  // convert -0.0 to +0.0\n        else          this.x = x;\n\n        if (y == 0.0) this.y = 0.0;  // convert -0.0 to +0.0\n        else          this.y = y;\n    }\n\n    /**\n     * Returns the x-coordinate.\n     * @return the x-coordinate\n     */\n    public double x() {\n        return x;\n    }\n\n    /**\n     * Returns the y-coordinate.\n     * @return the y-coordinate\n     */\n    public double y() {\n        return y;\n    }\n\n    /**\n     * Returns the polar radius of this point.\n     * @return the polar radius of this point in polar coordiantes: sqrt(x*x + y*y)\n     */\n    public double r() {\n        return Math.sqrt(x*x + y*y);\n    }\n\n    /**\n     * Returns the angle of this point in polar coordinates.\n     * @return the angle (in radians) of this point in polar coordiantes (between -pi/2 and pi/2)\n     */\n    public double theta() {\n        return Math.atan2(y, x);\n    }\n\n    /**\n     * Returns the angle between this point and that point.\n     * @return the angle in radians (between -pi and pi) between this point and that point (0 if equal)\n     */\n    private double angleTo(Point2D that) {\n        double dx = that.x - this.x;\n        double dy = that.y - this.y;\n        return Math.atan2(dy, dx);\n    }\n\n    /**\n     * Returns true if a→b→c is a counterclockwise turn.\n     * @param a first point\n     * @param b second point\n     * @param c third point\n     * @return { -1, 0, +1 } if a→b→c is a { clockwise, collinear; counterclocwise } turn.\n     */\n    public static int ccw(Point2D a, Point2D b, Point2D c) {\n        double area2 = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);\n        if      (area2 < 0) return -1;\n        else if (area2 > 0) return +1;\n        else                return  0;\n    }\n\n    /**\n     * Returns twice the signed area of the triangle a-b-c.\n     * @param a first point\n     * @param b second point\n     * @param c third point\n     * @return twice the signed area of the triangle a-b-c\n     */\n    public static double area2(Point2D a, Point2D b, Point2D c) {\n        return (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);\n    }\n\n    /**\n     * Returns the Euclidean distance between this point and that point.\n     * @param that the other point\n     * @return the Euclidean distance between this point and that point\n     */\n    public double distanceTo(Point2D that) {\n        double dx = this.x - that.x;\n        double dy = this.y - that.y;\n        return Math.sqrt(dx*dx + dy*dy);\n    }\n\n    /**\n     * Returns the square of the Euclidean distance between this point and that point.\n     * @param that the other point\n     * @return the square of the Euclidean distance between this point and that point\n     */\n    public double distanceSquaredTo(Point2D that) {\n        double dx = this.x - that.x;\n        double dy = this.y - that.y;\n        return dx*dx + dy*dy;\n    }\n\n    /**\n     * Compares two points by y-coordinate, breaking ties by x-coordinate.\n     * Formally, the invoking point (x0, y0) is less than the argument point (x1, y1)\n     * if and only if either {@code y0 < y1} or if {@code y0 == y1} and {@code x0 < x1}.\n     *\n     * @param  that the other point\n     * @return the value {@code 0} if this string is equal to the argument\n     *         string (precisely when {@code equals()} returns {@code true});\n     *         a negative integer if this point is less than the argument\n     *         point; and a positive integer if this point is greater than the\n     *         argument point\n     */\n    public int compareTo(Point2D that) {\n        if (this.y < that.y) return -1;\n        if (this.y > that.y) return +1;\n        if (this.x < that.x) return -1;\n        if (this.x > that.x) return +1;\n        return 0;\n    }\n\n    /**\n     * Compares two points by polar angle (between 0 and 2pi) with respect to this point.\n     *\n     * @return the comparator\n     */\n    public Comparator<Point2D> polarOrder() {\n        return new PolarOrder();\n    }\n\n    /**\n     * Compares two points by atan2() angle (between -pi and pi) with respect to this point.\n     *\n     * @return the comparator\n     */\n    public Comparator<Point2D> atan2Order() {\n        return new Atan2Order();\n    }\n\n    /**\n     * Compares two points by distance to this point.\n     *\n     * @return the comparator\n     */\n    public Comparator<Point2D> distanceToOrder() {\n        return new DistanceToOrder();\n    }\n\n    // compare points according to their x-coordinate\n    private static class XOrder implements Comparator<Point2D> {\n        public int compare(Point2D p, Point2D q) {\n            if (p.x < q.x) return -1;\n            if (p.x > q.x) return +1;\n            return 0;\n        }\n    }\n\n    // compare points according to their y-coordinate\n    private static class YOrder implements Comparator<Point2D> {\n        public int compare(Point2D p, Point2D q) {\n            if (p.y < q.y) return -1;\n            if (p.y > q.y) return +1;\n            return 0;\n        }\n    }\n\n    // compare points according to their polar radius\n    private static class ROrder implements Comparator<Point2D> {\n        public int compare(Point2D p, Point2D q) {\n            double delta = (p.x*p.x + p.y*p.y) - (q.x*q.x + q.y*q.y);\n            if (delta < 0) return -1;\n            if (delta > 0) return +1;\n            return 0;\n        }\n    }\n \n    // compare other points relative to atan2 angle (bewteen -pi/2 and pi/2) they make with this Point\n    private class Atan2Order implements Comparator<Point2D> {\n        public int compare(Point2D q1, Point2D q2) {\n            double angle1 = angleTo(q1);\n            double angle2 = angleTo(q2);\n            if      (angle1 < angle2) return -1;\n            else if (angle1 > angle2) return +1;\n            else                      return  0;\n        }\n    }\n\n    // compare other points relative to polar angle (between 0 and 2pi) they make with this Point\n    private class PolarOrder implements Comparator<Point2D> {\n        public int compare(Point2D q1, Point2D q2) {\n            double dx1 = q1.x - x;\n            double dy1 = q1.y - y;\n            double dx2 = q2.x - x;\n            double dy2 = q2.y - y;\n\n            if      (dy1 >= 0 && dy2 < 0) return -1;    // q1 above; q2 below\n            else if (dy2 >= 0 && dy1 < 0) return +1;    // q1 below; q2 above\n            else if (dy1 == 0 && dy2 == 0) {            // 3-collinear and horizontal\n                if      (dx1 >= 0 && dx2 < 0) return -1;\n                else if (dx2 >= 0 && dx1 < 0) return +1;\n                else                          return  0;\n            }\n            else return -ccw(Point2D.this, q1, q2);     // both above or below\n\n            // Note: ccw() recomputes dx1, dy1, dx2, and dy2\n        }\n    }\n\n    // compare points according to their distance to this point\n    private class DistanceToOrder implements Comparator<Point2D> {\n        public int compare(Point2D p, Point2D q) {\n            double dist1 = distanceSquaredTo(p);\n            double dist2 = distanceSquaredTo(q);\n            if      (dist1 < dist2) return -1;\n            else if (dist1 > dist2) return +1;\n            else                    return  0;\n        }\n    }\n\n\n    /**       \n     * Compares this point to the specified point.\n     *       \n     * @param  other the other point\n     * @return {@code true} if this point equals {@code other};\n     *         {@code false} otherwise\n     */\n    @Override\n    public boolean equals(Object other) {\n        if (other == this) return true;\n        if (other == null) return false;\n        if (other.getClass() != this.getClass()) return false;\n        Point2D that = (Point2D) other;\n        return this.x == that.x && this.y == that.y;\n    }\n\n    /**\n     * Return a string representation of this point.\n     * @return a string representation of this point in the format (x, y)\n     */\n    @Override\n    public String toString() {\n        return \"(\" + x + \", \" + y + \")\";\n    }\n\n    /**\n     * Returns an integer hash code for this point.\n     * @return an integer hash code for this point\n     */\n    @Override\n    public int hashCode() {\n        int hashX = ((Double) x).hashCode();\n        int hashY = ((Double) y).hashCode();\n        return 31*hashX + hashY;\n    }\n\n    /**\n     * Plot this point using standard draw.\n     */\n    public void draw() {\n        StdDraw.point(x, y);\n    }\n\n    /**\n     * Plot a line from this point to that point using standard draw.\n     * @param that the other point\n     */\n    public void drawTo(Point2D that) {\n        StdDraw.line(this.x, this.y, that.x, that.y);\n    }\n\n\n    /**\n     * Unit tests the point data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int x0 = Integer.parseInt(args[0]);\n        int y0 = Integer.parseInt(args[1]);\n        int n = Integer.parseInt(args[2]);\n\n        StdDraw.setCanvasSize(800, 800);\n        StdDraw.setXscale(0, 100);\n        StdDraw.setYscale(0, 100);\n        StdDraw.setPenRadius(0.005);\n        StdDraw.enableDoubleBuffering();\n\n        Point2D[] points = new Point2D[n];\n        for (int i = 0; i < n; i++) {\n            int x = StdRandom.uniform(100);\n            int y = StdRandom.uniform(100);\n            points[i] = new Point2D(x, y);\n            points[i].draw();\n        }\n\n        // draw p = (x0, x1) in red\n        Point2D p = new Point2D(x0, y0);\n        StdDraw.setPenColor(StdDraw.RED);\n        StdDraw.setPenRadius(0.02);\n        p.draw();\n\n\n        // draw line segments from p to each point, one at a time, in polar order\n        StdDraw.setPenRadius();\n        StdDraw.setPenColor(StdDraw.BLUE);\n        Arrays.sort(points, p.polarOrder());\n        for (int i = 0; i < n; i++) {\n            p.drawTo(points[i]);\n            StdDraw.show();\n            StdDraw.pause(100);\n        }\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Queue.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Queue.java\n *  Execution:    java Queue < input.txt\n *  Dependencies: StdIn.java StdOut.java\n *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt  \n *\n *  A generic queue, implemented using a linked list.\n *\n *  % java Queue < tobe.txt \n *  to be or not to be (2 left on queue)\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n/**\n *  The {@code Queue} class represents a first-in-first-out (FIFO)\n *  queue of generic items.\n *  It supports the usual <em>enqueue</em> and <em>dequeue</em>\n *  operations, along with methods for peeking at the first item,\n *  testing if the queue is empty, and iterating through\n *  the items in FIFO order.\n *  <p>\n *  This implementation uses a singly-linked list with a static nested class for\n *  linked-list nodes. See {@link LinkedQueue} for the version from the\n *  textbook that uses a non-static nested class.\n *  The <em>enqueue</em>, <em>dequeue</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>\n *  operations all take constant time in the worst case.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/13stacks\">Section 1.3</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Item> the generic type of an item in this queue\n */\npublic class Queue<Item> implements Iterable<Item> {\n    private Node<Item> first;    // beginning of queue\n    private Node<Item> last;     // end of queue\n    private int n;               // number of elements on queue\n\n    // helper linked list class\n    private static class Node<Item> {\n        private Item item;\n        private Node<Item> next;\n    }\n\n    /**\n     * Initializes an empty queue.\n     */\n    public Queue() {\n        first = null;\n        last  = null;\n        n = 0;\n    }\n\n    /**\n     * Returns true if this queue is empty.\n     *\n     * @return {@code true} if this queue is empty; {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return first == null;\n    }\n\n    /**\n     * Returns the number of items in this queue.\n     *\n     * @return the number of items in this queue\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Returns the item least recently added to this queue.\n     *\n     * @return the item least recently added to this queue\n     * @throws NoSuchElementException if this queue is empty\n     */\n    public Item peek() {\n        if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n        return first.item;\n    }\n\n    /**\n     * Adds the item to this queue.\n     *\n     * @param  item the item to add\n     */\n    public void enqueue(Item item) {\n        Node<Item> oldlast = last;\n        last = new Node<Item>();\n        last.item = item;\n        last.next = null;\n        if (isEmpty()) first = last;\n        else           oldlast.next = last;\n        n++;\n    }\n\n    /**\n     * Removes and returns the item on this queue that was least recently added.\n     *\n     * @return the item on this queue that was least recently added\n     * @throws NoSuchElementException if this queue is empty\n     */\n    public Item dequeue() {\n        if (isEmpty()) throw new NoSuchElementException(\"Queue underflow\");\n        Item item = first.item;\n        first = first.next;\n        n--;\n        if (isEmpty()) last = null;   // to avoid loitering\n        return item;\n    }\n\n    /**\n     * Returns a string representation of this queue.\n     *\n     * @return the sequence of items in FIFO order, separated by spaces\n     */\n    public String toString() {\n        StringBuilder s = new StringBuilder();\n        for (Item item : this) {\n            s.append(item);\n            s.append(' ');\n        }\n        return s.toString();\n    } \n\n    /**\n     * Returns an iterator that iterates over the items in this queue in FIFO order.\n     *\n     * @return an iterator that iterates over the items in this queue in FIFO order\n     */\n    public Iterator<Item> iterator()  {\n        return new ListIterator<Item>(first);  \n    }\n\n    // an iterator, doesn't implement remove() since it's optional\n    private class ListIterator<Item> implements Iterator<Item> {\n        private Node<Item> current;\n\n        public ListIterator(Node<Item> first) {\n            current = first;\n        }\n\n        public boolean hasNext()  { return current != null;                     }\n        public void remove()      { throw new UnsupportedOperationException();  }\n\n        public Item next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            Item item = current.item;\n            current = current.next; \n            return item;\n        }\n    }\n\n\n    /**\n     * Unit tests the {@code Queue} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Queue<String> queue = new Queue<String>();\n        while (!StdIn.isEmpty()) {\n            String item = StdIn.readString();\n            if (!item.equals(\"-\"))\n                queue.enqueue(item);\n            else if (!queue.isEmpty())\n                StdOut.print(queue.dequeue() + \" \");\n        }\n        StdOut.println(\"(\" + queue.size() + \" left on queue)\");\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/SET.java",
    "content": "/******************************************************************************\n *  Compilation:  javac SET.java\n *  Execution:    java SET\n *  Dependencies: StdOut.java\n *  \n *  Set implementation using Java's TreeSet library.\n *  Does not allow duplicates.\n *\n *  % java SET\n *  128.112.136.11\n *  208.216.181.15\n *  null\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.TreeSet;\n\n/**\n *  The {@code SET} class represents an ordered set of comparable keys.\n *  It supports the usual <em>add</em>, <em>contains</em>, and <em>delete</em>\n *  methods. It also provides ordered methods for finding the <em>minimum</em>,\n *  <em>maximum</em>, <em>floor</em>, and <em>ceiling</em> and set methods\n *  for <em>union</em>, <em>intersection</em>, and <em>equality</em>.\n *  <p>\n *  Even though this implementation include the method {@code equals()}, it\n *  does not support the method {@code hashCode()} because sets are mutable.\n *  <p>\n *  This implementation uses a balanced binary search tree. It requires that\n *  the key type implements the {@code Comparable} interface and calls the\n *  {@code compareTo()} and method to compare two keys. It does not call either\n *  {@code equals()} or {@code hashCode()}.\n *  The <em>add</em>, <em>contains</em>, <em>delete</em>, <em>minimum</em>,\n *  <em>maximum</em>, <em>ceiling</em>, and <em>floor</em> methods take\n *  logarithmic time in the worst case.\n *  The <em>size</em>, and <em>is-empty</em> operations take constant time.\n *  Construction takes constant time.\n *  <p>\n *  This implementation uses a balanced binary search tree. It requires that\n *  For additional documentation, see\n *  <a href=\"http://algs4.cs.princeton.edu/35applications\">Section 3.5</a> of\n *  <i>Algorithms in Java, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Key> the generic type of a key in this set\n */\n\npublic class SET<Key extends Comparable<Key>> implements Iterable<Key> {\n    private TreeSet<Key> set;\n\n    /**\n     * Initializes an empty set.\n     */\n    public SET() {\n        set = new TreeSet<Key>();\n    }\n\n    /**\n     * Initializes a new set that is an independent copy of the specified set.\n     *\n     * @param x the set to copy\n     */\n    public SET(SET<Key> x) {\n        set = new TreeSet<Key>(x.set);\n    }\n\n    /**\n     * Adds the key to this set (if it is not already present).\n     *\n     * @param  key the key to add\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public void add(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called add() with a null key\");\n        set.add(key);\n    }\n\n\n    /**\n     * Returns true if this set contains the given key.\n     *\n     * @param  key the key\n     * @return {@code true} if this set contains {@code key};\n     *         {@code false} otherwise\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public boolean contains(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called contains() with a null key\");\n        return set.contains(key);\n    }\n\n    /**\n     * Removes the specified key from this set (if the set contains the specified key).\n     *\n     * @param  key the key\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public void delete(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called delete() with a null key\");\n        set.remove(key);\n    }\n\n    /**\n     * Returns the number of keys in this set.\n     *\n     * @return the number of keys in this set\n     */\n    public int size() {\n        return set.size();\n    }\n\n    /**\n     * Returns true if this set is empty.\n     *\n     * @return {@code true} if this set is empty;\n     *         {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return size() == 0;\n    }\n \n    /**\n     * Returns all of the keys in this set, as an iterator.\n     * To iterate over all of the keys in a set named {@code set}, use the\n     * foreach notation: {@code for (Key key : set)}.\n     *\n     * @return an iterator to all of the keys in this set\n     */\n    public Iterator<Key> iterator() {\n        return set.iterator();\n    }\n\n    /**\n     * Returns the largest key in this set.\n     *\n     * @return the largest key in this set\n     * @throws NoSuchElementException if this set is empty\n     */\n    public Key max() {\n        if (isEmpty()) throw new NoSuchElementException(\"called max() with empty set\");\n        return set.last();\n    }\n\n    /**\n     * Returns the smallest key in this set.\n     *\n     * @return the smallest key in this set\n     * @throws NoSuchElementException if this set is empty\n     */\n    public Key min() {\n        if (isEmpty()) throw new NoSuchElementException(\"called min() with empty set\");\n        return set.first();\n    }\n\n\n    /**\n     * Returns the smallest key in this set greater than or equal to {@code key}.\n     *\n     * @param  key the key\n     * @return the smallest key in this set greater than or equal to {@code key}\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     * @throws NoSuchElementException if there is no such key\n     */\n    public Key ceiling(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called ceiling() with a null key\");\n        Key k = set.ceiling(key);\n        if (k == null) throw new NoSuchElementException(\"all keys are less than \" + key);\n        return k;\n    }\n\n    /**\n     * Returns the largest key in this set less than or equal to {@code key}.\n     *\n     * @param  key the key\n     * @return the largest key in this set table less than or equal to {@code key}\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     * @throws NoSuchElementException if there is no such key\n     */\n    public Key floor(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called floor() with a null key\");\n        Key k = set.floor(key);\n        if (k == null) throw new NoSuchElementException(\"all keys are greater than \" + key);\n        return k;\n    }\n\n    /**\n     * Returns the union of this set and that set.\n     *\n     * @param  that the other set\n     * @return the union of this set and that set\n     * @throws IllegalArgumentException if {@code that} is {@code null}\n     */\n    public SET<Key> union(SET<Key> that) {\n        if (that == null) throw new IllegalArgumentException(\"called union() with a null argument\");\n        SET<Key> c = new SET<Key>();\n        for (Key x : this) {\n            c.add(x);\n        }\n        for (Key x : that) {\n            c.add(x);\n        }\n        return c;\n    }\n\n    /**\n     * Returns the intersection of this set and that set.\n     *\n     * @param  that the other set\n     * @return the intersection of this set and that set\n     * @throws IllegalArgumentException if {@code that} is {@code null}\n     */\n    public SET<Key> intersects(SET<Key> that) {\n        if (that == null) throw new IllegalArgumentException(\"called intersects() with a null argument\");\n        SET<Key> c = new SET<Key>();\n        if (this.size() < that.size()) {\n            for (Key x : this) {\n                if (that.contains(x)) c.add(x);\n            }\n        }\n        else {\n            for (Key x : that) {\n                if (this.contains(x)) c.add(x);\n            }\n        }\n        return c;\n    }\n\n    /**       \n     * Compares this set to the specified set.\n     * <p>\n     * Note that this method declares two empty sets to be equal\n     * even if they are parameterized by different generic types.\n     * This is consistent with the behavior of {@code equals()} \n     * within Java's Collections framework.\n     *       \n     * @param  other the other set\n     * @return {@code true} if this set equals {@code other};\n     *         {@code false} otherwise\n     */\n    @Override\n    public boolean equals(Object other) {\n        if (other == this) return true;\n        if (other == null) return false;\n        if (other.getClass() != this.getClass()) return false;\n        SET that = (SET) other;\n        return this.set.equals(that.set);\n    }\n\n    /**\n     * This operation is not supported because sets are mutable.\n     *\n     * @return does not return a value\n     * @throws UnsupportedOperationException if called\n     */\n    @Override\n    public int hashCode() {\n        throw new UnsupportedOperationException(\"hashCode() is not supported because sets are mutable\");\n    }\n\n    /**\n     * Returns a string representation of this set.\n     *\n     * @return a string representation of this set, enclosed in curly braces,\n     *         with adjacent keys separated by a comma and a space\n     */\n    @Override\n    public String toString() {\n        String s = set.toString();\n        return \"{ \" + s.substring(1, s.length() - 1) + \" }\";\n    }\n\n    /**\n     * Unit tests the {@code SET} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        SET<String> set = new SET<String>();\n        StdOut.println(\"set = \" + set);\n\n        // insert some keys\n        set.add(\"www.cs.princeton.edu\");\n        set.add(\"www.cs.princeton.edu\");    // overwrite old value\n        set.add(\"www.princeton.edu\");\n        set.add(\"www.math.princeton.edu\");\n        set.add(\"www.yale.edu\");\n        set.add(\"www.amazon.com\");\n        set.add(\"www.simpsons.com\");\n        set.add(\"www.stanford.edu\");\n        set.add(\"www.google.com\");\n        set.add(\"www.ibm.com\");\n        set.add(\"www.apple.com\");\n        set.add(\"www.slashdot.com\");\n        set.add(\"www.whitehouse.gov\");\n        set.add(\"www.espn.com\");\n        set.add(\"www.snopes.com\");\n        set.add(\"www.movies.com\");\n        set.add(\"www.cnn.com\");\n        set.add(\"www.iitb.ac.in\");\n\n\n        StdOut.println(set.contains(\"www.cs.princeton.edu\"));\n        StdOut.println(!set.contains(\"www.harvardsucks.com\"));\n        StdOut.println(set.contains(\"www.simpsons.com\"));\n        StdOut.println();\n\n        StdOut.println(\"ceiling(www.simpsonr.com) = \" + set.ceiling(\"www.simpsonr.com\"));\n        StdOut.println(\"ceiling(www.simpsons.com) = \" + set.ceiling(\"www.simpsons.com\"));\n        StdOut.println(\"ceiling(www.simpsont.com) = \" + set.ceiling(\"www.simpsont.com\"));\n        StdOut.println(\"floor(www.simpsonr.com)   = \" + set.floor(\"www.simpsonr.com\"));\n        StdOut.println(\"floor(www.simpsons.com)   = \" + set.floor(\"www.simpsons.com\"));\n        StdOut.println(\"floor(www.simpsont.com)   = \" + set.floor(\"www.simpsont.com\"));\n        StdOut.println();\n\n        StdOut.println(\"set = \" + set);\n        StdOut.println();\n\n        // print out all keys in this set in lexicographic order\n        for (String s : set) {\n            StdOut.println(s);\n        }\n\n        StdOut.println();\n        SET<String> set2 = new SET<String>(set);\n        StdOut.println(set.equals(set2));\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/ST.java",
    "content": "/******************************************************************************\n *  Compilation:  javac ST.java\n *  Execution:    java ST < input.txt\n *  Dependencies: StdIn.java StdOut.java\n *  Data files:   http://algs4.cs.princeton.edu/35applications/tinyST.txt\n *  \n *  Sorted symbol table implementation using a java.util.TreeMap.\n *  Does not allow duplicates.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.TreeMap;\n\n/**\n *  The {@code ST} class represents an ordered symbol table of generic\n *  key-value pairs.\n *  It supports the usual <em>put</em>, <em>get</em>, <em>contains</em>,\n *  <em>delete</em>, <em>size</em>, and <em>is-empty</em> methods.\n *  It also provides ordered methods for finding the <em>minimum</em>,\n *  <em>maximum</em>, <em>floor</em>, and <em>ceiling</em>.\n *  It also provides a <em>keys</em> method for iterating over all of the keys.\n *  A symbol table implements the <em>associative array</em> abstraction:\n *  when associating a value with a key that is already in the symbol table,\n *  the convention is to replace the old value with the new value.\n *  Unlike {@link java.util.Map}, this class uses the convention that\n *  values cannot be {@code null}—setting the\n *  value associated with a key to {@code null} is equivalent to deleting the key\n *  from the symbol table.\n *  <p>\n *  This implementation uses a balanced binary search tree. It requires that\n *  the key type implements the {@code Comparable} interface and calls the\n *  {@code compareTo()} and method to compare two keys. It does not call either\n *  {@code equals()} or {@code hashCode()}.\n *  The <em>put</em>, <em>contains</em>, <em>remove</em>, <em>minimum</em>,\n *  <em>maximum</em>, <em>ceiling</em>, and <em>floor</em> operations each take\n *  logarithmic time in the worst case.\n *  The <em>size</em>, and <em>is-empty</em> operations take constant time.\n *  Construction takes constant time.\n *  <p>\n *  For additional documentation, see <a href=\"http://algs4.cs.princeton.edu/35applications\">Section 3.5</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Key> the generic type of keys in this symbol table\n *  @param <Value> the generic type of values in this symbol table\n */\npublic class ST<Key extends Comparable<Key>, Value> implements Iterable<Key> {\n\n    private TreeMap<Key, Value> st;\n\n    /**\n     * Initializes an empty symbol table.\n     */\n    public ST() {\n        st = new TreeMap<Key, Value>();\n    }\n\n\n    /**\n     * Returns the value associated with the given key in this symbol table.\n     *\n     * @param  key the key\n     * @return the value associated with the given key if the key is in this symbol table;\n     *         {@code null} if the key is not in this symbol table\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public Value get(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called get() with null key\");\n        return st.get(key);\n    }\n\n    /**\n     * Inserts the specified key-value pair into the symbol table, overwriting the old \n     * value with the new value if the symbol table already contains the specified key.\n     * Deletes the specified key (and its associated value) from this symbol table\n     * if the specified value is {@code null}.\n     *\n     * @param  key the key\n     * @param  val the value\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public void put(Key key, Value val) {\n        if (key == null) throw new IllegalArgumentException(\"called put() with null key\");\n        if (val == null) st.remove(key);\n        else             st.put(key, val);\n    }\n\n    /**\n     * Removes the specified key and its associated value from this symbol table     \n     * (if the key is in this symbol table).\n     *\n     * @param  key the key\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public void delete(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called delete() with null key\");\n        st.remove(key);\n    }\n\n    /**\n     * Returns true if this symbol table contain the given key.\n     *\n     * @param  key the key\n     * @return {@code true} if this symbol table contains {@code key} and\n     *         {@code false} otherwise\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public boolean contains(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called contains() with null key\");\n        return st.containsKey(key);\n    }\n\n    /**\n     * Returns the number of key-value pairs in this symbol table.\n     *\n     * @return the number of key-value pairs in this symbol table\n     */\n    public int size() {\n        return st.size();\n    }\n\n    /**\n     * Returns true if this symbol table is empty.\n     *\n     * @return {@code true} if this symbol table is empty and {@code false} otherwise\n     */\n    public boolean isEmpty() {\n        return size() == 0;\n    }\n\n    /**\n     * Returns all keys in this symbol table.\n     * <p>\n     * To iterate over all of the keys in the symbol table named {@code st},\n     * use the foreach notation: {@code for (Key key : st.keys())}.\n     *\n     * @return all keys in this symbol table\n     */\n    public Iterable<Key> keys() {\n        return st.keySet();\n    }\n\n    /**\n     * Returns all of the keys in this symbol table.\n     * To iterate over all of the keys in a symbol table named {@code st}, use the\n     * foreach notation: {@code for (Key key : st)}.\n     * <p>\n     * This method is provided for backward compatibility with the version from\n     * <em>Introduction to Programming in Java: An Interdisciplinary Approach.</em>\n     *\n     * @return     an iterator to all of the keys in this symbol table\n     * @deprecated Replaced by {@link #keys()}.\n     */\n    @Deprecated\n    public Iterator<Key> iterator() {\n        return st.keySet().iterator();\n    }\n\n    /**\n     * Returns the smallest key in this symbol table.\n     *\n     * @return the smallest key in this symbol table\n     * @throws NoSuchElementException if this symbol table is empty\n     */\n    public Key min() {\n        if (isEmpty()) throw new NoSuchElementException(\"called min() with empty symbol table\");\n        return st.firstKey();\n    }\n\n    /**\n     * Returns the largest key in this symbol table.\n     *\n     * @return the largest key in this symbol table\n     * @throws NoSuchElementException if this symbol table is empty\n     */\n    public Key max() {\n        if (isEmpty()) throw new NoSuchElementException(\"called max() with empty symbol table\");\n        return st.lastKey();\n    }\n\n    /**\n     * Returns the smallest key in this symbol table greater than or equal to {@code key}.\n     *\n     * @param  key the key\n     * @return the smallest key in this symbol table greater than or equal to {@code key}\n     * @throws NoSuchElementException if there is no such key\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public Key ceiling(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called ceiling() with null key\");\n        Key k = st.ceilingKey(key);\n        if (k == null) throw new NoSuchElementException(\"all keys are less than \" + key);\n        return k;\n    }\n\n    /**\n     * Returns the largest key in this symbol table less than or equal to {@code key}.\n     *\n     * @param  key the key\n     * @return the largest key in this symbol table less than or equal to {@code key}\n     * @throws NoSuchElementException if there is no such key\n     * @throws IllegalArgumentException if {@code key} is {@code null}\n     */\n    public Key floor(Key key) {\n        if (key == null) throw new IllegalArgumentException(\"called floor() with null key\");\n        Key k = st.floorKey(key);\n        if (k == null) throw new NoSuchElementException(\"all keys are greater than \" + key);\n        return k;\n    }\n\n    /**\n     * Unit tests the {@code ST} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        ST<String, Integer> st = new ST<String, Integer>();\n        for (int i = 0; !StdIn.isEmpty(); i++) {\n            String key = StdIn.readString();\n            st.put(key, i);\n        }\n        for (String s : st.keys())\n            StdOut.println(s + \" \" + st.get(s));\n    }\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/Stack.java",
    "content": "/******************************************************************************\n *  Compilation:  javac Stack.java\n *  Execution:    java Stack < input.txt\n *  Dependencies: StdIn.java StdOut.java\n *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt\n *\n *  A generic stack, implemented using a singly-linked list.\n *  Each stack element is of type Item.\n *\n *  This version uses a static nested class Node (to save 8 bytes per\n *  Node), whereas the version in the textbook uses a non-static nested\n *  class (for simplicity).\n *  \n *  % more tobe.txt \n *  to be or not to - be - - that - - - is\n *\n *  % java Stack < tobe.txt\n *  to be not that or be (2 left on stack)\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\n\n/**\n *  The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items.\n *  It supports the usual <em>push</em> and <em>pop</em> operations, along with methods\n *  for peeking at the top item, testing if the stack is empty, and iterating through\n *  the items in LIFO order.\n *  <p>\n *  This implementation uses a singly-linked list with a static nested class for\n *  linked-list nodes. See {@link LinkedStack} for the version from the\n *  textbook that uses a non-static nested class.\n *  The <em>push</em>, <em>pop</em>, <em>peek</em>, <em>size</em>, and <em>is-empty</em>\n *  operations all take constant time in the worst case.\n *  <p>\n *  For additional documentation,\n *  see <a href=\"http://algs4.cs.princeton.edu/13stacks\">Section 1.3</a> of\n *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n *\n *  @param <Item> the generic type of an item in this stack\n */\npublic class Stack<Item> implements Iterable<Item> {\n    private Node<Item> first;     // top of stack\n    private int n;                // size of the stack\n\n    // helper linked list class\n    private static class Node<Item> {\n        private Item item;\n        private Node<Item> next;\n    }\n\n    /**\n     * Initializes an empty stack.\n     */\n    public Stack() {\n        first = null;\n        n = 0;\n    }\n\n    /**\n     * Returns true if this stack is empty.\n     *\n     * @return true if this stack is empty; false otherwise\n     */\n    public boolean isEmpty() {\n        return first == null;\n    }\n\n    /**\n     * Returns the number of items in this stack.\n     *\n     * @return the number of items in this stack\n     */\n    public int size() {\n        return n;\n    }\n\n    /**\n     * Adds the item to this stack.\n     *\n     * @param  item the item to add\n     */\n    public void push(Item item) {\n        Node<Item> oldfirst = first;\n        first = new Node<Item>();\n        first.item = item;\n        first.next = oldfirst;\n        n++;\n    }\n\n    /**\n     * Removes and returns the item most recently added to this stack.\n     *\n     * @return the item most recently added\n     * @throws NoSuchElementException if this stack is empty\n     */\n    public Item pop() {\n        if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n        Item item = first.item;        // save item to return\n        first = first.next;            // delete first node\n        n--;\n        return item;                   // return the saved item\n    }\n\n\n    /**\n     * Returns (but does not remove) the item most recently added to this stack.\n     *\n     * @return the item most recently added to this stack\n     * @throws NoSuchElementException if this stack is empty\n     */\n    public Item peek() {\n        if (isEmpty()) throw new NoSuchElementException(\"Stack underflow\");\n        return first.item;\n    }\n\n    /**\n     * Returns a string representation of this stack.\n     *\n     * @return the sequence of items in this stack in LIFO order, separated by spaces\n     */\n    public String toString() {\n        StringBuilder s = new StringBuilder();\n        for (Item item : this) {\n            s.append(item);\n            s.append(' ');\n        }\n        return s.toString();\n    }\n       \n\n    /**\n     * Returns an iterator to this stack that iterates through the items in LIFO order.\n     *\n     * @return an iterator to this stack that iterates through the items in LIFO order\n     */\n    public Iterator<Item> iterator() {\n        return new ListIterator<Item>(first);\n    }\n\n    // an iterator, doesn't implement remove() since it's optional\n    private class ListIterator<Item> implements Iterator<Item> {\n        private Node<Item> current;\n\n        public ListIterator(Node<Item> first) {\n            current = first;\n        }\n\n        public boolean hasNext() {\n            return current != null;\n        }\n\n        public void remove() {\n            throw new UnsupportedOperationException();\n        }\n\n        public Item next() {\n            if (!hasNext()) throw new NoSuchElementException();\n            Item item = current.item;\n            current = current.next; \n            return item;\n        }\n    }\n\n\n    /**\n     * Unit tests the {@code Stack} data type.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        Stack<String> stack = new Stack<String>();\n        while (!StdIn.isEmpty()) {\n            String item = StdIn.readString();\n            if (!item.equals(\"-\"))\n                stack.push(item);\n            else if (!stack.isEmpty())\n                StdOut.print(stack.pop() + \" \");\n        }\n        StdOut.println(\"(\" + stack.size() + \" left on stack)\");\n    }\n}\n\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/StdDraw.java",
    "content": "/******************************************************************************\n *  Compilation:  javac StdDraw.java\n *  Execution:    java StdDraw\n *  Dependencies: none\n *\n *  Standard drawing library. This class provides a basic capability for\n *  creating drawings with your programs. It uses a simple graphics model that\n *  allows you to create drawings consisting of points, lines, and curves\n *  in a window on your computer and to save the drawings to a file.\n *\n *  Todo\n *  ----\n *    -  Add support for gradient fill, etc.\n *    -  Fix setCanvasSize() so that it can only be called once.\n *    -  On some systems, drawing a line (or other shape) that extends way\n *       beyond canvas (e.g., to infinity) dimensions does not get drawn.\n *\n *  Remarks\n *  -------\n *    -  don't use AffineTransform for rescaling since it inverts\n *       images and strings\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.awt.BasicStroke;\nimport java.awt.Color;\nimport java.awt.FileDialog;\nimport java.awt.Font;\nimport java.awt.FontMetrics;\nimport java.awt.Graphics2D;\nimport java.awt.Image;\nimport java.awt.MediaTracker;\nimport java.awt.RenderingHints;\nimport java.awt.Toolkit;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.awt.event.MouseMotionListener;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\n\nimport java.awt.geom.Arc2D;\nimport java.awt.geom.Ellipse2D;\nimport java.awt.geom.GeneralPath;\nimport java.awt.geom.Line2D;\nimport java.awt.geom.Rectangle2D;\n\nimport java.awt.image.BufferedImage;\nimport java.awt.image.DirectColorModel;\nimport java.awt.image.WritableRaster;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport java.net.URL;\n\nimport java.util.LinkedList;\nimport java.util.TreeSet;\nimport java.util.NoSuchElementException;\n\nimport javax.imageio.ImageIO;\n\nimport javax.swing.ImageIcon;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuBar;\nimport javax.swing.JMenuItem;\nimport javax.swing.KeyStroke;\n\n/**\n *  The {@code StdDraw} class provides a basic capability for\n *  creating drawings with your programs. It uses a simple graphics model that\n *  allows you to create drawings consisting of points, lines, squares, \n *  circles, and other geometric shapes in a window on your computer and\n *  to save the drawings to a file. Standard drawing also includes\n *  facilities for text, color, pictures, and animation, along with\n *  user interaction via the keyboard and mouse.\n *  <p>\n *  <b>Getting started.</b>\n *  To use standard drawing, you must have {@code StdDraw.class} in your\n *  Java classpath. If you used our autoinstaller, you should be all set.\n *  Otherwise, download\n *  <a href = \"http://introcs.cs.princeton.edu/java/stdlib/StdDraw.java\">StdDraw.java</a>\n *  and put a copy in your working directory.\n *  <p>\n *  Now, type the following short program into your editor:\n *  <pre>\n *   public class TestStdDraw {\n *       public static void main(String[] args) {\n *           StdDraw.setPenRadius(0.05);\n *           StdDraw.setPenColor(StdDraw.BLUE);\n *           StdDraw.point(0.5, 0.5);\n *           StdDraw.setPenColor(StdDraw.MAGENTA);\n *           StdDraw.line(0.2, 0.2, 0.8, 0.2);\n *       }\n *   }\n *  </pre>\n *  If you compile and execute the program, you should see a window\n *  appear with a thick magenta line and a blue point.\n *  This program illustrates the two main types of methods in standard\n *  drawing—methods that draw geometric shapes and methods that\n *  control drawing parameters.\n *  The methods {@code StdDraw.line()} and {@code StdDraw.point()}\n *  draw lines and points; the methods {@code StdDraw.setPenRadius()}\n *  and {@code StdDraw.setPenColor()} control the line thickness and color.\n *  <p>\n *  <b>Points and lines.</b>\n *  You can draw points and line segments with the following methods:\n *  <ul>\n *  <li> {@link #point(double x, double y)}\n *  <li> {@link #line(double x1, double y1, double x2, double y2)}\n *  </ul>\n *  <p>\n *  The <em>x</em>- and <em>y</em>-coordinates must be in the drawing area\n *  (between 0 and 1 and by default) or the points and lines will not be visible.\n *  <p>\n *  <b>Squares, circles, rectangles, and ellipses.</b>\n *  You can draw squares, circles, rectangles, and ellipses using\n *  the following methods:\n *  <ul>\n *  <li> {@link #circle(double x, double y, double radius)}\n *  <li> {@link #ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis)}\n *  <li> {@link #square(double x, double y, double radius)}\n *  <li> {@link #rectangle(double x, double y, double halfWidth, double halfHeight)}\n *  </ul>\n *  <p>\n *  All of these methods take as arguments the location and size of the shape.\n *  The location is always specified by the <em>x</em>- and <em>y</em>-coordinates\n *  of its <em>center</em>.\n *  The size of a circle is specified by its radius and the size of an ellipse is\n *  specified by the lengths of its semi-major and semi-minor axes.\n *  The size of a square or rectangle is specified by its half-width or half-height.\n *  The convention for drawing squares and rectangles is parallel to those for\n *  drawing circles and ellipses, but may be unexpected to the uninitiated.\n *  <p>\n *  The methods above trace outlines of the given shapes. The following methods\n *  draw filled versions:\n *  <ul>\n *  <li> {@link #filledCircle(double x, double y, double radius)}\n *  <li> {@link #filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis)}\n *  <li> {@link #filledSquare(double x, double y, double radius)}\n *  <li> {@link #filledRectangle(double x, double y, double halfWidth, double halfHeight)}\n *  </ul>\n *  <p>\n *  <b>Circular arcs.</b>\n *  You can draw circular arcs with the following method:\n *  <ul>\n *  <li> {@link #arc(double x, double y, double radius, double angle1, double angle2)}\n *  </ul>\n *  <p>\n *  The arc is from the circle centered at (<em>x</em>, <em>y</em>) of the specified radius.\n *  The arc extends from angle1 to angle2. By convention, the angles are\n *  <em>polar</em> (counterclockwise angle from the <em>x</em>-axis)\n *  and represented in degrees. For example, {@code StdDraw.arc(0.0, 0.0, 1.0, 0, 90)}\n *  draws the arc of the unit circle from 3 o'clock (0 degrees) to 12 o'clock (90 degrees).\n *  <p>\n *  <b>Polygons.</b>\n *  You can draw polygons with the following methods:\n *  <ul>\n *  <li> {@link #polygon(double[] x, double[] y)}\n *  <li> {@link #filledPolygon(double[] x, double[] y)}\n *  </ul>\n *  <p>\n *  The points in the polygon are ({@code x[i]}, {@code y[i]}).\n *  For example, the following code fragment draws a filled diamond\n *  with vertices (0.1, 0.2), (0.2, 0.3), (0.3, 0.2), and (0.2, 0.1):\n *  <pre>\n *   double[] x = { 0.1, 0.2, 0.3, 0.2 };\n *   double[] y = { 0.2, 0.3, 0.2, 0.1 };\n *   StdDraw.filledPolygon(x, y);\n *  </pre>\n *  <p>\n *  <b>Pen size.</b>\n *  The pen is circular, so that when you set the pen radius to <em>r</em>\n *  and draw a point, you get a circle of radius <em>r</em>. Also, lines are\n *  of thickness 2<em>r</em> and have rounded ends. The default pen radius\n *  is 0.005 and is not affected by coordinate scaling. This default pen\n *  radius is about 1/200 the width of the default canvas, so that if\n *  you draw 100 points equally spaced along a horizontal or vertical line,\n *  you will be able to see individual circles, but if you draw 200 such\n *  points, the result will look like a line.\n *  <ul>\n *  <li> {@link #setPenRadius(double radius)}\n *  </ul>\n *  <p>\n *  For example, {@code StdDraw.setPenRadius(0.025)} makes\n *  the thickness of the lines and the size of the points to be five times\n *  the 0.005 default.\n *  To draw points with the minimum possible radius (one pixel on typical\n *  displays), set the pen radius to 0.0.\n *  <p>\n *  <b>Pen color.</b>\n *  All geometric shapes (such as points, lines, and circles) are drawn using\n *  the current pen color. By default, it is black.\n *  You can change the pen color with the following methods:\n *  <ul>\n *  <li> {@link #setPenColor(int red, int green, int blue)}\n *  <li> {@link #setPenColor(Color color)}\n *  </ul>\n *  <p>\n *  The first method allows you to specify colors using the RGB color system.\n *  This <a href = \"http://johndyer.name/lab/colorpicker/\">color picker</a>\n *  is a convenient way to find a desired color.\n *  The second method allows you to specify colors using the\n *  {@link Color} data type that is discussed in Chapter 3. Until then,\n *  you can use this method with one of these predefined colors in standard drawing:\n *  {@link #BLACK}, {@link #BLUE}, {@link #CYAN}, {@link #DARK_GRAY}, {@link #GRAY},\n *  {@link #GREEN}, {@link #LIGHT_GRAY}, {@link #MAGENTA}, {@link #ORANGE},\n *  {@link #PINK}, {@link #RED}, {@link #WHITE}, and {@link #YELLOW}.\n *  For example, {@code StdDraw.setPenColor(StdDraw.MAGENTA)} sets the\n *  pen color to magenta.\n *  <p>\n *  <b>Canvas size.</b>\n *  By default, all drawing takes places in a 512-by-512 canvas.\n *  The canvas does not include the window title or window border.\n *  You can change the size of the canvas with the following method:\n *  <ul>\n *  <li> {@link #setCanvasSize(int width, int height)}\n *  </ul>\n *  <p>\n *  This sets the canvas size to be <em>width</em>-by-<em>height</em> pixels.\n *  It also erases the current drawing and resets the coordinate system,\n *  pen radius, pen color, and font back to their default values.\n *  Ordinarly, this method is called once, at the very beginning of a program.\n *  For example, {@code StdDraw.setCanvasSize(800, 800)}\n *  sets the canvas size to be 800-by-800 pixels.\n *  <p>\n *  <b>Canvas scale and coordinate system.</b>\n *  By default, all drawing takes places in the unit square, with (0, 0) at\n *  lower left and (1, 1) at upper right. You can change the default\n *  coordinate system with the following methods:\n *  <ul>\n *  <li> {@link #setXscale(double xmin, double xmax)}\n *  <li> {@link #setYscale(double ymin, double ymax)}\n *  <li> {@link #setScale(double min, double max)}\n *  </ul>\n *  <p>\n *  The arguments are the coordinates of the minimum and maximum \n *  <em>x</em>- or <em>y</em>-coordinates that will appear in the canvas.\n *  For example, if you  wish to use the default coordinate system but\n *  leave a small margin, you can call {@code StdDraw.setScale(-.05, 1.05)}.\n *  <p>\n *  These methods change the coordinate system for subsequent drawing\n *  commands; they do not affect previous drawings.\n *  These methods do not change the canvas size; so, if the <em>x</em>-\n *  and <em>y</em>-scales are different, squares will become rectangles\n *  and circles will become ellipsoidal.\n *  <p>\n *  <b>Text.</b>\n *  You can use the following methods to annotate your drawings with text:\n *  <ul>\n *  <li> {@link #text(double x, double y, String text)}\n *  <li> {@link #text(double x, double y, String text, double degrees)}\n *  <li> {@link #textLeft(double x, double y, String text)}\n *  <li> {@link #textRight(double x, double y, String text)}\n *  </ul>\n *  <p>\n *  The first two methods write the specified text in the current font,\n *  centered at (<em>x</em>, <em>y</em>).\n *  The second method allows you to rotate the text.\n *  The last two methods either left- or right-align the text at (<em>x</em>, <em>y</em>).\n *  <p>\n *  The default font is a Sans Serif font with point size 16.\n *  You can use the following method to change the font:\n *  <ul>\n *  <li> {@link #setFont(Font font)}\n *  </ul>\n *  <p>\n *  You use the {@link Font} data type to specify the font. This allows you to\n *  choose the face, size, and style of the font. For example, the following\n *  code fragment sets the font to Arial Bold, 60 point.\n *  <pre>\n *   Font font = new Font(\"Arial\", Font.BOLD, 60);\n *   StdDraw.setFont(font);\n *   StdDraw.text(0.5, 0.5, \"Hello, World\");\n *  </pre>\n *  <p>\n *  <b>Images.</b>\n *  You can use the following methods to add images to your drawings:\n *  <ul>\n *  <li> {@link #picture(double x, double y, String filename)}\n *  <li> {@link #picture(double x, double y, String filename, double degrees)}\n *  <li> {@link #picture(double x, double y, String filename, double scaledWidth, double scaledHeight)}\n *  <li> {@link #picture(double x, double y, String filename, double scaledWidth, double scaledHeight, double degrees)}\n *  </ul>\n *  <p>\n *  These methods draw the specified image, centered at (<em>x</em>, <em>y</em>).\n *  The supported image formats are JPEG, PNG, and GIF.\n *  The image will display at its native size, independent of the coordinate system.\n *  Optionally, you can rotate the image a specified number of degrees counterclockwise\n *  or rescale it to fit snugly inside a width-by-height bounding box.\n *  <p>\n *  <b>Saving to a file.</b>\n *  You save your image to a file using the <em>File → Save</em> menu option.\n *  You can also save a file programatically using the following method:\n *  <ul>\n *  <li> {@link #save(String filename)}\n *  </ul>\n *  <p>\n *  The supported image formats are JPEG and PNG. The filename must have either the\n *  extension .jpg or .png.\n *  We recommend using PNG for drawing that consist solely of geometric shapes and JPEG \n *  for drawings that contains pictures.\n *  <p>\n *  <b>Clearing the canvas.</b>\n *  To clear the entire drawing canvas, you can use the following methods:\n *  <ul>\n *  <li> {@link #clear()}\n *  <li> {@link #clear(Color color)}\n *  </ul>\n *  <p>\n *  The first method clears the canvas to white; the second method\n *  allows you to specify a color of your choice. For example,\n *  {@code StdDraw.clear(StdDraw.LIGHT_GRAY)} clears the canvas to a shade\n *  of gray.\n *  <p>\n *  <b>Computer animations and double buffering.</b>\n *  Double buffering is one of the most powerful features of standard drawing,\n *  enabling computer animations.\n *  The following methods control the way in which objects are drawn:\n *  <ul>\n *  <li> {@link #enableDoubleBuffering()}\n *  <li> {@link #disableDoubleBuffering()}\n *  <li> {@link #show()}\n *  <li> {@link #pause(int t)}\n *  </ul>\n *  <p>\n *  By default, double buffering is disabled, which means that as soon as you\n *  call a drawing\n *  method—such as {@code point()} or {@code line()}—the\n *  results appear on the screen.\n *  <p>\n *  When double buffering is enabled by calling {@link #enableDoubleBuffering()},\n *  all drawing takes place on the <em>offscreen canvas</em>. The offscreen canvas\n *  is not displayed. Only when you call\n *  {@link #show()} does your drawing get copied from the offscreen canvas to\n *  the onscreen canvas, where it is displayed in the standard drawing window. You \n *  can think of double buffering as collecting all of the lines, points, shapes,\n *  and text that you tell it to draw, and then drawing them all\n *  <em>simultaneously</em>, upon request.\n *  <p>\n *  The most important use of double buffering is to produce computer\n *  animations, creating the illusion of motion by rapidly\n *  displaying static drawings. To produce an animation, repeat\n *  the following four steps:\n *  <ul>\n *  <li> Clear the offscreen canvas.\n *  <li> Draw objects on the offscreen canvas.\n *  <li> Copy the offscreen canvas to the onscreen canvas.\n *  <li> Wait for a short while.\n *  </ul>\n *  <p>\n *  The {@link #clear()}, {@link #show()}, and {@link #pause(int dt)} methods\n *  support the first, third, and fourth of these steps, respectively.\n *  <p>\n *  For example, this code fragment animates two balls moving in a circle.\n *  <pre>\n *   StdDraw.setScale(-2, +2);\n *   StdDraw.enableDoubleBuffering();\n *\n *   for (double t = 0.0; true; t += 0.02) {\n *       double x = Math.sin(t);\n *       double y = Math.cos(t);\n *       StdDraw.clear();\n *       StdDraw.filledCircle(x, y, 0.05);\n *       StdDraw.filledCircle(-x, -y, 0.05);\n *       StdDraw.show();\n *       StdDraw.pause(20);\n *   }\n *  </pre>\n *  <p>\n *  <b>Keyboard and mouse inputs.</b>\n *  Standard drawing has very basic support for keyboard and mouse input.\n *  It is much less powerful than most user interface libraries provide, but also much simpler.\n *  You can use the following methods to intercept mouse events:\n *  <ul>\n *  <li> {@link #mousePressed()}\n *  <li> {@link #mouseX()}\n *  <li> {@link #mouseY()}\n *  </ul>\n *  <p>\n *  The first method tells you whether a mouse button is currently being pressed.\n *  The last two methods tells you the <em>x</em>- and <em>y</em>-coordinates of the mouse's\n *  current position, using the same coordinate system as the canvas (the unit square, by default).\n *  You should use these methods in an animation loop that waits a short while before trying\n *  to poll the mouse for its current state.\n *  You can use the following methods to intercept keyboard events:\n *  <ul>\n *  <li> {@link #hasNextKeyTyped()}\n *  <li> {@link #nextKeyTyped()}\n *  <li> {@link #isKeyPressed(int keycode)}\n *  </ul>\n *  <p>\n *  If the user types lots of keys, they will be saved in a list until you process them.\n *  The first method tells you whether the user has typed a key (that your program has\n *  not yet processed).\n *  The second method returns the next key that the user typed (that your program has\n *  not yet processed) and removes it from the list of saved keystrokes.\n *  The third method tells you whether a key is currently being pressed.\n *  <p>\n *  <b>Accessing control parameters.</b>\n *  You can use the following methods to access the current pen color, pen radius,\n *  and font:\n *  <ul>\n *  <li> {@link #getPenColor()}\n *  <li> {@link #getPenRadius()}\n *  <li> {@link #getFont()}\n *  </ul>\n *  <p>\n *  These methods are useful when you want to temporarily change a\n *  control parameter and reset it back to its original value.\n *  <p>\n *  <b>Corner cases.</b>\n *  To avoid clutter, the API doesn't explicitly refer to arguments that are\n *  null, infinity, or NaN.\n *  <ul>\n *  <li> Any method that is passed a {@code null} argument will throw a\n *       {@link NullPointerException}.\n *  <li> Except as noted in the APIs, drawing an object outside (or partly outside)\n *       the canvas is permitted—however, only the part of the object that\n *       appears inside the canvas will be visible.\n *  <li> Except as noted in the APIs, all methods accept {@link Double#NaN},\n *       {@link Double#POSITIVE_INFINITY}, and {@link Double#NEGATIVE_INFINITY}\n *       as arugments. An object drawn with an <em>x</em>- or <em>y</em>-coordinate\n *       that is NaN will behave as if it is outside the canvas, and will not be visible.\n *  </ul>\n *  <p>\n *  <b>Performance tricks.</b>\n *  Standard drawing is capable of drawing large amounts of data.\n *  Here are a few tricks and tips:\n *  <ul>\n *  <li> Use <em>double buffering</em> for static drawing with a large\n *       number of objects.\n *       That is, call {@link #enableDoubleBuffering()} before\n *       the sequence of drawing commands and call {@link #show()} afterwards.\n *       Incrementally displaying a complex drawing while it is being\n *       created can be intolerably inefficient on many computer systems.\n *  <li> When drawing computer animations, call {@code show()}\n *       only once per frame, not after drawing each individual object.\n *  <li> If you call {@code picture()} multiple times with the same filename,\n *       Java will cache the image, so you do not incur the cost of reading\n *       from a file each time.\n *  </ul>\n *  <p>\n *  <b>Known bugs and issues.</b>\n *  <ul>\n *  <li> The {@code picture()} methods may not draw the portion of the image that is\n *       inside the canvas if the center point (<em>x</em>, <em>y</em>) is outside the\n *       canvas.\n *       This bug appears only on some systems.\n *  <li> Some methods may not draw the portion of the geometric object that is inside the\n *       canvas if the <em>x</em>- or <em>y</em>-coordinates are infinite.\n *       This bug appears only on some systems.\n *  </ul>\n *  <p>\n *  <b>Reference.</b>\n *  For additional documentation,\n *  see <a href=\"http://introcs.cs.princeton.edu/15inout\">Section 1.5</a> of\n *  <em>Introduction to Programming in Java: An Interdisciplinary Approach</em>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class StdDraw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {\n\n    /**\n     *  The color black.\n     */\n    public static final Color BLACK = Color.BLACK;\n\n    /**\n     *  The color blue.\n     */\n    public static final Color BLUE = Color.BLUE;\n\n    /**\n     *  The color cyan.\n     */\n    public static final Color CYAN = Color.CYAN;\n\n    /**\n     *  The color dark gray.\n     */\n    public static final Color DARK_GRAY = Color.DARK_GRAY;\n\n    /**\n     *  The color gray.\n     */\n    public static final Color GRAY = Color.GRAY;\n\n    /**\n     *  The color green.\n     */\n    public static final Color GREEN  = Color.GREEN;\n\n    /**\n     *  The color light gray.\n     */\n    public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;\n\n    /**\n     *  The color magenta.\n     */\n    public static final Color MAGENTA = Color.MAGENTA;\n\n    /**\n     *  The color orange.\n     */\n    public static final Color ORANGE = Color.ORANGE;\n\n    /**\n     *  The color pink.\n     */\n    public static final Color PINK = Color.PINK;\n\n    /**\n     *  The color red.\n     */\n    public static final Color RED = Color.RED;\n\n    /**\n     *  The color white.\n     */\n    public static final Color WHITE = Color.WHITE;\n\n    /**\n     *  The color yellow.\n     */\n    public static final Color YELLOW = Color.YELLOW;\n\n    /**\n     * Shade of blue used in <em>Introduction to Programming in Java</em>.\n     * It is Pantone 300U. The RGB values are approximately (9, 90, 166).\n     */\n    public static final Color BOOK_BLUE = new Color(9, 90, 166);\n\n    /**\n     * Shade of light blue used in <em>Introduction to Programming in Java</em>.\n     * The RGB values are approximately (103, 198, 243).\n     */\n    public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);\n\n    /**\n     * Shade of red used in <em>Algorithms, 4th edition</em>.\n     * It is Pantone 1805U. The RGB values are approximately (150, 35, 31).\n     */\n    public static final Color BOOK_RED = new Color(150, 35, 31);\n\n    // default colors\n    private static final Color DEFAULT_PEN_COLOR   = BLACK;\n    private static final Color DEFAULT_CLEAR_COLOR = WHITE;\n\n    // current pen color\n    private static Color penColor;\n\n    // default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE\n    private static final int DEFAULT_SIZE = 512;\n    private static int width  = DEFAULT_SIZE;\n    private static int height = DEFAULT_SIZE;\n\n    // default pen radius\n    private static final double DEFAULT_PEN_RADIUS = 0.002;\n\n    // current pen radius\n    private static double penRadius;\n\n    // show we draw immediately or wait until next show?\n    private static boolean defer = false;\n\n    // boundary of drawing canvas, 0% border\n    // private static final double BORDER = 0.05;\n    private static final double BORDER = 0.00;\n    private static final double DEFAULT_XMIN = 0.0;\n    private static final double DEFAULT_XMAX = 1.0;\n    private static final double DEFAULT_YMIN = 0.0;\n    private static final double DEFAULT_YMAX = 1.0;\n    private static double xmin, ymin, xmax, ymax;\n\n    // for synchronization\n    private static Object mouseLock = new Object();\n    private static Object keyLock = new Object();\n\n    // default font\n    private static final Font DEFAULT_FONT = new Font(\"SansSerif\", Font.PLAIN, 16);\n\n    // current font\n    private static Font font;\n\n    // double buffered graphics\n    private static BufferedImage offscreenImage, onscreenImage;\n    private static Graphics2D offscreen, onscreen;\n\n    // singleton for callbacks: avoids generation of extra .class files\n    private static StdDraw std = new StdDraw();\n\n    // the frame for drawing to the screen\n    private static JFrame frame;\n\n    // mouse state\n    private static boolean mousePressed = false;\n    private static double mouseX = 0;\n    private static double mouseY = 0;\n\n    // queue of typed key characters\n    private static LinkedList<Character> keysTyped = new LinkedList<Character>();\n\n    // set of key codes currently pressed down\n    private static TreeSet<Integer> keysDown = new TreeSet<Integer>();\n\n    // time in milliseconds (from currentTimeMillis()) when we can draw again\n    // used to control the frame rate\n    private static long nextDraw = -1;  \n\n    // singleton pattern: client can't instantiate\n    private StdDraw() { }\n\n\n    // static initializer\n    static {\n        init();\n    }\n\n    /**\n     * Sets the canvas (drawing area) to be 512-by-512 pixels.\n     * This also erases the current drawing and resets the coordinate system,\n     * pen radius, pen color, and font back to their default values.\n     * Ordinarly, this method is called once, at the very beginning\n     * of a program.\n     */\n    public static void setCanvasSize() {\n        setCanvasSize(DEFAULT_SIZE, DEFAULT_SIZE);\n    }\n\n    /**\n     * Sets the canvas (drawing area) to be <em>width</em>-by-<em>height</em> pixels.\n     * This also erases the current drawing and resets the coordinate system,\n     * pen radius, pen color, and font back to their default values.\n     * Ordinarly, this method is called once, at the very beginning\n     * of a program.\n     *\n     * @param  canvasWidth the width as a number of pixels\n     * @param  canvasHeight the height as a number of pixels\n     * @throws IllegalArgumentException unless both {@code width} and\n     *         {@code height} are positive\n     */\n    public static void setCanvasSize(int canvasWidth, int canvasHeight) {\n        if (canvasWidth <= 0 || canvasHeight <= 0)\n            throw new IllegalArgumentException(\"width and height must be positive\");\n        width = canvasWidth;\n        height = canvasHeight;\n        init();\n    }\n\n    // init\n    private static void init() {\n        if (frame != null) frame.setVisible(false);\n        frame = new JFrame();\n        offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n        onscreenImage  = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n        offscreen = offscreenImage.createGraphics();\n        onscreen  = onscreenImage.createGraphics();\n        setXscale();\n        setYscale();\n        offscreen.setColor(DEFAULT_CLEAR_COLOR);\n        offscreen.fillRect(0, 0, width, height);\n        setPenColor();\n        setPenRadius();\n        setFont();\n        clear();\n\n        // add antialiasing\n        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,\n                                                  RenderingHints.VALUE_ANTIALIAS_ON);\n        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);\n        offscreen.addRenderingHints(hints);\n\n        // frame stuff\n        ImageIcon icon = new ImageIcon(onscreenImage);\n        JLabel draw = new JLabel(icon);\n\n        draw.addMouseListener(std);\n        draw.addMouseMotionListener(std);\n\n        frame.setContentPane(draw);\n        frame.addKeyListener(std);    // JLabel cannot get keyboard focus\n        frame.setResizable(false);\n        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            // closes all windows\n        // frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);      // closes only current window\n        frame.setTitle(\"Standard Draw\");\n        frame.setJMenuBar(createMenuBar());\n        frame.pack();\n        frame.requestFocusInWindow();\n        frame.setVisible(true);\n    }\n\n    // create the menu bar (changed to private)\n    private static JMenuBar createMenuBar() {\n        JMenuBar menuBar = new JMenuBar();\n        JMenu menu = new JMenu(\"File\");\n        menuBar.add(menu);\n        JMenuItem menuItem1 = new JMenuItem(\" Save...   \");\n        menuItem1.addActionListener(std);\n        menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,\n                                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));\n        menu.add(menuItem1);\n        return menuBar;\n    }\n\n\n   /***************************************************************************\n    *  User and screen coordinate systems.\n    ***************************************************************************/\n\n    /**\n     * Sets the <em>x</em>-scale to be the default (between 0.0 and 1.0).\n     */\n    public static void setXscale() {\n        setXscale(DEFAULT_XMIN, DEFAULT_XMAX);\n    }\n\n    /**\n     * Sets the <em>y</em>-scale to be the default (between 0.0 and 1.0).\n     */\n    public static void setYscale() {\n        setYscale(DEFAULT_YMIN, DEFAULT_YMAX);\n    }\n\n    /**\n     * Sets the <em>x</em>-scale and <em>y</em>-scale to be the default\n     * (between 0.0 and 1.0).\n     */\n    public static void setScale() {\n        setXscale();\n        setYscale();\n    }\n\n    /**\n     * Sets the <em>x</em>-scale to the specified range.\n     *\n     * @param  min the minimum value of the <em>x</em>-scale\n     * @param  max the maximum value of the <em>x</em>-scale\n     * @throws IllegalArgumentException if {@code (max == min)}\n     */\n    public static void setXscale(double min, double max) {\n        double size = max - min;\n        if (size == 0.0) throw new IllegalArgumentException(\"the min and max are the same\");\n        synchronized (mouseLock) {\n            xmin = min - BORDER * size;\n            xmax = max + BORDER * size;\n        }\n    }\n\n    /**\n     * Sets the <em>y</em>-scale to the specified range.\n     *\n     * @param  min the minimum value of the <em>y</em>-scale\n     * @param  max the maximum value of the <em>y</em>-scale\n     * @throws IllegalArgumentException if {@code (max == min)}\n     */\n    public static void setYscale(double min, double max) {\n        double size = max - min;\n        if (size == 0.0) throw new IllegalArgumentException(\"the min and max are the same\");\n        synchronized (mouseLock) {\n            ymin = min - BORDER * size;\n            ymax = max + BORDER * size;\n        }\n    }\n\n    /**\n     * Sets both the <em>x</em>-scale and <em>y</em>-scale to the (same) specified range.\n     *\n     * @param  min the minimum value of the <em>x</em>- and <em>y</em>-scales\n     * @param  max the maximum value of the <em>x</em>- and <em>y</em>-scales\n     * @throws IllegalArgumentException if {@code (max == min)}\n     */\n    public static void setScale(double min, double max) {\n        double size = max - min;\n        if (size == 0.0) throw new IllegalArgumentException(\"the min and max are the same\");\n        synchronized (mouseLock) {\n            xmin = min - BORDER * size;\n            xmax = max + BORDER * size;\n            ymin = min - BORDER * size;\n            ymax = max + BORDER * size;\n        }\n    }\n\n    // helper functions that scale from user coordinates to screen coordinates and back\n    private static double  scaleX(double x) { return width  * (x - xmin) / (xmax - xmin); }\n    private static double  scaleY(double y) { return height * (ymax - y) / (ymax - ymin); }\n    private static double factorX(double w) { return w * width  / Math.abs(xmax - xmin);  }\n    private static double factorY(double h) { return h * height / Math.abs(ymax - ymin);  }\n    private static double   userX(double x) { return xmin + x * (xmax - xmin) / width;    }\n    private static double   userY(double y) { return ymax - y * (ymax - ymin) / height;   }\n\n\n    /**\n     * Clears the screen to the default color (white).\n     */\n    public static void clear() {\n        clear(DEFAULT_CLEAR_COLOR);\n    }\n\n    /**\n     * Clears the screen to the specified color.\n     *\n     * @param color the color to make the background\n     */\n    public static void clear(Color color) {\n        offscreen.setColor(color);\n        offscreen.fillRect(0, 0, width, height);\n        offscreen.setColor(penColor);\n        draw();\n    }\n\n    /**\n     * Returns the current pen radius.\n     *\n     * @return the current value of the pen radius\n     */\n    public static double getPenRadius() {\n        return penRadius;\n    }\n\n    /**\n     * Sets the pen size to the default size (0.002).\n     * The pen is circular, so that lines have rounded ends, and when you set the\n     * pen radius and draw a point, you get a circle of the specified radius.\n     * The pen radius is not affected by coordinate scaling.\n     */\n    public static void setPenRadius() {\n        setPenRadius(DEFAULT_PEN_RADIUS);\n    }\n\n    /**\n     * Sets the radius of the pen to the specified size.\n     * The pen is circular, so that lines have rounded ends, and when you set the\n     * pen radius and draw a point, you get a circle of the specified radius.\n     * The pen radius is not affected by coordinate scaling.\n     *\n     * @param  radius the radius of the pen\n     * @throws IllegalArgumentException if {@code radius} is negative\n     */\n    public static void setPenRadius(double radius) {\n        if (!(radius >= 0)) throw new IllegalArgumentException(\"pen radius must be nonnegative\");\n        penRadius = radius;\n        float scaledPenRadius = (float) (radius * DEFAULT_SIZE);\n        BasicStroke stroke = new BasicStroke(scaledPenRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);\n        // BasicStroke stroke = new BasicStroke(scaledPenRadius);\n        offscreen.setStroke(stroke);\n    }\n\n    /**\n     * Returns the current pen color.\n     *\n     * @return the current pen color\n     */\n    public static Color getPenColor() {\n        return penColor;\n    }\n\n    /**\n     * Set the pen color to the default color (black).\n     */\n    public static void setPenColor() {\n        setPenColor(DEFAULT_PEN_COLOR);\n    }\n\n    /**\n     * Sets the pen color to the specified color.\n     * <p>\n     * The predefined pen colors are\n     * {@code StdDraw.BLACK}, {@code StdDraw.BLUE}, {@code StdDraw.CYAN},\n     * {@code StdDraw.DARK_GRAY}, {@code StdDraw.GRAY}, {@code StdDraw.GREEN},\n     * {@code StdDraw.LIGHT_GRAY}, {@code StdDraw.MAGENTA}, {@code StdDraw.ORANGE},\n     * {@code StdDraw.PINK}, {@code StdDraw.RED}, {@code StdDraw.WHITE}, and\n     * {@code StdDraw.YELLOW}.\n     *\n     * @param color the color to make the pen\n     */\n    public static void setPenColor(Color color) {\n        if (color == null) throw new NullPointerException();\n        penColor = color;\n        offscreen.setColor(penColor);\n    }\n\n    /**\n     * Sets the pen color to the specified RGB color.\n     *\n     * @param  red the amount of red (between 0 and 255)\n     * @param  green the amount of green (between 0 and 255)\n     * @param  blue the amount of blue (between 0 and 255)\n     * @throws IllegalArgumentException if {@code red}, {@code green},\n     *         or {@code blue} is outside its prescribed range\n     */\n    public static void setPenColor(int red, int green, int blue) {\n        if (red   < 0 || red   >= 256) throw new IllegalArgumentException(\"amount of red must be between 0 and 255\");\n        if (green < 0 || green >= 256) throw new IllegalArgumentException(\"amount of green must be between 0 and 255\");\n        if (blue  < 0 || blue  >= 256) throw new IllegalArgumentException(\"amount of blue must be between 0 and 255\");\n        setPenColor(new Color(red, green, blue));\n    }\n\n    /**\n     * Returns the current font.\n     *\n     * @return the current font\n     */\n    public static Font getFont() {\n        return font;\n    }\n\n    /**\n     * Sets the font to the default font (sans serif, 16 point).\n     */\n    public static void setFont() {\n        setFont(DEFAULT_FONT);\n    }\n\n    /**\n     * Sets the font to the specified value.\n     *\n     * @param font the font\n     */\n    public static void setFont(Font font) {\n        if (font == null) throw new NullPointerException();\n        StdDraw.font = font;\n    }\n\n\n   /***************************************************************************\n    *  Drawing geometric shapes.\n    ***************************************************************************/\n\n    /**\n     * Draws a line segment between (<em>x</em><sub>0</sub>, <em>y</em><sub>0</sub>) and\n     * (<em>x</em><sub>1</sub>, <em>y</em><sub>1</sub>).\n     *\n     * @param  x0 the <em>x</em>-coordinate of one endpoint\n     * @param  y0 the <em>y</em>-coordinate of one endpoint\n     * @param  x1 the <em>x</em>-coordinate of the other endpoint\n     * @param  y1 the <em>y</em>-coordinate of the other endpoint\n     */\n    public static void line(double x0, double y0, double x1, double y1) {\n        offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));\n        draw();\n    }\n\n    /**\n     * Draws one pixel at (<em>x</em>, <em>y</em>).\n     * This method is private because pixels depend on the display.\n     * To achieve the same effect, set the pen radius to 0 and call {@code point()}.\n     *\n     * @param  x the <em>x</em>-coordinate of the pixel\n     * @param  y the <em>y</em>-coordinate of the pixel\n     */\n    private static void pixel(double x, double y) {\n        offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);\n    }\n\n    /**\n     * Draws a point centered at (<em>x</em>, <em>y</em>).\n     * The point is a filled circle whose radius is equal to the pen radius.\n     * To draw a single-pixel point, first set the pen radius to 0.\n     *\n     * @param x the <em>x</em>-coordinate of the point\n     * @param y the <em>y</em>-coordinate of the point\n     */\n    public static void point(double x, double y) {\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double r = penRadius;\n        float scaledPenRadius = (float) (r * DEFAULT_SIZE);\n\n        // double ws = factorX(2*r);\n        // double hs = factorY(2*r);\n        // if (ws <= 1 && hs <= 1) pixel(x, y);\n        if (scaledPenRadius <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - scaledPenRadius/2, ys - scaledPenRadius/2,\n                                                 scaledPenRadius, scaledPenRadius));\n        draw();\n    }\n\n    /**\n     * Draws a circle of the specified radius, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the circle\n     * @param  y the <em>y</em>-coordinate of the center of the circle\n     * @param  radius the radius of the circle\n     * @throws IllegalArgumentException if {@code radius} is negative\n     */\n    public static void circle(double x, double y, double radius) {\n        if (!(radius >= 0)) throw new IllegalArgumentException(\"radius must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*radius);\n        double hs = factorY(2*radius);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled circle of the specified radius, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the circle\n     * @param  y the <em>y</em>-coordinate of the center of the circle\n     * @param  radius the radius of the circle\n     * @throws IllegalArgumentException if {@code radius} is negative\n     */\n    public static void filledCircle(double x, double y, double radius) {\n        if (!(radius >= 0)) throw new IllegalArgumentException(\"radius must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*radius);\n        double hs = factorY(2*radius);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws an ellipse with the specified semimajor and semiminor axes,\n     * centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the ellipse\n     * @param  y the <em>y</em>-coordinate of the center of the ellipse\n     * @param  semiMajorAxis is the semimajor axis of the ellipse\n     * @param  semiMinorAxis is the semiminor axis of the ellipse\n     * @throws IllegalArgumentException if either {@code semiMajorAxis}\n     *         or {@code semiMinorAxis} is negative\n     */\n    public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {\n        if (!(semiMajorAxis >= 0)) throw new IllegalArgumentException(\"ellipse semimajor axis must be nonnegative\");\n        if (!(semiMinorAxis >= 0)) throw new IllegalArgumentException(\"ellipse semiminor axis must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*semiMajorAxis);\n        double hs = factorY(2*semiMinorAxis);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws an ellipse with the specified semimajor and semiminor axes,\n     * centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the ellipse\n     * @param  y the <em>y</em>-coordinate of the center of the ellipse\n     * @param  semiMajorAxis is the semimajor axis of the ellipse\n     * @param  semiMinorAxis is the semiminor axis of the ellipse\n     * @throws IllegalArgumentException if either {@code semiMajorAxis}\n     *         or {@code semiMinorAxis} is negative\n     */\n    public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {\n        if (!(semiMajorAxis >= 0)) throw new IllegalArgumentException(\"ellipse semimajor axis must be nonnegative\");\n        if (!(semiMinorAxis >= 0)) throw new IllegalArgumentException(\"ellipse semiminor axis must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*semiMajorAxis);\n        double hs = factorY(2*semiMinorAxis);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws a circular arc of the specified radius,\n     * centered at (<em>x</em>, <em>y</em>), from angle1 to angle2 (in degrees).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the circle\n     * @param  y the <em>y</em>-coordinate of the center of the circle\n     * @param  radius the radius of the circle\n     * @param  angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.\n     * @param  angle2 the angle at the end of the arc. For example, if\n     *         you want a 90 degree arc, then angle2 should be angle1 + 90.\n     * @throws IllegalArgumentException if {@code radius} is negative\n     */\n    public static void arc(double x, double y, double radius, double angle1, double angle2) {\n        if (radius < 0) throw new IllegalArgumentException(\"arc radius must be nonnegative\");\n        while (angle2 < angle1) angle2 += 360;\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*radius);\n        double hs = factorY(2*radius);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));\n        draw();\n    }\n\n    /**\n     * Draws a square of side length 2r, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the square\n     * @param  y the <em>y</em>-coordinate of the center of the square\n     * @param  halfLength one half the length of any side of the square\n     * @throws IllegalArgumentException if {@code halfLength} is negative\n     */\n    public static void square(double x, double y, double halfLength) {\n        if (!(halfLength >= 0)) throw new IllegalArgumentException(\"half length must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfLength);\n        double hs = factorY(2*halfLength);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled square of the specified size, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the square\n     * @param  y the <em>y</em>-coordinate of the center of the square\n     * @param  halfLength one half the length of any side of the square\n     * @throws IllegalArgumentException if {@code halfLength} is negative\n     */\n    public static void filledSquare(double x, double y, double halfLength) {\n        if (!(halfLength >= 0)) throw new IllegalArgumentException(\"half length must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfLength);\n        double hs = factorY(2*halfLength);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws a rectangle of the specified size, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the rectangle\n     * @param  y the <em>y</em>-coordinate of the center of the rectangle\n     * @param  halfWidth one half the width of the rectangle\n     * @param  halfHeight one half the height of the rectangle\n     * @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative\n     */\n    public static void rectangle(double x, double y, double halfWidth, double halfHeight) {\n        if (!(halfWidth  >= 0)) throw new IllegalArgumentException(\"half width must be nonnegative\");\n        if (!(halfHeight >= 0)) throw new IllegalArgumentException(\"half height must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfWidth);\n        double hs = factorY(2*halfHeight);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n    /**\n     * Draws a filled rectangle of the specified size, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the center of the rectangle\n     * @param  y the <em>y</em>-coordinate of the center of the rectangle\n     * @param  halfWidth one half the width of the rectangle\n     * @param  halfHeight one half the height of the rectangle\n     * @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative\n     */\n    public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) {\n        if (!(halfWidth  >= 0)) throw new IllegalArgumentException(\"half width must be nonnegative\");\n        if (!(halfHeight >= 0)) throw new IllegalArgumentException(\"half height must be nonnegative\");\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(2*halfWidth);\n        double hs = factorY(2*halfHeight);\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));\n        draw();\n    }\n\n\n    /**\n     * Draws a polygon with the vertices \n     * (<em>x</em><sub>0</sub>, <em>y</em><sub>0</sub>),\n     * (<em>x</em><sub>1</sub>, <em>y</em><sub>1</sub>), ...,\n     * (<em>x</em><sub><em>n</em>&minus;1</sub>, <em>y</em><sub><em>n</em>&minus;1</sub>).\n     *\n     * @param  x an array of all the <em>x</em>-coordinates of the polygon\n     * @param  y an array of all the <em>y</em>-coordinates of the polygon\n     * @throws IllegalArgumentException unless {@code x[]} and {@code y[]}\n     *         are of the same length\n     */\n    public static void polygon(double[] x, double[] y) {\n        if (x == null) throw new NullPointerException();\n        if (y == null) throw new NullPointerException();\n        int n1 = x.length;\n        int n2 = y.length;\n        if (n1 != n2) throw new IllegalArgumentException(\"arrays must be of the same length\");\n        int n = n1;\n        GeneralPath path = new GeneralPath();\n        path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));\n        for (int i = 0; i < n; i++)\n            path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));\n        path.closePath();\n        offscreen.draw(path);\n        draw();\n    }\n\n    /**\n     * Draws a polygon with the vertices \n     * (<em>x</em><sub>0</sub>, <em>y</em><sub>0</sub>),\n     * (<em>x</em><sub>1</sub>, <em>y</em><sub>1</sub>), ...,\n     * (<em>x</em><sub><em>n</em>&minus;1</sub>, <em>y</em><sub><em>n</em>&minus;1</sub>).\n     *\n     * @param  x an array of all the <em>x</em>-coordinates of the polygon\n     * @param  y an array of all the <em>y</em>-coordinates of the polygon\n     * @throws IllegalArgumentException unless {@code x[]} and {@code y[]}\n     *         are of the same length\n     */\n    public static void filledPolygon(double[] x, double[] y) {\n        if (x == null) throw new NullPointerException();\n        if (y == null) throw new NullPointerException();\n        int n1 = x.length;\n        int n2 = y.length;\n        if (n1 != n2) throw new IllegalArgumentException(\"arrays must be of the same length\");\n        int n = n1;\n        GeneralPath path = new GeneralPath();\n        path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));\n        for (int i = 0; i < n; i++)\n            path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));\n        path.closePath();\n        offscreen.fill(path);\n        draw();\n    }\n\n\n   /***************************************************************************\n    *  Drawing images.\n    ***************************************************************************/\n    // get an image from the given filename\n    private static Image getImage(String filename) {\n        if (filename == null) throw new NullPointerException();\n\n        // to read from file\n        ImageIcon icon = new ImageIcon(filename);\n\n        // try to read from URL\n        if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {\n            try {\n                URL url = new URL(filename);\n                icon = new ImageIcon(url);\n            }\n            catch (Exception e) {\n                /* not a url */\n            }\n        }\n\n        // in case file is inside a .jar (classpath relative to StdDraw)\n        if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {\n            URL url = StdDraw.class.getResource(filename);\n            if (url != null)\n                icon = new ImageIcon(url);\n        }\n\n        // in case file is inside a .jar (classpath relative to root of jar)\n        if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {\n            URL url = StdDraw.class.getResource(\"/\" + filename);\n            if (url == null) throw new IllegalArgumentException(\"image \" + filename + \" not found\");\n            icon = new ImageIcon(url);\n        }\n\n        return icon.getImage();\n    }\n\n   /***************************************************************************\n    * [Summer 2016] Should we update to use ImageIO instead of ImageIcon()?\n    *               Seems to have some issues loading images on some systems\n    *               and slows things down on other systems.\n    *               especially if you don't call ImageIO.setUseCache(false)\n    *               One advantage is that it returns a BufferedImage.\n    ***************************************************************************/\n/*\n    private static BufferedImage getImage(String filename) {\n        if (filename == null) throw new NullPointerException();\n\n        // from a file or URL\n        try {\n            URL url = new URL(filename);\n            BufferedImage image = ImageIO.read(url);\n            return image;\n        } \n        catch (IOException e) {\n            // ignore\n        }\n\n        // in case file is inside a .jar (classpath relative to StdDraw)\n        try {\n            URL url = StdDraw.class.getResource(filename);\n            BufferedImage image = ImageIO.read(url);\n            return image;\n        } \n        catch (IOException e) {\n            // ignore\n        }\n\n        // in case file is inside a .jar (classpath relative to root of jar)\n        try {\n            URL url = StdDraw.class.getResource(\"/\" + filename);\n            BufferedImage image = ImageIO.read(url);\n            return image;\n        } \n        catch (IOException e) {\n            // ignore\n        }\n        throw new IllegalArgumentException(\"image \" + filename + \" not found\");\n    }\n*/\n    /**\n     * Draws the specified image centered at (<em>x</em>, <em>y</em>).\n     * The supported image formats are JPEG, PNG, and GIF.\n     * As an optimization, the picture is cached, so there is no performance\n     * penalty for redrawing the same image multiple times (e.g., in an animation).\n     * However, if you change the picture file after drawing it, subsequent\n     * calls will draw the original picture.\n     *\n     * @param  x the center <em>x</em>-coordinate of the image\n     * @param  y the center <em>y</em>-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @throws IllegalArgumentException if the image filename is invalid\n     */\n    public static void picture(double x, double y, String filename) {\n        // BufferedImage image = getImage(filename);\n        Image image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        // int ws = image.getWidth();    // can call only if image is a BufferedImage\n        // int hs = image.getHeight();\n        int ws = image.getWidth(null);\n        int hs = image.getHeight(null);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);\n        draw();\n    }\n\n    /**\n     * Draws the specified image centered at (<em>x</em>, <em>y</em>),\n     * rotated given number of degrees.\n     * The supported image formats are JPEG, PNG, and GIF.\n     *\n     * @param  x the center <em>x</em>-coordinate of the image\n     * @param  y the center <em>y</em>-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  degrees is the number of degrees to rotate counterclockwise\n     * @throws IllegalArgumentException if the image filename is invalid\n     */\n    public static void picture(double x, double y, String filename, double degrees) {\n        // BufferedImage image = getImage(filename);\n        Image image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        // int ws = image.getWidth();    // can call only if image is a BufferedImage\n        // int hs = image.getHeight();\n        int ws = image.getWidth(null);\n        int hs = image.getHeight(null);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n\n        draw();\n    }\n\n    /**\n     * Draws the specified image centered at (<em>x</em>, <em>y</em>),\n     * rescaled to the specified bounding box.\n     * The supported image formats are JPEG, PNG, and GIF.\n     *\n     * @param  x the center <em>x</em>-coordinate of the image\n     * @param  y the center <em>y</em>-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  scaledWidth the width of the scaled image (in screen coordinates)\n     * @param  scaledHeight the height of the scaled image (in screen coordinates)\n     * @throws IllegalArgumentException if either {@code scaledWidth}\n     *         or {@code scaledHeight} is negative\n     * @throws IllegalArgumentException if the image filename is invalid\n     */\n    public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight) {\n        Image image = getImage(filename);\n        if (scaledWidth  < 0) throw new IllegalArgumentException(\"width  is negative: \" + scaledWidth);\n        if (scaledHeight < 0) throw new IllegalArgumentException(\"height is negative: \" + scaledHeight);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(scaledWidth);\n        double hs = factorY(scaledHeight);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n        else {\n            offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),\n                                       (int) Math.round(ys - hs/2.0),\n                                       (int) Math.round(ws),\n                                       (int) Math.round(hs), null);\n        }\n        draw();\n    }\n\n\n    /**\n     * Draws the specified image centered at (<em>x</em>, <em>y</em>), rotated\n     * given number of degrees, and rescaled to the specified bounding box.\n     * The supported image formats are JPEG, PNG, and GIF.\n     *\n     * @param  x the center <em>x</em>-coordinate of the image\n     * @param  y the center <em>y</em>-coordinate of the image\n     * @param  filename the name of the image/picture, e.g., \"ball.gif\"\n     * @param  scaledWidth the width of the scaled image (in screen coordinates)\n     * @param  scaledHeight the height of the scaled image (in screen coordinates)\n     * @param  degrees is the number of degrees to rotate counterclockwise\n     * @throws IllegalArgumentException if either {@code scaledWidth}\n     *         or {@code scaledHeight} is negative\n     * @throws IllegalArgumentException if the image filename is invalid\n     */\n    public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight, double degrees) {\n        if (scaledWidth < 0) throw new IllegalArgumentException(\"width is negative: \" + scaledWidth);\n        if (scaledHeight < 0) throw new IllegalArgumentException(\"height is negative: \" + scaledHeight);\n        Image image = getImage(filename);\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        double ws = factorX(scaledWidth);\n        double hs = factorY(scaledHeight);\n        if (ws < 0 || hs < 0) throw new IllegalArgumentException(\"image \" + filename + \" is corrupt\");\n        if (ws <= 1 && hs <= 1) pixel(x, y);\n\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),\n                                   (int) Math.round(ys - hs/2.0),\n                                   (int) Math.round(ws),\n                                   (int) Math.round(hs), null);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n\n        draw();\n    }\n\n   /***************************************************************************\n    *  Drawing text.\n    ***************************************************************************/\n\n    /**\n     * Write the given text string in the current font, centered at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the center <em>x</em>-coordinate of the text\n     * @param  y the center <em>y</em>-coordinate of the text\n     * @param  text the text to write\n     */\n    public static void text(double x, double y, String text) {\n        if (text == null) throw new NullPointerException();\n        offscreen.setFont(font);\n        FontMetrics metrics = offscreen.getFontMetrics();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int ws = metrics.stringWidth(text);\n        int hs = metrics.getDescent();\n        offscreen.drawString(text, (float) (xs - ws/2.0), (float) (ys + hs));\n        draw();\n    }\n\n    /**\n     * Write the given text string in the current font, centered at (<em>x</em>, <em>y</em>) and\n     * rotated by the specified number of degrees.\n     * @param  x the center <em>x</em>-coordinate of the text\n     * @param  y the center <em>y</em>-coordinate of the text\n     * @param  text the text to write\n     * @param  degrees is the number of degrees to rotate counterclockwise\n     */\n    public static void text(double x, double y, String text, double degrees) {\n        if (text == null) throw new NullPointerException();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        offscreen.rotate(Math.toRadians(-degrees), xs, ys);\n        text(x, y, text);\n        offscreen.rotate(Math.toRadians(+degrees), xs, ys);\n    }\n\n\n    /**\n     * Write the given text string in the current font, left-aligned at (<em>x</em>, <em>y</em>).\n     * @param  x the <em>x</em>-coordinate of the text\n     * @param  y the <em>y</em>-coordinate of the text\n     * @param  text the text\n     */\n    public static void textLeft(double x, double y, String text) {\n        if (text == null) throw new NullPointerException();\n        offscreen.setFont(font);\n        FontMetrics metrics = offscreen.getFontMetrics();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int hs = metrics.getDescent();\n        offscreen.drawString(text, (float) xs, (float) (ys + hs));\n        draw();\n    }\n\n    /**\n     * Write the given text string in the current font, right-aligned at (<em>x</em>, <em>y</em>).\n     *\n     * @param  x the <em>x</em>-coordinate of the text\n     * @param  y the <em>y</em>-coordinate of the text\n     * @param  text the text to write\n     */\n    public static void textRight(double x, double y, String text) {\n        if (text == null) throw new NullPointerException();\n        offscreen.setFont(font);\n        FontMetrics metrics = offscreen.getFontMetrics();\n        double xs = scaleX(x);\n        double ys = scaleY(y);\n        int ws = metrics.stringWidth(text);\n        int hs = metrics.getDescent();\n        offscreen.drawString(text, (float) (xs - ws), (float) (ys + hs));\n        draw();\n    }\n\n\n\n    /**\n     * Copies the offscreen buffer to the onscreen buffer, pauses for t milliseconds\n     * and enables double buffering.\n     * @param t number of milliseconds\n     * @deprecated replaced by {@link #enableDoubleBuffering}, {@link #show()}, and {@link #pause}\n     */\n    @Deprecated\n    public static void show(int t) {\n        // sleep until the next time we're allowed to draw\n        long millis = System.currentTimeMillis();\n        if (millis < nextDraw) {\n            try {\n                Thread.sleep(nextDraw - millis);\n            }\n            catch (InterruptedException e) {\n                System.out.println(\"Error sleeping\");\n            }\n            millis = nextDraw;\n        }\n\n        show();\n        enableDoubleBuffering();\n\n        // when are we allowed to draw again\n        nextDraw = millis + t;\n    }\n\n    /**\n     * Pause for t milliseconds. This method is intended to support computer animations.\n     * @param t number of milliseconds\n     */\n    public static void pause(int t) {\n        // sleep until the next time we're allowed to draw\n        long millis = System.currentTimeMillis();\n        if (millis < nextDraw) {\n            try {\n                Thread.sleep(nextDraw - millis);\n            }\n            catch (InterruptedException e) {\n                System.out.println(\"Error sleeping\");\n            }\n            millis = nextDraw;\n        }\n\n        // when are we allowed to draw again\n        nextDraw = millis + t;\n    }\n\n    /**\n     * Copies offscreen buffer to onscreen buffer. There is no reason to call\n     * this method unless double buffering is enabled.\n     */\n    public static void show() {\n        onscreen.drawImage(offscreenImage, 0, 0, null);\n        frame.repaint();\n    }\n\n    // draw onscreen if defer is false\n    private static void draw() {\n        if (!defer) show();\n    }\n\n    /**\n     * Enable double buffering. All subsequent calls to \n     * drawing methods such as {@code line()}, {@code circle()},\n     * and {@code square()} will be deffered until the next call\n     * to show(). Useful for animations.\n     */\n    public static void enableDoubleBuffering() {\n        defer = true;\n    }\n\n    /**\n     * Disable double buffering. All subsequent calls to \n     * drawing methods such as {@code line()}, {@code circle()},\n     * and {@code square()} will be displayed on screen when called.\n     * This is the default.\n     */\n    public static void disableDoubleBuffering() {\n        defer = false;\n    }\n\n\n   /***************************************************************************\n    *  Save drawing to a file.\n    ***************************************************************************/\n\n    /**\n     * Saves the drawing to using the specified filename.\n     * The supported image formats are JPEG and PNG;\n     * the filename suffix must be {@code .jpg} or {@code .png}.\n     *\n     * @param  filename the name of the file with one of the required suffixes\n     */\n    public static void save(String filename) {\n        if (filename == null) throw new NullPointerException();\n        File file = new File(filename);\n        String suffix = filename.substring(filename.lastIndexOf('.') + 1);\n\n        // png files\n        if (suffix.toLowerCase().equals(\"png\")) {\n            try {\n                ImageIO.write(onscreenImage, suffix, file);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        // need to change from ARGB to RGB for JPEG\n        // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727\n        else if (suffix.toLowerCase().equals(\"jpg\")) {\n            WritableRaster raster = onscreenImage.getRaster();\n            WritableRaster newRaster;\n            newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});\n            DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();\n            DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),\n                                                          cm.getRedMask(),\n                                                          cm.getGreenMask(),\n                                                          cm.getBlueMask());\n            BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false,  null);\n            try {\n                ImageIO.write(rgbBuffer, suffix, file);\n            }\n            catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n\n        else {\n            System.out.println(\"Invalid image file type: \" + suffix);\n        }\n    }\n\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void actionPerformed(ActionEvent e) {\n        FileDialog chooser = new FileDialog(StdDraw.frame, \"Use a .png or .jpg extension\", FileDialog.SAVE);\n        chooser.setVisible(true);\n        String filename = chooser.getFile();\n        if (filename != null) {\n            StdDraw.save(chooser.getDirectory() + File.separator + chooser.getFile());\n        }\n    }\n\n\n   /***************************************************************************\n    *  Mouse interactions.\n    ***************************************************************************/\n\n    /**\n     * Returns true if the mouse is being pressed.\n     *\n     * @return {@code true} if the mouse is being pressed; {@code false} otherwise\n     */\n    public static boolean mousePressed() {\n        synchronized (mouseLock) {\n            return mousePressed;\n        }\n    }\n\n    /**\n     * Returns the <em>x</em>-coordinate of the mouse.\n     *\n     * @return the <em>x</em>-coordinate of the mouse\n     */\n    public static double mouseX() {\n        synchronized (mouseLock) {\n            return mouseX;\n        }\n    }\n\n    /**\n     * Returns the <em>y</em>-coordinate of the mouse.\n     *\n     * @return <em>y</em>-coordinate of the mouse\n     */\n    public static double mouseY() {\n        synchronized (mouseLock) {\n            return mouseY;\n        }\n    }\n\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseClicked(MouseEvent e) { }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseEntered(MouseEvent e) { }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseExited(MouseEvent e) { }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mousePressed(MouseEvent e) {\n        synchronized (mouseLock) {\n            mouseX = StdDraw.userX(e.getX());\n            mouseY = StdDraw.userY(e.getY());\n            mousePressed = true;\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseReleased(MouseEvent e) {\n        synchronized (mouseLock) {\n            mousePressed = false;\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseDragged(MouseEvent e)  {\n        synchronized (mouseLock) {\n            mouseX = StdDraw.userX(e.getX());\n            mouseY = StdDraw.userY(e.getY());\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void mouseMoved(MouseEvent e) {\n        synchronized (mouseLock) {\n            mouseX = StdDraw.userX(e.getX());\n            mouseY = StdDraw.userY(e.getY());\n        }\n    }\n\n\n   /***************************************************************************\n    *  Keyboard interactions.\n    ***************************************************************************/\n\n    /**\n     * Returns true if the user has typed a key (that has not yet been processed).\n     *\n     * @return {@code true} if the user has typed a key (that has not yet been processed\n     *         by {@link #nextKeyTyped()}; {@code false} otherwise\n     */\n    public static boolean hasNextKeyTyped() {\n        synchronized (keyLock) {\n            return !keysTyped.isEmpty();\n        }\n    }\n\n    /**\n     * Returns the next key that was typed by the user (that your program has not already processed).\n     * This method should be preceded by a call to {@link #hasNextKeyTyped()} to ensure\n     * that there is a next key to process.\n     * This method returns a Unicode character corresponding to the key\n     * typed (such as {@code 'a'} or {@code 'A'}).\n     * It cannot identify action keys (such as F1 and arrow keys)\n     * or modifier keys (such as control).\n     *\n     * @return the next key typed by the user (that your program has not already processed).\n     * @throws NoSuchElementException if there is no remaining key\n     */\n    public static char nextKeyTyped() {\n        synchronized (keyLock) {\n            if (keysTyped.isEmpty()) {\n                throw new NoSuchElementException(\"your program has already processed all keystrokes\");\n            }\n            return keysTyped.removeLast();\n        }\n    }\n\n    /**\n     * Returns true if the given key is being pressed.\n     * <p>\n     * This method takes the keycode (corresponding to a physical key)\n    *  as an argument. It can handle action keys\n     * (such as F1 and arrow keys) and modifier keys (such as shift and control).\n     * See {@link KeyEvent} for a description of key codes.\n     *\n     * @param  keycode the key to check if it is being pressed\n     * @return {@code true} if {@code keycode} is currently being pressed;\n     *         {@code false} otherwise\n     */\n    public static boolean isKeyPressed(int keycode) {\n        synchronized (keyLock) {\n            return keysDown.contains(keycode);\n        }\n    }\n\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyTyped(KeyEvent e) {\n        synchronized (keyLock) {\n            keysTyped.addFirst(e.getKeyChar());\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyPressed(KeyEvent e) {\n        synchronized (keyLock) {\n            keysDown.add(e.getKeyCode());\n        }\n    }\n\n    /**\n     * This method cannot be called directly.\n     */\n    @Override\n    public void keyReleased(KeyEvent e) {\n        synchronized (keyLock) {\n            keysDown.remove(e.getKeyCode());\n        }\n    }\n\n\n\n\n    /**\n     * Test client.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        StdDraw.square(.2, .8, .1);\n        StdDraw.filledSquare(.8, .8, .2);\n        StdDraw.circle(.8, .2, .2);\n\n        StdDraw.setPenColor(StdDraw.BOOK_RED);\n        StdDraw.setPenRadius(.02);\n        StdDraw.arc(.8, .2, .1, 200, 45);\n\n        // draw a blue diamond\n        StdDraw.setPenRadius();\n        StdDraw.setPenColor(StdDraw.BOOK_BLUE);\n        double[] x = { .1, .2, .3, .2 };\n        double[] y = { .2, .3, .2, .1 };\n        StdDraw.filledPolygon(x, y);\n\n        // text\n        StdDraw.setPenColor(StdDraw.BLACK);\n        StdDraw.text(0.2, 0.5, \"black text\");\n        StdDraw.setPenColor(StdDraw.WHITE);\n        StdDraw.text(0.8, 0.8, \"white text\");\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/StdIn.java",
    "content": "/******************************************************************************\n *  Compilation:  javac StdIn.java\n *  Execution:    java StdIn   (interactive test of basic functionality)\n *  Dependencies: none\n *\n *  Reads in data of various types from standard input.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.ArrayList;\nimport java.util.InputMismatchException;\nimport java.util.Locale;\nimport java.util.NoSuchElementException;\nimport java.util.Scanner;\nimport java.util.regex.Pattern;\n\n/**\n *  The {@code StdIn} class provides static methods for reading strings\n *  and numbers from standard input.\n *  These functions fall into one of four categories:\n *  <ul>\n *  <li>those for reading individual tokens from standard input, one at a time,\n *      and converting each to a number, string, or boolean\n *  <li>those for reading characters from standard input, one at a time\n *  <li>those for reading lines from standard input, one at a time\n *  <li>those for reading a sequence of values of the same type from standard input,\n *      and returning the values in an array\n *  </ul>\n *  <p>\n *  Generally, it is best not to mix functions from the different\n *  categories in the same program. \n *  <p>\n *  <b>Reading tokens from standard input one at a time,\n *  and converting to numbers and strings.</b>\n *  You can use the following methods to read numbers, strings, and booleans\n *  from standard input:\n *  <ul>\n *  <li> {@link #readInt()}\n *  <li> {@link #readDouble()}\n *  <li> {@link #readString()}\n *  <li> {@link #readBoolean()}\n *  <li> {@link #readShort()}\n *  <li> {@link #readLong()}\n *  <li> {@link #readFloat()}\n *  <li> {@link #readByte()}\n *  </ul>\n *  <p>\n *  Each method skips over any input that is whitespace. Then, it reads\n *  the next token and attempts to convert it into a value of the specified\n *  type. If it succeeds, it returns that value; otherwise, it\n *  throws a {@link InputMismatchException}.\n *  <p>\n *  <em>Whitespace</em> includes spaces, tabs, and newlines; the full definition\n *  is inherited from {@link Character#isWhitespace(char)}.\n *  A <em>token</em> is a maximal sequence of non-whitespace characters.\n *  The precise rules for describing which tokens can be converted to\n *  integers and floating-point numbers are inherited from\n *  <a href = \"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#number-syntax\">Scanner</a>,\n *  using the locale {@link Locale#US}; the rules\n *  for floating-point numbers are slightly different\n *  from those in {@link Double#valueOf(String)},\n *  but unlikely to be of concern to most programmers.\n *  <p>\n *  <b>Reading characters from standard input, one at a time.</b>\n *  You can use the following two methods to read characters from standard input:\n *  <ul>\n *  <li> {@link #hasNextChar()}\n *  <li> {@link #readChar()}\n *  </ul>\n *  <p>\n *  The first method returns true if standard input has more input (including whitespace).\n *  The second method reads and returns the next character of input on standard \n *  input (possibly a whitespace character).\n *  <p>\n *  As an example, the following code fragment reads characters from standard input,\n *  one character at a time, and prints it to standard output.\n *  <pre>\n *  while (StdIn.hasNextChar()) {\n *      char c = StdIn.readChar();\n *      StdOut.print(c);\n *  }\n *  </pre>\n *  <p>\n *  <b>Reading lines from standard input, one at a time.</b>\n *  You can use the following two methods to read lines from standard input:\n *  <ul>\n *  <li> {@link #hasNextLine()}\n *  <li> {@link #readLine()}\n *  </ul>\n *  <p>\n *  The first method returns true if standard input has more input (including whitespace).\n *  The second method reads and returns the remaining portion of \n *  the next line of input on standard input (possibly whitespace),\n *  discarding the trailing line separator.\n *  <p>\n *  A <em>line separator</em> is defined to be one of the following strings:\n *  {@code \\n} (Linux), {@code \\r} (old Macintosh),\n *  {@code \\r\\n} (Windows),\n *  {@code &#92;u2028}, {@code &#92;u2029}, or {@code &#92;u0085}.\n *  <p>\n *  As an example, the following code fragment reads text from standard input,\n *  one line at a time, and prints it to standard output.\n *  <pre>\n *  while (StdIn.hasNextLine()) {\n *      String line = StdIn.readLine();\n *      StdOut.println(line);\n *  }\n *  </pre>\n *  <p>\n *  <b>Reading a sequence of values of the same type from standard input.</b>\n *  You can use the following methods to read a sequence numbers, strings,\n *  or booleans (all of the same type) from standard input:\n *  <ul>\n *  <li> {@link #readAllDoubles()}\n *  <li> {@link #readAllInts()}\n *  <li> {@link #readAllLongs()}\n *  <li> {@link #readAllStrings()}\n *  <li> {@link #readAllLines()}\n *  <li> {@link #readAll()}\n *  </ul>\n *  <p>\n *  The first three methods read of all of remaining token on standard input\n *  and dconverts the tokens to values of\n *  the specified type, as in the corresponding\n *  {@code readDouble}, {@code readInt}, and {@code readString()} methods.\n *  The {@code readAllLines()} method reads all remaining lines on standard\n *  input and returns them as an array of strings.\n *  The {@code readAll()} method reads all remaining input on standard\n *  input and returns it as a string.\n *  <p>\n *  As an example, the following code fragment reads all of the remaining\n *  tokens from standard input and returns them as an array of strings.\n *  <pre>\n *  String[] words = StdIn.readAllStrings();\n *  </pre>\n *  <p>\n *  <b>Differences with Scanner.</b>\n *  {@code StdIn} and {@link Scanner} are both designed to parse \n *  tokens and convert them to primitive types and strings.\n *  Some of the main differences are summarized below:\n *  <ul>\n *  <li> {@code StdIn} is a set of static methods and reads \n *       reads input from only standard input. It is suitable for use before\n *       a programmer knows about objects.\n *       See {@link In} for an object-oriented version that handles\n *       input from files, URLs,\n *       and sockets.\n *  <li> {@code StdIn} uses whitespace as the delimiter between tokens.\n *  <li> {@code StdIn} coerces the character-set encoding to UTF-8,\n *       which is a standard character encoding for Unicode.\n *  <li> {@code StdIn} coerces the locale to {@link Locale#US},\n *       for consistency with {@link StdOut}, {@link Double#parseDouble(String)},\n *       and floating-point literals.\n *  <li> {@code StdIn} has convenient methods for reading a single\n *       character; reading in sequences of integers, doubles, or strings;\n *       and reading in all of the remaining input.\n *  </ul>\n *  <p>\n *  Historical note: {@code StdIn} preceded {@code Scanner}; when\n *  {@code Scanner} was introduced, this class was reimplemented to use {@code Scanner}.\n *  <p>\n *  <b>Using standard input.</b>\n *  Standard input is fundamental operating system abstraction, on Mac OS X,\n *  Windows, and Linux.\n *  The methods in {@code StdIn} are <em>blocking</em>, which means that they\n *  will wait until you enter input on standard input.\n *  If your program has a loop that repeats until standard input is empty,\n *  you must signal that the input is finished.\n *  To do so, depending on your operating system and IDE,\n *  use either {@code <Ctrl-d>} or {@code <Ctrl-z>}, on its own line.\n *  If you are redirecting standard input from a file, you will not need\n *  to do anything to signal that the input is finished.\n *  <p>\n *  <b>Known bugs.</b>\n *  Java's UTF-8 encoding does not recognize the optional \n *  <a href = \"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058\">byte-order mask</a>.\n *  If the input begins with the optional byte-order mask, {@code StdIn}\n *  will have an extra character {@code &#92;uFEFF} at the beginning.\n *  <p>\n *  <b>Reference.</b> \n *  For additional documentation,\n *  see <a href=\"http://introcs.cs.princeton.edu/15inout\">Section 1.5</a> of   \n *  <em>Introduction to Programming in Java: An Interdisciplinary Approach</em>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author David Pritchard\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class StdIn {\n\n    /*** begin: section (1 of 2) of code duplicated from In to StdIn. */\n    \n    // assume Unicode UTF-8 encoding\n    private static final String CHARSET_NAME = \"UTF-8\";\n\n    // assume language = English, country = US for consistency with System.out.\n    private static final Locale LOCALE = Locale.US;\n\n    // the default token separator; we maintain the invariant that this value\n    // is held by the scanner's delimiter between calls\n    private static final Pattern WHITESPACE_PATTERN = Pattern.compile(\"\\\\p{javaWhitespace}+\");\n\n    // makes whitespace significant\n    private static final Pattern EMPTY_PATTERN = Pattern.compile(\"\");\n\n    // used to read the entire input\n    private static final Pattern EVERYTHING_PATTERN = Pattern.compile(\"\\\\A\");\n\n    /*** end: section (1 of 2) of code duplicated from In to StdIn. */\n\n    private static Scanner scanner;\n \n    // it doesn't make sense to instantiate this class\n    private StdIn() { }\n\n    //// begin: section (2 of 2) of code duplicated from In to StdIn,\n    //// with all methods changed from \"public\" to \"public static\"\n\n   /**\n     * Returns true if standard input is empty (except possibly for whitespace).\n     * Use this method to know whether the next call to {@link #readString()}, \n     * {@link #readDouble()}, etc will succeed.\n     *\n     * @return {@code true} if standard input is empty (except possibly\n     *         for whitespace); {@code false} otherwise\n     */\n    public static boolean isEmpty() {\n        return !scanner.hasNext();\n    }\n\n   /**\n     * Returns true if standard input has a next line.\n     * Use this method to know whether the\n     * next call to {@link #readLine()} will succeed.\n     * This method is functionally equivalent to {@link #hasNextChar()}.\n     *\n     * @return {@code true} if standard input is empty;\n     *         {@code false} otherwise\n     */\n    public static boolean hasNextLine() {\n        return scanner.hasNextLine();\n    }\n\n    /**\n     * Returns true if standard input has more inputy (including whitespace).\n     * Use this method to know whether the next call to {@link #readChar()} will succeed.\n     * This method is functionally equivalent to {@link #hasNextLine()}.\n     *\n     * @return {@code true} if standard input has more input (including whitespace);\n     *         {@code false} otherwise\n     */\n    public static boolean hasNextChar() {\n        scanner.useDelimiter(EMPTY_PATTERN);\n        boolean result = scanner.hasNext();\n        scanner.useDelimiter(WHITESPACE_PATTERN);\n        return result;\n    }\n\n\n   /**\n     * Reads and returns the next line, excluding the line separator if present.\n     *\n     * @return the next line, excluding the line separator if present;\n     *         {@code null} if no such line\n     */\n    public static String readLine() {\n        String line;\n        try {\n            line = scanner.nextLine();\n        }\n        catch (NoSuchElementException e) {\n            line = null;\n        }\n        return line;\n    }\n\n    /**\n     * Reads and returns the next character.\n     *\n     * @return the next character\n     * @throws NoSuchElementException if standard input is empty\n     */\n    public static char readChar() {\n        scanner.useDelimiter(EMPTY_PATTERN);\n        String ch = scanner.next();\n        assert ch.length() == 1 : \"Internal (Std)In.readChar() error!\"\n            + \" Please contact the authors.\";\n        scanner.useDelimiter(WHITESPACE_PATTERN);\n        return ch.charAt(0);\n    }  \n\n\n   /**\n     * Reads and returns the remainder of the input, as a string.\n     *\n     * @return the remainder of the input, as a string\n     * @throws NoSuchElementException if standard input is empty\n     */\n    public static String readAll() {\n        if (!scanner.hasNextLine())\n            return \"\";\n\n        String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();\n        // not that important to reset delimeter, since now scanner is empty\n        scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway\n        return result;\n    }\n\n\n   /**\n     * Reads the next token  and returns the {@code String}.\n     *\n     * @return the next {@code String}\n     * @throws NoSuchElementException if standard input is empty\n     */\n    public static String readString() {\n        return scanner.next();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as an integer, and returns the integer.\n     *\n     * @return the next integer on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as an {@code int}\n     */\n    public static int readInt() {\n        return scanner.nextInt();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as a double, and returns the double.\n     *\n     * @return the next double on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code double}\n     */\n    public static double readDouble() {\n        return scanner.nextDouble();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as a float, and returns the float.\n     *\n     * @return the next float on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code float}\n     */\n    public static float readFloat() {\n        return scanner.nextFloat();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as a long integer, and returns the long integer.\n     *\n     * @return the next long integer on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code long}\n     */\n    public static long readLong() {\n        return scanner.nextLong();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as a short integer, and returns the short integer.\n     *\n     * @return the next short integer on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code short}\n     */\n    public static short readShort() {\n        return scanner.nextShort();\n    }\n\n   /**\n     * Reads the next token from standard input, parses it as a byte, and returns the byte.\n     *\n     * @return the next byte on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code byte}\n     */\n    public static byte readByte() {\n        return scanner.nextByte();\n    }\n\n    /**\n     * Reads the next token from standard input, parses it as a boolean,\n     * and returns the boolean.\n     *\n     * @return the next boolean on standard input\n     * @throws NoSuchElementException if standard input is empty\n     * @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:\n     *    {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,\n     *    ignoring case\n     */\n    public static boolean readBoolean() {\n        String s = readString();\n        if (s.equalsIgnoreCase(\"true\"))  return true;\n        if (s.equalsIgnoreCase(\"false\")) return false;\n        if (s.equals(\"1\"))               return true;\n        if (s.equals(\"0\"))               return false;\n        throw new InputMismatchException();\n    }\n\n    /**\n     * Reads all remaining tokens from standard input and returns them as an array of strings.\n     *\n     * @return all remaining tokens on standard input, as an array of strings\n     */\n    public static String[] readAllStrings() {\n        // we could use readAll.trim().split(), but that's not consistent\n        // because trim() uses characters 0x00..0x20 as whitespace\n        String[] tokens = WHITESPACE_PATTERN.split(readAll());\n        if (tokens.length == 0 || tokens[0].length() > 0)\n            return tokens;\n\n        // don't include first token if it is leading whitespace\n        String[] decapitokens = new String[tokens.length-1];\n        for (int i = 0; i < tokens.length - 1; i++)\n            decapitokens[i] = tokens[i+1];\n        return decapitokens;\n    }\n\n    /**\n     * Reads all remaining lines from standard input and returns them as an array of strings.\n     * @return all remaining lines on standard input, as an array of strings\n     */\n    public static String[] readAllLines() {\n        ArrayList<String> lines = new ArrayList<String>();\n        while (hasNextLine()) {\n            lines.add(readLine());\n        }\n        return lines.toArray(new String[0]);\n    }\n\n    /**\n     * Reads all remaining tokens from standard input, parses them as integers, and returns\n     * them as an array of integers.\n     * @return all remaining integers on standard input, as an array\n     * @throws InputMismatchException if any token cannot be parsed as an {@code int}\n     */\n    public static int[] readAllInts() {\n        String[] fields = readAllStrings();\n        int[] vals = new int[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Integer.parseInt(fields[i]);\n        return vals;\n    }\n\n    /**\n     * Reads all remaining tokens from standard input, parses them as longs, and returns\n     * them as an array of longs.\n     * @return all remaining longs on standard input, as an array\n     * @throws InputMismatchException if any token cannot be parsed as a {@code long}\n     */\n    public static long[] readAllLongs() {\n        String[] fields = readAllStrings();\n        long[] vals = new long[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Long.parseLong(fields[i]);\n        return vals;\n    }\n\n    /**\n     * Reads all remaining tokens from standard input, parses them as doubles, and returns\n     * them as an array of doubles.\n     * @return all remaining doubles on standard input, as an array\n     * @throws InputMismatchException if any token cannot be parsed as a {@code double}\n     */\n    public static double[] readAllDoubles() {\n        String[] fields = readAllStrings();\n        double[] vals = new double[fields.length];\n        for (int i = 0; i < fields.length; i++)\n            vals[i] = Double.parseDouble(fields[i]);\n        return vals;\n    }\n    \n    //// end: section (2 of 2) of code duplicated from In to StdIn\n    \n    \n    // do this once when StdIn is initialized\n    static {\n        resync();\n    }\n\n    /**\n     * If StdIn changes, use this to reinitialize the scanner.\n     */\n    private static void resync() {\n        setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME));\n    }\n    \n    private static void setScanner(Scanner scanner) {\n        StdIn.scanner = scanner;\n        StdIn.scanner.useLocale(LOCALE);\n    }\n\n   /**\n     * Reads all remaining tokens, parses them as integers, and returns\n     * them as an array of integers.\n     * @return all remaining integers, as an array\n     * @throws InputMismatchException if any token cannot be parsed as an {@code int}\n     * @deprecated Replaced by {@link #readAllInts()}.\n     */\n    @Deprecated\n    public static int[] readInts() {\n        return readAllInts();\n    }\n\n   /**\n     * Reads all remaining tokens, parses them as doubles, and returns\n     * them as an array of doubles.\n     * @return all remaining doubles, as an array\n     * @throws InputMismatchException if any token cannot be parsed as a {@code double}\n     * @deprecated Replaced by {@link #readAllDoubles()}.\n     */\n    @Deprecated\n    public static double[] readDoubles() {\n        return readAllDoubles();\n    }\n\n   /**\n     * Reads all remaining tokens and returns them as an array of strings.\n     * @return all remaining tokens, as an array of strings\n     * @deprecated Replaced by {@link #readAllStrings()}.\n     */\n    @Deprecated\n    public static String[] readStrings() {\n        return readAllStrings();\n    }\n\n\n    /**\n     * Interactive test of basic functionality.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n\n        StdOut.print(\"Type a string: \");\n        String s = StdIn.readString();\n        StdOut.println(\"Your string was: \" + s);\n        StdOut.println();\n\n        StdOut.print(\"Type an int: \");\n        int a = StdIn.readInt();\n        StdOut.println(\"Your int was: \" + a);\n        StdOut.println();\n\n        StdOut.print(\"Type a boolean: \");\n        boolean b = StdIn.readBoolean();\n        StdOut.println(\"Your boolean was: \" + b);\n        StdOut.println();\n\n        StdOut.print(\"Type a double: \");\n        double c = StdIn.readDouble();\n        StdOut.println(\"Your double was: \" + c);\n        StdOut.println();\n\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/StdOut.java",
    "content": "/******************************************************************************\n *  Compilation:  javac StdOut.java\n *  Execution:    java StdOut\n *  Dependencies: none\n *\n *  Writes data of various types to standard output.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.io.UnsupportedEncodingException;\nimport java.util.Locale;\n\n/**\n *  This class provides methods for printing strings and numbers to standard output.\n *  <p>\n *  <b>Getting started.</b>\n *  To use this class, you must have {@code StdOut.class} in your\n *  Java classpath. If you used our autoinstaller, you should be all set.\n *  Otherwise, download\n *  <a href = \"http://introcs.cs.princeton.edu/java/stdlib/StdOut.java\">StdOut.java</a>\n *  and put a copy in your working directory.\n *  <p>\n *  Here is an example program that uses {@code StdOut}:\n *  <pre>\n *   public class TestStdOut {\n *       public static void main(String[] args) {\n *           int a = 17;\n *           int b = 23;\n *           int sum = a + b;\n *           StdOut.println(\"Hello, World\");\n *           StdOut.printf(\"%d + %d = %d\\n\", a, b, sum);\n *       }\n *   }\n *  </pre>\n *  <p>\n *  <b>Differences with System.out.</b>\n *  The behavior of {@code StdOut} is similar to that of {@link System#out},\n *  but there are a few subtle differences:\n *  <ul>\n *  <li> {@code StdOut} coerces the character-set encoding to UTF-8,\n *       which is a standard character encoding for Unicode.\n *  <li> {@code StdOut} coerces the locale to {@link Locale#US},\n *       for consistency with {@link StdIn}, {@link Double#parseDouble(String)},\n *       and floating-point literals.\n *  <li> {@code StdOut} <em>flushes</em> standard output after each call to\n *       {@code print()} so that text will appear immediately in the terminal.\n *  </ul>\n *  <p>\n *  <b>Reference.</b>\n *  For additional documentation,\n *  see <a href=\"http://introcs.cs.princeton.edu/15inout\">Section 1.5</a> of\n *  <em>Introduction to Programming in Java: An Interdisciplinary Approach</em>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class StdOut {\n\n    // force Unicode UTF-8 encoding; otherwise it's system dependent\n    private static final String CHARSET_NAME = \"UTF-8\";\n\n    // assume language = English, country = US for consistency with StdIn\n    private static final Locale LOCALE = Locale.US;\n\n    // send output here\n    private static PrintWriter out;\n\n    // this is called before invoking any methods\n    static {\n        try {\n            out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);\n        }\n        catch (UnsupportedEncodingException e) {\n            System.out.println(e);\n        }\n    }\n\n    // don't instantiate\n    private StdOut() { }\n\n   /**\n     * Closes standard output.\n     */\n    public static void close() {\n        out.close();\n    }\n\n   /**\n     * Terminates the current line by printing the line-separator string.\n     */\n    public static void println() {\n        out.println();\n    }\n\n   /**\n     * Prints an object to this output stream and then terminates the line.\n     *\n     * @param x the object to print\n     */\n    public static void println(Object x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a boolean to standard output and then terminates the line.\n     *\n     * @param x the boolean to print\n     */\n    public static void println(boolean x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a character to standard output and then terminates the line.\n     *\n     * @param x the character to print\n     */\n    public static void println(char x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a double to standard output and then terminates the line.\n     *\n     * @param x the double to print\n     */\n    public static void println(double x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints an integer to standard output and then terminates the line.\n     *\n     * @param x the integer to print\n     */\n    public static void println(float x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints an integer to standard output and then terminates the line.\n     *\n     * @param x the integer to print\n     */\n    public static void println(int x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a long to standard output and then terminates the line.\n     *\n     * @param x the long to print\n     */\n    public static void println(long x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a short integer to standard output and then terminates the line.\n     *\n     * @param x the short to print\n     */\n    public static void println(short x) {\n        out.println(x);\n    }\n\n   /**\n     * Prints a byte to standard output and then terminates the line.\n     * <p>\n     * To write binary data, see {@link BinaryStdOut}.\n     *\n     * @param x the byte to print\n     */\n    public static void println(byte x) {\n        out.println(x);\n    }\n\n   /**\n     * Flushes standard output.\n     */\n    public static void print() {\n        out.flush();\n    }\n\n   /**\n     * Prints an object to standard output and flushes standard output.\n     * \n     * @param x the object to print\n     */\n    public static void print(Object x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a boolean to standard output and flushes standard output.\n     * \n     * @param x the boolean to print\n     */\n    public static void print(boolean x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a character to standard output and flushes standard output.\n     * \n     * @param x the character to print\n     */\n    public static void print(char x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a double to standard output and flushes standard output.\n     * \n     * @param x the double to print\n     */\n    public static void print(double x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a float to standard output and flushes standard output.\n     * \n     * @param x the float to print\n     */\n    public static void print(float x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints an integer to standard output and flushes standard output.\n     * \n     * @param x the integer to print\n     */\n    public static void print(int x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a long integer to standard output and flushes standard output.\n     * \n     * @param x the long integer to print\n     */\n    public static void print(long x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a short integer to standard output and flushes standard output.\n     * \n     * @param x the short integer to print\n     */\n    public static void print(short x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a byte to standard output and flushes standard output.\n     *\n     * @param x the byte to print\n     */\n    public static void print(byte x) {\n        out.print(x);\n        out.flush();\n    }\n\n   /**\n     * Prints a formatted string to standard output, using the specified format\n     * string and arguments, and then flushes standard output.\n     *\n     *\n     * @param format the <a href = \"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax\">format string</a>\n     * @param args   the arguments accompanying the format string\n     */\n    public static void printf(String format, Object... args) {\n        out.printf(LOCALE, format, args);\n        out.flush();\n    }\n\n   /**\n     * Prints a formatted string to standard output, using the locale and\n     * the specified format string and arguments; then flushes standard output.\n     *\n     * @param locale the locale\n     * @param format the <a href = \"http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax\">format string</a>\n     * @param args   the arguments accompanying the format string\n     */\n    public static void printf(Locale locale, String format, Object... args) {\n        out.printf(locale, format, args);\n        out.flush();\n    }\n\n   /**\n     * Unit tests some of the methods in {@code StdOut}.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n\n        // write to stdout\n        StdOut.println(\"Test\");\n        StdOut.println(17);\n        StdOut.println(true);\n        StdOut.printf(\"%.6f\\n\", 1.0/7.0);\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/algs4/StdRandom.java",
    "content": "/******************************************************************************\n *  Compilation:  javac StdRandom.java\n *  Execution:    java StdRandom\n *  Dependencies: StdOut.java\n *\n *  A library of static methods to generate pseudo-random numbers from\n *  different distributions (bernoulli, uniform, gaussian, discrete,\n *  and exponential). Also includes a method for shuffling an array.\n *\n *\n *  %  java StdRandom 5\n *  seed = 1316600602069\n *  59 16.81826  true 8.83954  0 \n *  32 91.32098  true 9.11026  0 \n *  35 10.11874  true 8.95396  3 \n *  92 32.88401  true 8.87089  0 \n *  72 92.55791  true 9.46241  0 \n *\n *  % java StdRandom 5\n *  seed = 1316600616575\n *  96 60.17070  true 8.72821  0 \n *  79 32.01607  true 8.58159  0 \n *  81 59.49065  true 9.10423  1 \n *  96 51.65818  true 9.02102  0 \n *  99 17.55771  true 8.99762  0 \n *\n *  % java StdRandom 5 1316600616575\n *  seed = 1316600616575\n *  96 60.17070  true 8.72821  0 \n *  79 32.01607  true 8.58159  0 \n *  81 59.49065  true 9.10423  1 \n *  96 51.65818  true 9.02102  0 \n *  99 17.55771  true 8.99762  0 \n *\n *\n *  Remark\n *  ------\n *    - Relies on randomness of nextDouble() method in java.util.Random\n *      to generate pseudorandom numbers in [0, 1).\n *\n *    - This library allows you to set and get the pseudorandom number seed.\n *\n *    - See http://www.honeylocust.com/RngPack/ for an industrial\n *      strength random number generator in Java.\n *\n ******************************************************************************/\n\npackage algs4;\n\nimport java.util.Random;\n\n/**\n *  The {@code StdRandom} class provides static methods for generating\n *  random number from various discrete and continuous distributions, \n *  including Bernoulli, uniform, Gaussian, exponential, pareto,\n *  Poisson, and Cauchy. It also provides method for shuffling an\n *  array or subarray.\n *  <p>\n *  For additional documentation,\n *  see <a href=\"http://introcs.cs.princeton.edu/22library\">Section 2.2</a> of\n *  <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>\n *  by Robert Sedgewick and Kevin Wayne.\n *\n *  @author Robert Sedgewick\n *  @author Kevin Wayne\n */\npublic final class StdRandom {\n\n    private static Random random;    // pseudo-random number generator\n    private static long seed;        // pseudo-random number generator seed\n\n    // static initializer\n    static {\n        // this is how the seed was set in Java 1.4\n        seed = System.currentTimeMillis();\n        random = new Random(seed);\n    }\n\n    // don't instantiate\n    private StdRandom() { }\n\n    /**\n     * Sets the seed of the pseudorandom number generator.\n     * This method enables you to produce the same sequence of \"random\"\n     * number for each execution of the program.\n     * Ordinarily, you should call this method at most once per program.\n     *\n     * @param s the seed\n     */\n    public static void setSeed(long s) {\n        seed   = s;\n        random = new Random(seed);\n    }\n\n    /**\n     * Returns the seed of the pseudorandom number generator.\n     *\n     * @return the seed\n     */\n    public static long getSeed() {\n        return seed;\n    }\n\n    /**\n     * Returns a random real number uniformly in [0, 1).\n     *\n     * @return a random real number uniformly in [0, 1)\n     */\n    public static double uniform() {\n        return random.nextDouble();\n    }\n\n    /**\n     * Returns a random integer uniformly in [0, n).\n     * \n     * @param n number of possible integers\n     * @return a random integer uniformly between 0 (inclusive) and {@code N} (exclusive)\n     * @throws IllegalArgumentException if {@code n <= 0}\n     */\n    public static int uniform(int n) {\n        if (n <= 0) throw new IllegalArgumentException(\"Parameter N must be positive\");\n        return random.nextInt(n);\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    //  STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA\n    //  THE STATIC METHODS ABOVE.\n    ///////////////////////////////////////////////////////////////////////////\n\n    /**\n     * Returns a random real number uniformly in [0, 1).\n     * \n     * @return     a random real number uniformly in [0, 1)\n     * @deprecated Replaced by {@link #uniform()}.\n     */\n    @Deprecated\n    public static double random() {\n        return uniform();\n    }\n\n    /**\n     * Returns a random integer uniformly in [a, b).\n     * \n     * @param  a the left endpoint\n     * @param  b the right endpoint\n     * @return a random integer uniformly in [a, b)\n     * @throws IllegalArgumentException if {@code b <= a}\n     * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE}\n     */\n    public static int uniform(int a, int b) {\n        if (b <= a) throw new IllegalArgumentException(\"Invalid range\");\n        if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException(\"Invalid range\");\n        return a + uniform(b - a);\n    }\n\n    /**\n     * Returns a random real number uniformly in [a, b).\n     * \n     * @param  a the left endpoint\n     * @param  b the right endpoint\n     * @return a random real number uniformly in [a, b)\n     * @throws IllegalArgumentException unless {@code a < b}\n     */\n    public static double uniform(double a, double b) {\n        if (!(a < b)) throw new IllegalArgumentException(\"Invalid range\");\n        return a + uniform() * (b-a);\n    }\n\n    /**\n     * Returns a random boolean from a Bernoulli distribution with success\n     * probability <em>p</em>.\n     *\n     * @param  p the probability of returning {@code true}\n     * @return {@code true} with probability {@code p} and\n     *         {@code false} with probability {@code p}\n     * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0}\n     */\n    public static boolean bernoulli(double p) {\n        if (!(p >= 0.0 && p <= 1.0))\n            throw new IllegalArgumentException(\"Probability must be between 0.0 and 1.0\");\n        return uniform() < p;\n    }\n\n    /**\n     * Returns a random boolean from a Bernoulli distribution with success\n     * probability 1/2.\n     * \n     * @return {@code true} with probability 1/2 and\n     *         {@code false} with probability 1/2\n     */\n    public static boolean bernoulli() {\n        return bernoulli(0.5);\n    }\n\n    /**\n     * Returns a random real number from a standard Gaussian distribution.\n     * \n     * @return a random real number from a standard Gaussian distribution\n     *         (mean 0 and standard deviation 1).\n     */\n    public static double gaussian() {\n        // use the polar form of the Box-Muller transform\n        double r, x, y;\n        do {\n            x = uniform(-1.0, 1.0);\n            y = uniform(-1.0, 1.0);\n            r = x*x + y*y;\n        } while (r >= 1 || r == 0);\n        return x * Math.sqrt(-2 * Math.log(r) / r);\n\n        // Remark:  y * Math.sqrt(-2 * Math.log(r) / r)\n        // is an independent random gaussian\n    }\n\n    /**\n     * Returns a random real number from a Gaussian distribution with mean &mu;\n     * and standard deviation &sigma;.\n     * \n     * @param  mu the mean\n     * @param  sigma the standard deviation\n     * @return a real number distributed according to the Gaussian distribution\n     *         with mean {@code mu} and standard deviation {@code sigma}\n     */\n    public static double gaussian(double mu, double sigma) {\n        return mu + sigma * gaussian();\n    }\n\n    /**\n     * Returns a random integer from a geometric distribution with success\n     * probability <em>p</em>.\n     * \n     * @param  p the parameter of the geometric distribution\n     * @return a random integer from a geometric distribution with success\n     *         probability {@code p}; or {@code Integer.MAX_VALUE} if\n     *         {@code p} is (nearly) equal to {@code 1.0}.\n     * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0}\n     */\n    public static int geometric(double p) {\n        if (!(p >= 0.0 && p <= 1.0))\n            throw new IllegalArgumentException(\"Probability must be between 0.0 and 1.0\");\n        // using algorithm given by Knuth\n        return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));\n    }\n\n    /**\n     * Returns a random integer from a Poisson distribution with mean &lambda;.\n     *\n     * @param  lambda the mean of the Poisson distribution\n     * @return a random integer from a Poisson distribution with mean {@code lambda}\n     * @throws IllegalArgumentException unless {@code lambda > 0.0} and not infinite\n     */\n    public static int poisson(double lambda) {\n        if (!(lambda > 0.0))\n            throw new IllegalArgumentException(\"Parameter lambda must be positive\");\n        if (Double.isInfinite(lambda))\n            throw new IllegalArgumentException(\"Parameter lambda must not be infinite\");\n        // using algorithm given by Knuth\n        // see http://en.wikipedia.org/wiki/Poisson_distribution\n        int k = 0;\n        double p = 1.0;\n        double expLambda = Math.exp(-lambda);\n        do {\n            k++;\n            p *= uniform();\n        } while (p >= expLambda);\n        return k-1;\n    }\n\n    /**\n     * Returns a random real number from the standard Pareto distribution.\n     *\n     * @return a random real number from the standard Pareto distribution\n     */\n    public static double pareto() {\n        return pareto(1.0);\n    }\n\n    /**\n     * Returns a random real number from a Pareto distribution with\n     * shape parameter &alpha;.\n     *\n     * @param  alpha shape parameter\n     * @return a random real number from a Pareto distribution with shape\n     *         parameter {@code alpha}\n     * @throws IllegalArgumentException unless {@code alpha > 0.0}\n     */\n    public static double pareto(double alpha) {\n        if (!(alpha > 0.0))\n            throw new IllegalArgumentException(\"Shape parameter alpha must be positive\");\n        return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;\n    }\n\n    /**\n     * Returns a random real number from the Cauchy distribution.\n     *\n     * @return a random real number from the Cauchy distribution.\n     */\n    public static double cauchy() {\n        return Math.tan(Math.PI * (uniform() - 0.5));\n    }\n\n    /**\n     * Returns a random integer from the specified discrete distribution.\n     *\n     * @param  probabilities the probability of occurrence of each integer\n     * @return a random integer from a discrete distribution:\n     *         {@code i} with probability {@code probabilities[i]}\n     * @throws NullPointerException if {@code probabilities} is {@code null}\n     * @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to {@code 1.0}\n     * @throws IllegalArgumentException unless {@code probabilities[i] >= 0.0} for each index {@code i}\n     */\n    public static int discrete(double[] probabilities) {\n        if (probabilities == null) throw new NullPointerException(\"argument array is null\");\n        double EPSILON = 1E-14;\n        double sum = 0.0;\n        for (int i = 0; i < probabilities.length; i++) {\n            if (!(probabilities[i] >= 0.0))\n                throw new IllegalArgumentException(\"array entry \" + i + \" must be nonnegative: \" + probabilities[i]);\n            sum += probabilities[i];\n        }\n        if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)\n            throw new IllegalArgumentException(\"sum of array entries does not approximately equal 1.0: \" + sum);\n\n        // the for loop may not return a value when both r is (nearly) 1.0 and when the\n        // cumulative sum is less than 1.0 (as a result of floating-point roundoff error)\n        while (true) {\n            double r = uniform();\n            sum = 0.0;\n            for (int i = 0; i < probabilities.length; i++) {\n                sum = sum + probabilities[i];\n                if (sum > r) return i;\n            }\n        }\n    }\n\n    /**\n     * Returns a random integer from the specified discrete distribution.\n     *\n     * @param  frequencies the frequency of occurrence of each integer\n     * @return a random integer from a discrete distribution:\n     *         {@code i} with probability proportional to {@code frequencies[i]}\n     * @throws NullPointerException if {@code frequencies} is {@code null}\n     * @throws IllegalArgumentException if all array entries are {@code 0}\n     * @throws IllegalArgumentException if {@code frequencies[i]} is negative for any index {@code i}\n     * @throws IllegalArgumentException if sum of frequencies exceeds {@code Integer.MAX_VALUE} (2<sup>31</sup> - 1)\n     */\n    public static int discrete(int[] frequencies) {\n        if (frequencies == null) throw new NullPointerException(\"argument array is null\");\n        long sum = 0;\n        for (int i = 0; i < frequencies.length; i++) {\n            if (frequencies[i] < 0)\n                throw new IllegalArgumentException(\"array entry \" + i + \" must be nonnegative: \" + frequencies[i]);\n            sum += frequencies[i];\n        }\n        if (sum == 0)\n            throw new IllegalArgumentException(\"at least one array entry must be positive\");\n        if (sum >= Integer.MAX_VALUE)\n            throw new IllegalArgumentException(\"sum of frequencies overflows an int\");\n\n        // pick index i with probabilitity proportional to frequency\n        double r = uniform((int) sum);\n        sum = 0;\n        for (int i = 0; i < frequencies.length; i++) {\n            sum += frequencies[i];\n            if (sum > r) return i;\n        }\n\n        // can't reach here\n        assert false;\n        return -1;\n    }\n\n    /**\n     * Returns a random real number from an exponential distribution\n     * with rate &lambda;.\n     * \n     * @param  lambda the rate of the exponential distribution\n     * @return a random real number from an exponential distribution with\n     *         rate {@code lambda}\n     * @throws IllegalArgumentException unless {@code lambda > 0.0}\n     */\n    public static double exp(double lambda) {\n        if (!(lambda > 0.0))\n            throw new IllegalArgumentException(\"Rate lambda must be positive\");\n        return -Math.log(1 - uniform()) / lambda;\n    }\n\n    /**\n     * Rearranges the elements of the specified array in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @throws NullPointerException if {@code a} is {@code null}\n     */\n    public static void shuffle(Object[] a) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        int n = a.length;\n        for (int i = 0; i < n; i++) {\n            int r = i + uniform(n-i);     // between i and n-1\n            Object temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n    /**\n     * Rearranges the elements of the specified array in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @throws NullPointerException if {@code a} is {@code null}\n     */\n    public static void shuffle(double[] a) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        int n = a.length;\n        for (int i = 0; i < n; i++) {\n            int r = i + uniform(n-i);     // between i and n-1\n            double temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n    /**\n     * Rearranges the elements of the specified array in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @throws NullPointerException if {@code a} is {@code null}\n     */\n    public static void shuffle(int[] a) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        int n = a.length;\n        for (int i = 0; i < n; i++) {\n            int r = i + uniform(n-i);     // between i and n-1\n            int temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n\n    /**\n     * Rearranges the elements of the specified subarray in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @param  lo the left endpoint (inclusive)\n     * @param  hi the right endpoint (inclusive)\n     * @throws NullPointerException if {@code a} is {@code null}\n     * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}\n     * \n     */\n    public static void shuffle(Object[] a, int lo, int hi) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        if (lo < 0 || lo > hi || hi >= a.length) {\n            throw new IndexOutOfBoundsException(\"Illegal subarray range\");\n        }\n        for (int i = lo; i <= hi; i++) {\n            int r = i + uniform(hi-i+1);     // between i and hi\n            Object temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n    /**\n     * Rearranges the elements of the specified subarray in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @param  lo the left endpoint (inclusive)\n     * @param  hi the right endpoint (inclusive)\n     * @throws NullPointerException if {@code a} is {@code null}\n     * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}\n     */\n    public static void shuffle(double[] a, int lo, int hi) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        if (lo < 0 || lo > hi || hi >= a.length) {\n            throw new IndexOutOfBoundsException(\"Illegal subarray range\");\n        }\n        for (int i = lo; i <= hi; i++) {\n            int r = i + uniform(hi-i+1);     // between i and hi\n            double temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n    /**\n     * Rearranges the elements of the specified subarray in uniformly random order.\n     *\n     * @param  a the array to shuffle\n     * @param  lo the left endpoint (inclusive)\n     * @param  hi the right endpoint (inclusive)\n     * @throws NullPointerException if {@code a} is {@code null}\n     * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}\n     */\n    public static void shuffle(int[] a, int lo, int hi) {\n        if (a == null) throw new NullPointerException(\"argument array is null\");\n        if (lo < 0 || lo > hi || hi >= a.length) {\n            throw new IndexOutOfBoundsException(\"Illegal subarray range\");\n        }\n        for (int i = lo; i <= hi; i++) {\n            int r = i + uniform(hi-i+1);     // between i and hi\n            int temp = a[i];\n            a[i] = a[r];\n            a[r] = temp;\n        }\n    }\n\n    /**\n     * Unit test.\n     *\n     * @param args the command-line arguments\n     */\n    public static void main(String[] args) {\n        int n = Integer.parseInt(args[0]);\n        if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));\n        double[] probabilities = { 0.5, 0.3, 0.1, 0.1 };\n        int[] frequencies = { 5, 3, 1, 1 };\n        String[] a = \"A B C D E F G\".split(\" \");\n\n        StdOut.println(\"seed = \" + StdRandom.getSeed());\n        for (int i = 0; i < n; i++) {\n            StdOut.printf(\"%2d \",   uniform(100));\n            StdOut.printf(\"%8.5f \", uniform(10.0, 99.0));\n            StdOut.printf(\"%5b \",   bernoulli(0.5));\n            StdOut.printf(\"%7.5f \", gaussian(9.0, 0.2));\n            StdOut.printf(\"%1d \",   discrete(probabilities));\n            StdOut.printf(\"%1d \",   discrete(frequencies));\n            StdRandom.shuffle(a);\n            for (String s : a)\n                StdOut.print(s);\n            StdOut.println();\n        }\n    }\n\n}\n\n/******************************************************************************\n *  Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.\n *\n *  This file is part of algs4.jar, which accompanies the textbook\n *\n *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,\n *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.\n *      http://algs4.cs.princeton.edu\n *\n *\n *  algs4.jar is free software: you can redistribute it and/or modify\n *  it under the terms of the GNU General Public License as published by\n *  the Free Software Foundation, either version 3 of the License, or\n *  (at your option) any later version.\n *\n *  algs4.jar is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n *  GNU General Public License for more details.\n *\n *  You should have received a copy of the GNU General Public License\n *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.\n ******************************************************************************/\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/BinarySearch.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport java.util.Arrays;\nimport algs4.*;\n\n/**\n * 二分查找\n * @author huang\n */\npublic class BinarySearch {\n\n    public static int rank(int key, int[] a) {\n        // 数组必须有序\n        int lo = 0;\n        int hi = a.length - 1;\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            if(key < a[mid])\n                hi = mid - 1;\n            else if(key > a[mid])\n                lo = mid + 1;\n            else\n                return mid;\n        }\n        return -1;\n    }\n    \n    public static void main(String[] args) {\n        \n        int[] whitelist = In.readInts(args[0]);\n        Arrays.sort(whitelist);\n        while(!StdIn.isEmpty()){\n            int key = StdIn.readInt();\n            if(rank(key, whitelist) < 0)\n                StdOut.println(key);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/BouncingBall.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdDraw;\n\npublic class BouncingBall {\n\n    public static void main(String[] args) {\n        \n        // set the scale of the coordinate system\n        StdDraw.setXscale(-1.0, 1.0);\n        StdDraw.setYscale(-1.0, 1.0);\n        StdDraw.enableDoubleBuffering();\n        \n        // initial values\n        double rx = .480, ry = .860;  // position\n        double vx = .015, vy = .023;  // velocity\n        double radius = .05;  // radius\n        \n        // main animation loop\n        while(true) {\n            // bounce off wall according to law of elastic collision\n            if(Math.abs(rx + vx) > 1.0 - radius)\n                vx = -vx;\n            if(Math.abs(ry + vy) > 1.0 - radius)\n                vy = -vy;\n            \n            // update position\n            rx = rx + vx;\n            ry = ry + vy;\n            \n            // clear the background\n            StdDraw.setPenColor(StdDraw.GRAY);\n            StdDraw.filledSquare(0, 0, 1.0);\n            \n            // draw ball on the screen\n            StdDraw.setPenColor(StdDraw.BLACK);\n            StdDraw.filledCircle(rx, ry, radius);\n            \n            // display and pause for 20 ms\n            StdDraw.show();\n            StdDraw.pause(20);\n        }\n        \n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex1.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex1 {\n\n    public static void main(String[] args) {\n        \n        StdOut.println((0 + 15) / 2);\n        StdOut.println(2.0e-6 * 100000000.1);\n        StdOut.println(true && false || true && true);\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex10.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex10 {\n\n    public static void main(String[] args) {\n        \n        int[] a = new int[10];\n        for(int i = 0; i < 10; i++)\n            a[i] = i*i;\n        for(int i = 9; i >= 0; i--)\n            StdOut.printf(\"%d \", a[i]);\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex11.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Ex11 {\n\n    public static void main(String[] args) {\n        \n        boolean[][] arr = new boolean[7][6];\n        for(int i = 0; i < 7; i++) {\n            for(int j = 0; j < 6; j++) {\n                double num = StdRandom.uniform();\n                if(num > 0.5)\n                    arr[i][j] = true;\n                else\n                    arr[i][j] = false;\n            }\n        }\n        \n        printBoolArr(arr);\n\n    }\n    \n    public static void printBoolArr (boolean[][] arr) {\n\n        StdOut.print(' ');\n        for (int i = 0; i < arr[0].length; i++) {\n            StdOut.print(i);\n        }\n        StdOut.println();\n        for (int i = 0; i < arr.length; i++) {\n            StdOut.print(i);\n            for (int j = 0; j < arr[i].length; j++) {\n                StdOut.print(arr[i][j] ? '*' : ' ');\n            }\n            StdOut.println();\n        }\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex13.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Ex13 {\n\n    public static void main(String[] args) {\n\n        int M = 3, N = 4;\n        int[][] arr = new int[M][N];\n        for (int i = 0; i < arr.length; i++)\n            for (int j = 0; j < arr[0].length; j++)\n                arr[i][j] = StdRandom.uniform(20);\n        StdOut.println(\"oldArr: \");\n        printArr(arr);\n        StdOut.println(\"newArr: \");\n        printArr(arrReverse(arr));\n\n    }\n\n    public static int[][] arrReverse(int[][] arr) {\n        int[][] newArr = new int[arr[0].length][arr.length];\n        for(int i = 0; i < newArr.length; i++)\n            for(int j = 0; j < newArr[0].length; j++)\n                newArr[i][j] = arr[j][i];\n\n        return newArr;\n    }\n\n    public static void printArr(int[][] arr) {\n        for (int i = 0; i < arr.length; i++) {\n            for(int j = 0; j < arr[0].length; j++) {\n                StdOut.printf(\"%d  \",arr[i][j]);\n            }\n            StdOut.println();\n            \n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex14.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex14 {\n\n    public static void main(String[] args) {\n        \n        StdOut.print(lg(8));\n\n    }\n    \n    public static int lg(int N) {\n        \n        int i = 0;\n        while(n2(i) <= N)\n            i++;\n        return i-1;\n    }\n    \n    public static int n2(int n) {\n        int result = 1;\n        for(int i = 0; i < n; i++)\n            result *= 2;\n        return result;\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex15.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex15 {\n\n    public static void main(String[] args) {\n        \n        int[] arr = {0, 1, 1, 1};\n        int[] timesArr = histogram(arr, 2);\n        for(int j = 0; j < timesArr.length; j++) {\n            StdOut.printf(\"%d \", timesArr[j]);\n        }\n    }\n    \n    public static int[] histogram(int[] a, int M) {\n        \n        int[] arr = new int[M];\n        for(int i = 0; i < M; i++){\n            int times = 0;\n            for(int j = 0; j < a.length; j++){\n                if(a[j] == i)\n                    times++;\n            }\n            arr[i] = times;\n        }\n        return arr;\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex19.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex19 {\n    \n    static final int M = 100;\n    static long[] arr = new long[M];\n    \n    public static long F(int N) {\n        if(N == 0)\n            arr[N] = 0;\n        else if(N == 1)\n            arr[N] = 1;\n        else\n            arr[N] = arr[N - 1] + arr[N - 2];\n        return arr[N];\n    }\n    \n    public static void main(String[] args) {\n        for(int N = 0; N < M; N++)\n            StdOut.println(N + \" \" + F(N));\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex2.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex2 {\n\n    public static void main(String[] args) {\n\n        StdOut.println((1 + 2.236) / 2);\n        StdOut.println(1 + 2 + 3 + 4.0);\n        StdOut.println(4.1 >= 4);\n        StdOut.println(1 + 2 + \"3\");\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex20.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex20 {\n\n    public static void main(String[] args) {\n        \n        StdOut.print(ln10(9));\n\n    }\n    \n    public static double ln10(int N) {\n        \n        if(N == 1)\n            return Math.log10(1);\n        return Math.log10(N) + ln10(N - 1);\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex3.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class Ex3 {\n    public static void main(String[] args) {\n        int a = StdIn.readInt();\n        int b = StdIn.readInt();\n        int c = StdIn.readInt();\n        if(a == b && a == c) {\n            StdOut.println(\"equal\");\n        } else {\n            StdOut.println(\"not equal\");\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex30.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex30 {\n\n    public static void main(String[] args) {\n        \n        int N = 10;\n        boolean[][] arr = new boolean [N][N];\n        setArrBoolean(arr);\n        \n        for(int i = 0; i < arr.length; i++) {\n            for(int j = 0; j < arr.length; j++) {\n                StdOut.printf(\"%b \", arr[i][j]);\n            }\n            StdOut.println();\n        }\n    }\n    \n    public static void setArrBoolean(boolean[][] arr) {\n        for(int i = 0; i < arr.length; i++) {\n            for(int j = 0; j < arr.length; j++) {\n                arr[i][j] = true;\n                for(int k = 2; k <= i; k++) {\n                    if((i % k == 0) && (j % k == 0)) {\n                        arr[i][j] = false;\n                    }\n                }\n            }\n        }   \n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex31.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport java.awt.Color;\n\nimport algs4.StdDraw;\nimport algs4.StdRandom;\n\npublic class Ex31 {\n    \n    static class Point {\n        double x, y;\n        \n        public Point(double x, double y) {\n            super();\n            this.x = x;\n            this.y = y;\n        }\n    }\n\n    public static void main(String[] args) {\n        \n        int N = Integer.parseInt(args[0]);\n        double p = Double.parseDouble(args[1]);\n        if(p < 0 || p > 1) {\n            System.out.println(\"p is not valid!\");\n            return;\n        }\n        Point[] points = new Point[N];\n        double angle = 360.0 / N;\n        StdDraw.circle(.5, .5, .5);\n        StdDraw.setPenRadius(.05);\n        \n        for(int i = 0; i < N; i++) {\n            points[i] = new Point(.5 + .5 * Math.cos(angle * i * Math.PI / 180),\n                    .5 + .5 * Math.sin(angle * i * Math.PI / 180));\n            StdDraw.point(points[i].x, points[i].y);\n        }\n        \n        StdDraw.setPenRadius(.01);\n        StdDraw.setPenColor(Color.GRAY);\n        \n        for(int i = 0; i < N - 1; i++) {\n            for(int j = i + 1; j < N; j++) {\n                if(StdRandom.bernoulli(p)) {\n                    StdDraw.line(points[i].x, points[i].y, points[j].x, points[j].y);\n                }\n            }\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex32.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport java.util.ArrayList;\nimport java.util.Scanner;\n\nimport algs4.StdDraw;\n\npublic class Ex32 {\n\n    public static void main(String[] args) {\n        \n        @SuppressWarnings(\"resource\")\n        Scanner scanner = new Scanner(System.in);\n        ArrayList<Double> list = new ArrayList<>();\n        while (scanner.hasNextDouble()) {\n            list.add(scanner.nextDouble());\n        }\n        \n        int N = Integer.parseInt(args[0]);\n        double l = Double.parseDouble(args[1]),\n               r = Double.parseDouble(args[2]);\n        \n        double length = (r - l) / N,\n               start = l;\n        \n        while(start < r) {\n            int height = 0;\n            for(int i = 0; i < list.size(); i++) { \n                if(start <= list.indexOf(i) && list.indexOf(i) < start + length) {\n                    height++;\n                }\n            }\n            StdDraw.filledRectangle(start, height, length / 2, height);\n            start += length;\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex6.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex6 {\n    public static void main(String[] args) {\n        int f = 0;\n        int g = 1;\n        for(int i = 0; i <= 15; i++){\n            StdOut.println(f);\n            f = f + g;\n            g = f - g;\n        }\n    }\n}"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex7a.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7a {\n\n    public static void main(String[] args) {\n        \n        double t = 9.0;\n        while(Math.abs(t - 9.0 / t) > .001)\n            t = (9.0 / t + t) / 2.0;\n        StdOut.printf(\"%.5f\\n\", t);\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex7b.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7b {\n    public static void main(String[] args) {\n        int sum = 0;\n        for(int i = 1; i < 1000; i++)\n            for(int j = 0; j < i; j++)\n                sum++;\n        StdOut.println(sum);\n    }\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex7c.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex7c {\n\n    public static void main(String[] args) {\n        \n        int sum = 0;\n        for(int i = 1; i < 1000; i *= 2)\n            for(int j = 0; j < 1000; j++)\n                sum++;\n        StdOut.println(sum);\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex8.java",
    "content": "package chapter1_1_Programming_Model;\n\npublic class Ex8 {\n\n    public static void main(String[] args) {\n        \n        System.out.println('b');\n        System.out.println('b' + 'c');\n        System.out.println((char)('a' + 4));\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Ex9.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdOut;\n\npublic class Ex9 {\n\n    public static void main(String[] args) {\n        \n        int a = Integer.parseInt(args[0]);\n        String result = \"\";\n        \n        for(int n = a; n > 0; n /= 2) {\n            result = (n % 2) + result;\n        }\n        \n        StdOut.println(result);\n    \n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/RightTriangle.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdDraw;\n\npublic class RightTriangle {\n\n    public static void main(String[] args) {\n        StdDraw.square(.5,  .5,  .5);\n        StdDraw.setPenColor(StdDraw.BLUE);\n        StdDraw.line(.5, .5, .9, .5);\n        StdDraw.line(.9, .5, .5, .8);\n        StdDraw.line(.5, .5, .5, .8);\n        StdDraw.circle(.7, .65, .25);\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/Sattolo.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class Sattolo {\n    \n    private Sattolo() { }\n    \n    public static void cycle(Object[] a) {\n        int n = a.length;\n        for(int i = n; i > 1; i--) {\n            int r = (int)(Math.random() * (i - 1));\n            Object swap = a[r];\n            a[r] = a[i - 1];\n            a[i - 1] = swap;\n        }\n    }\n    \n    public static void main(String[] args) {\n        String[] a = StdIn.readAllStrings();\n        \n        Sattolo.cycle(a);\n        \n        for(int i = 0; i < a.length; i++)\n            StdOut.println(a[i]);\n    }\n}\n"
  },
  {
    "path": "code/chapter1_1_Programming_Model/StdDrawTest.java",
    "content": "package chapter1_1_Programming_Model;\n\nimport java.util.Arrays;\nimport algs4.*;\n\npublic class StdDrawTest {\n\tpublic static void main(String[] args) {\n\t\t// int N = 100;\n\t\t// StdDraw.setXscale(0, N);\n\t\t// StdDraw.setYscale(0, N*N);\n\t\t// StdDraw.setPenRadius(.01);\n\t\t// for(int i = 1; i <= N; i++){\n\t\t// StdDraw.point(i, i);\n\t\t// StdDraw.point(i, i*i);\n\t\t// StdDraw.point(i, i*Math.log(i));\n\t\t// }\n\n\t\tint N = 50;\n\t\tdouble[] a = new double[N];\n\t\tfor (int i = 0; i < N; i++) {\n\t\t\ta[i] = StdRandom.uniform();\n\t\t}\n\t\tArrays.sort(a);\n\t\tfor (int i = 0; i < N; i++) {\n\t\t    double x = 1.0 * i / N;\n\t\t    double y = a[i] / 2.0;\n\t\t    double rw = 0.5 / N;\n\t\t    double rh = a[i] / 2.0;\n\t\t    StdDraw.filledRectangle(x, y, rw, rh);\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Accumulator.java",
    "content": "package chapter1_2_Data_Abstraction;\n\npublic class Accumulator {\n    private double total;\n    private int N;\n    public void addDataValue(double val) {\n        N++;\n        total += val;\n    }\n    public double mean() {\n        return total / N;\n    }\n    public String toString() {\n        return \"Mean (\" + N + \" values): \" + String.format(\"%7.5f\", mean());\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/AccumulatorTest.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class AccumulatorTest {\n\n    public static void main(String[] args) {\n        \n        int T = Integer.parseInt(args[0]);\n        Accumulator a = new Accumulator();\n        for(int t = 0; t < T; t++) {\n            a.addDataValue(StdRandom.uniform());\n        }\n        StdOut.println(a);\n\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Cat.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.In;\nimport algs4.Out;\n\npublic class Cat {\n\n    public static void main(String[] args) {\n        // 将所有输入文件复制到输出流（最后一个参数）中\n        Out out = new Out(args[args.length - 1]);\n        for(int i = 0; i < args.length - 1; i++) {\n            // 将第 i 个输入文件复制到输出流中\n            In in = new In(args[i]);\n            String str = in.readAll();\n            out.println(str);\n            in.close();\n        }\n        out.close();\n\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Date.java",
    "content": "package chapter1_2_Data_Abstraction;\n\npublic class Date {\n    private final int month;\n    private final int day;\n    private final int year;\n    \n    public Date(int m, int d, int y) {\n        this.month = m;\n        this.day = d;\n        this.year = y;\n    }\n    public int month() {\n        return month;\n    }\n    public int day() {\n        return day;\n    }\n    public int year() {\n        return year;\n    }\n    public String toString() {\n        return month() + \"/\" + day() + \"/\" + year();\n    }\n    public boolean equals(Object x) {\n        if(this == x) \n            return true;\n        if(x == null)\n            return false;\n        if(this.getClass() != x.getClass())\n            return false;\n        Date that = (Date) x;\n        if(this.day != that.day)\n            return false;\n        if(this.month != that.month)\n            return false;\n        if(this.year != that.year)\n            return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Flips.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Flips {\n\n    public static void main(String[] args) {\n        \n        int T = Integer.parseInt(args[0]);\n        Counter heads = new Counter(\"heads\");\n        Counter tails = new Counter(\"tails\");\n        for(int t = 0; t < T; t++) {\n            if(StdRandom.bernoulli(.5))\n                heads.increment();\n            else\n                tails.increment();\n        }\n        StdOut.println(heads);\n        StdOut.println(tails);\n        int d = heads.tally() - tails.tally();\n        StdOut.println(\"delta: \" + Math.abs(d));\n        \n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/FlipsMax.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class FlipsMax {\n    \n    public static Counter max(Counter x, Counter y) {\n        if(x.tally() > y.tally()) {\n            return x;\n        }\n        return y;\n    }\n\n    public static void main(String[] args) {\n        int T = Integer.parseInt(args[0]);\n        Counter heads = new Counter(\"heads\");\n        Counter tails = new Counter(\"tails\");\n        for(int t = 0; t < T; t++) {\n            if(StdRandom.bernoulli(.5))\n                heads.increment();\n            else\n                tails.increment();\n        }\n        \n        if(heads.tally() == tails.tally())\n            StdOut.println(\"Tie\");\n        else\n            StdOut.println(max(heads, tails) + \" wins\");\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Interval2DTest.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.Interval1D;\nimport algs4.Interval2D;\nimport algs4.Point2D;\nimport algs4.StdOut;\n\npublic class Interval2DTest {\n\n    public static void main(String[] args) {\n        double xlo = Double.parseDouble(args[0]);\n        double xhi = Double.parseDouble(args[1]);\n        double ylo = Double.parseDouble(args[2]);\n        double yhi = Double.parseDouble(args[3]);\n        int T = Integer.parseInt(args[4]);\n        \n        Interval1D xinterval = new Interval1D(xlo, xhi);\n        Interval1D yinterval = new Interval1D(ylo, yhi);\n        Interval2D box = new Interval2D(xinterval, yinterval);\n        box.draw();\n        \n        Counter c = new Counter(\"hits\");\n        for(int t = 0; t < T; t++) {\n            double x = Math.random();\n            double y = Math.random();\n            Point2D p = new Point2D(x, y);\n            if(box.contains(p))\n                c.increment();\n            else\n                p.draw();\n        }\n        StdOut.println(c);\n        StdOut.println(box.area());\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/Rolls.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.Counter;\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class Rolls {\n\n    public static void main(String[] args) {\n        int T = Integer.parseInt(args[0]);\n        int SIDES = 6;\n        Counter[] rolls = new Counter[SIDES + 1];\n        for(int i = 0; i <= SIDES; i++) {\n            rolls[i] = new Counter(i + \"'s\");\n        }\n        for(int t = 0; t < T; t++) {\n            int result = StdRandom.uniform(1, SIDES + 1);\n            rolls[result].increment();\n        }\n        for(int i = 1; i <= SIDES; i++) {\n            StdOut.println(rolls[i]);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/StaticSETofInts.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport java.util.Arrays;\n\npublic class StaticSETofInts {\n    private int[] a;\n    public StaticSETofInts(int[] keys) {\n        a = new int[keys.length];\n        for(int i = 0; i < keys.length; i++) {\n            a[i] = keys[i];  // 保护性复制\n        }\n        Arrays.sort(a);\n    }\n    public boolean contains(int key) {\n        return rank(key) != -1;\n    }\n    private int rank(int key) {\n        // 二分查找\n        int lo = 0;\n        int hi = a.length;\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            if(key > a[mid]) {\n                lo = mid + 1;\n            } \n            else if(key < a[mid]) {\n                hi = mid - 1;\n            }\n            else {\n                return mid;\n            }\n        }\n        return -1;\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/VisualAccumulator.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdDraw;\n\npublic class VisualAccumulator {\n    private double total;\n    private int N;\n    \n    public VisualAccumulator(int trials, double max) {\n        StdDraw.setXscale(0, trials);\n        StdDraw.setYscale(0, max);\n        StdDraw.setPenRadius(.005);\n    }\n    \n    public void addDataValue(double val) {\n        N++;\n        total += val;\n        StdDraw.setPenColor(StdDraw.DARK_GRAY);\n        StdDraw.point(N, val);\n        StdDraw.setPenColor(StdDraw.RED);\n        StdDraw.point(N, mean());\n    }\n    public double mean() {\n        return total / N;\n    }\n    public String toString() {\n        return \"Mean (\" + N + \" values): \" + String.format(\"%7.5f\", mean());\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class VisualAccumulatorTest {\n\n    public static void main(String[] args) {\n        \n        int T = Integer.parseInt(args[0]);\n        VisualAccumulator a = new VisualAccumulator(T, 1.0);\n        for(int t = 0; t < T; t++) {\n            a.addDataValue(StdRandom.uniform());\n        }\n        StdOut.println(a);\n\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/WhiteList.java",
    "content": "package chapter1_2_Data_Abstraction;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class WhiteList {\n    public static void main(String[] args) {\n        int[] w = In.readInts(args[0]);\n        StaticSETofInts seTofInts = new StaticSETofInts(w);\n        while(!StdIn.isEmpty()) {\n            // 读取键，如果不在白名单中则打印它\n            int key = StdIn.readInt();\n            if(!seTofInts.contains(key))\n                StdOut.println(key);\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/in1.txt",
    "content": "This is"
  },
  {
    "path": "code/chapter1_2_Data_Abstraction/in2.txt",
    "content": "a tiny\ntest."
  },
  {
    "path": "code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java",
    "content": "package chapter1_3_Bags_Queues_Stacks;\n\nimport java.util.Iterator;\n\npublic class ResizingArrayStack<Item> implements Iterable<Item>{\n    private Item[] a = (Item[]) new Object[1];  // 栈元素\n    private int N = 0;\n    public boolean isEmpty() {\n        return N == 0;\n    }\n    public int size() {\n        return N;\n    }\n    public void resize(int max) {\n        // 将栈移动到一个大小为 max 的新数组\n        Item[] temp = (Item[]) new Object[max];\n        for(int i = 0; i < N; i++)\n            temp[i] = a[i];\n        a = temp;\n    }\n    public void push(Item item) {\n        if(N == a.length)\n            resize(2 * a.length);\n        a[N++] = item;\n    }\n    public Item pop() {\n        Item item = a[--N];\n        a[N] = null;\n        if(N > 0 && N == a.length / 4)\n            resize(a.length / 2);\n        return item;\n    }\n    \n    @Override\n    public Iterator<Item> iterator() {\n        return new ReverseArrayIterator();\n    }\n    private class ReverseArrayIterator implements Iterator<Item> {\n        private int i = N;\n        public boolean hasNext() {\n            return i > 0;\n        }\n        public Item next() {\n            return a[--i];\n        }\n        public void remove() {}\n    }\n}\n"
  },
  {
    "path": "code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java",
    "content": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class DoublingRatio {\n\n    public static double timeTrial(int N) {\n        // 为处理 N 个随机的六位整数的 ThreeSum.count() 计时\n        int MAX = 1000000;\n        int[] a = new int[N];\n        for(int i = 0; i < N; i++)\n            a[i] = StdRandom.uniform(-MAX, MAX);\n        Stopwatch timer = new Stopwatch();\n        int cnt = ThreeSum.count(a);\n        return timer.elapsedTime();\n    }\n\n    public static void main(String[] args) {\n        \n        double prev = timeTrial(125);\n        for(int N = 250; true; N *= 2) {\n            double time = timeTrial(N);\n            StdOut.printf(\"%6d %7.1f \", N, time);\n            StdOut.printf(\"%5.1f\\n\", time/prev);\n            prev = time;\n        }\n        \n    }\n    \n}\n"
  },
  {
    "path": "code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java",
    "content": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class DoublingTest {\n    \n    public static double timeTrial(int N) {\n        // 为处理 N 个随机的六位整数的 ThreeSum.count() 计时\n        int MAX = 1000000;\n        int[] a = new int[N];\n        for(int i = 0; i < N; i++)\n            a[i] = StdRandom.uniform(-MAX, MAX);\n        Stopwatch timer = new Stopwatch();\n        int cnt = ThreeSum.count(a);\n        return timer.elapsedTime();\n    }\n\n    public static void main(String[] args) {\n        // 打印运行时间的表格\n        for(int N = 250; true; N *= 2) {\n            double time = timeTrial(N);\n            StdOut.printf(\"%7d %5.1f\\n\", N, time);\n        }\n        \n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java",
    "content": "package chapter1_4_Analysis_of_Algorithms;\n\npublic class Stopwatch {\n    private final long start;\n    public Stopwatch() {\n        start = System.currentTimeMillis();\n    }\n    public double elapsedTime() {\n        long now = System.currentTimeMillis();\n        return (now - start) / 1000.0;\n    }\n}\n"
  },
  {
    "path": "code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java",
    "content": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\npublic class StopwatchTest {\n\n    public static void main(String[] args) {\n    \n        int N = Integer.parseInt(args[0]);\n        int[] a = new int[N];\n        for(int i = 0; i < N; i++)\n            a[i] = StdRandom.uniform(-1000000, 1000000);\n        Stopwatch timer = new Stopwatch();\n        int cnt = ThreeSum.count(a);\n        double time = timer.elapsedTime();\n        StdOut.println(cnt + \" triples \" + time + \" seconds\");\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java",
    "content": "package chapter1_4_Analysis_of_Algorithms;\n\nimport algs4.In;\nimport algs4.StdOut;\n\npublic class ThreeSum {\n    \n    public static int count(int[] a) {\n        int N = a.length;\n        int cnt = 0;\n        for(int i = 0; i < N; i++) \n            for(int j = i + 1; j < N; j++)\n                for(int k = j + 1; k < N; k++)\n                    if(a[i] + a[j] + a[k] == 0)\n                        cnt++;\n        return cnt;\n    }\n\n    public static void main(String[] args) {\n        int[] a = In.readInts(args[0]);\n        StdOut.println(count(a));\n    }\n\n}\n"
  },
  {
    "path": "code/chapter1_5_Case_Study_Union_Find/UF.java",
    "content": "package chapter1_5_Case_Study_Union_Find;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class UF {\n    private int[] id; // 分量id（以触点作为索引）\n    private int count; // 分量数量\n\n    public UF(int N) {\n        // 初始化分量 id 数组\n        count = N;\n        id = new int[N];\n        for (int i = 0; i < N; i++)\n            id[i] = i;\n    }\n\n    public int count() {\n        return count;\n    }\n\n    public boolean connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    /* quick-find 算法 */\n//    public int find(int p) {\n//        return id[p];\n//    }\n//\n//    public void union(int p, int q) {\n//        // 将 p 和 q 归并到同样的分量中\n//        int pID = find(p);\n//        int qID = find(q);\n//        \n//        // 如果 p 和 q 已经在相同的分量之中则不需要采取任何行动\n//        if(pID == qID)\n//            return;\n//        \n//        // 将 p 的分量重命名为 q 的名称\n//        for(int i = 0; i < id.length; i++)\n//            if(id[i] == pID)\n//                id[i] = qID;\n//        count--;\n//    }\n    \n    /* quick-union 算法 */\n    private int find(int p) {\n        // 找出分量的名称\n        while(p != id[p])\n            p = id[p];\n        return p;\n    }\n    \n    private void union(int p, int q) {\n        // 将 p 和 q 的根节点统一\n        int pRoot = find(p);\n        int qRoot = find(q);\n        if(pRoot == qRoot)\n            return;\n        \n        id[pRoot] = qRoot;\n        \n        count--;\n    }\n\n    public static void main(String[] args) {\n        // 解决由StdIn得到的动态连通性问题\n        int N = StdIn.readInt();    // 读取触点数量\n        UF uf = new UF(N);    // 初始化 N 个分量\n        while (!StdIn.isEmpty()) {\n            int p = StdIn.readInt();\n            int q = StdIn.readInt();    // 读取整数对\n            if (uf.connected(p, q))     // 如果已经连通则忽略\n                continue;\n            uf.union(p, q);    // 归并分量\n            StdOut.println(p + \" \" + q);    // 打印连接\n        }\n        StdOut.println(uf.count + \"components\");\n    }\n}\n"
  },
  {
    "path": "code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java",
    "content": "package chapter1_5_Case_Study_Union_Find;\n\n/**\n * 加权 quick-union 算法\n * @author huang\n */\npublic class WeightedQuickUnionUF {\n    private int[] id;    // 父链接数组（由触点索引）\n    private int[] sz;    // （由触点索引的）各个根节点所对应的分量的大小\n    private int count;    // 连通分量的数量 \n    \n    public WeightedQuickUnionUF(int N) {\n        count = N;\n        id = new int[N];\n        for(int i = 0; i < N; i++)\n            id[i] = i;\n        sz = new int[N];\n        for(int i = 0; i < N; i++)\n            sz[i] = 1;\n    }\n    \n    public int count() {\n        return count;\n    }\n    \n    public boolean connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    public int find(int p) {\n        // 跟随链接找到根节点\n        while(p != id[p])\n            p = id[p];\n        return p;\n    }\n    \n    public void union(int p, int q) {\n        int pRoot = find(p);\n        int qRoot = find(q);\n        if(pRoot == qRoot)\n            return;\n        // 将小树的根节点连接到大树的根节点\n        if(sz[pRoot] < sz[qRoot]) {\n            id[pRoot] = qRoot;\n            sz[qRoot] += sz[pRoot];\n        }\n        else {\n            id[qRoot] = pRoot;\n            sz[pRoot] += sz[qRoot];\n        }\n        count--;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_1_Elementary_Sorts/Insertion.java",
    "content": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 插入排序\n * @author huang\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Insertion {\n    public static void sort(Comparable[] a) {\n        // 将 a[] 按升序排列\n        int N = a.length;\n        for(int i = 1; i < N; i++) {\n            // 将 a[i] 插入到 a[i-1]、a[i-2]、a[i-3]...之中   \n            /** 有改进空间，见练习 2.1.25  */\n            for(int j = i; j > 0 && less(a[j], a[j-1]); j--)\n                exch(a, j, j-1);\n        }\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_1_Elementary_Sorts/Selection.java",
    "content": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 选择排序\n * @author huang\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Selection {\n    public static void sort(Comparable[] a) {\n        // 将 a[] 按升序排列\n        int N = a.length;\n        for(int i = 0 ; i < N; i++) {\n            // 将 a[i] 和 a[i...N]中最小的元素交换\n            int min = i;    // 最小元素的索引\n            for(int j = i+1; j < N; j++)\n                if(less(a[j], a[min]))\n                    min = j;\n            exch(a, i, min);\n        }\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_1_Elementary_Sorts/Shell.java",
    "content": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\n\n/**\n * 希尔排序\n * @author huang\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Shell {\n    public static void sort(Comparable[] a) {\n        // 将 a[] 按升序排列\n        int N = a.length;\n        int h = 1;\n        while(h < N / 3)\n            h = 3 * h + 1;    // 1, 4, 13, 40, 121, 364, 1093, ...\n        while(h >= 1) {\n            // 将数组变为 h 有序\n            for(int i = h; i < N; i++) {\n                // 将 a[i] 插入到 a[i-h]，a[i-2*h]，a[i-3*h]... 之中\n                for(int j = i; j >= h && less(a[j], a[j -h]); j -= h)\n                    exch(a, j, j-h);\n            }\n            h /= 3;\n        }\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_1_Elementary_Sorts/SortCompare.java",
    "content": "package chapter2_1_Elementary_Sorts;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\nimport chapter1_4_Analysis_of_Algorithms.Stopwatch;\n\n/**\n * @author huang\n * 比较两种排序算法\n */\n@SuppressWarnings({\"rawtypes\"})\npublic class SortCompare {\n    public static double time(String alg, Comparable[] a) {\n        Stopwatch timer = new Stopwatch();\n        if(alg.equals(\"Insertion\"))\n            Insertion.sort(a);\n        if(alg.equals(\"Selection\"))\n            Selection.sort(a);\n        if(alg.equals(\"Shell\"))\n            Shell.sort(a);\n//        if(alg.equals(\"Merge\"))\n//            Merge.sort(a);\n//        if(alg.equals(\"Quick\"))\n//            Quick.sort(a);\n//        if(alg.equals(\"Heap\"))\n//            Heap.sort(a);\n        return timer.elapsedTime();\n    }\n    \n    public static double timeRandomInput(String alg, int N, int T) {\n        // 使用算法 alg 将 T 个长度为 N 的数组排序\n        double total = 0.0;\n        Double[] a = new Double[N];\n        for(int t = 0; t < T; t++) {\n            // 进行一次测试（生成一个数组并排序）\n            for(int i = 0; i < N; i ++)\n                a[i] = StdRandom.uniform();    /** 练习 2.5.31 */\n            total += time(alg, a);\n        }\n        return total;\n    }\n    \n    public static void main(String[] args) {\n        String alg1 = args[0];\n        String alg2 = args[1];\n        int N = Integer.parseInt(args[2]);\n        int T = Integer.parseInt(args[3]);\n        double t1 = timeRandomInput(alg1, N, T);    // 算法 1 的总时间\n        double t2 = timeRandomInput(alg2, N, T);    // 算法 2 的总时间\n        StdOut.printf(\"For %d random Doubles\\n    %s is\", N, alg1);\n        StdOut.printf(\" %.1f times faster than %s\\n\", t2/t1, alg2);\n    }\n}\n"
  },
  {
    "path": "code/chapter2_2_Mergesort/Merge.java",
    "content": "package chapter2_2_Mergesort;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 自顶向下的归并排序\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Merge {\n    private static Comparable[] aux;    // 归并所需的辅助数组\n    \n    public static void sort(Comparable[] a) {\n        aux = new Comparable[a.length];\n        sort(a, 0, a.length - 1);\n    }\n    \n    private static void sort(Comparable[] a, int lo, int hi) {\n        // 将数组 a[lo..hi] 排序\n        if(hi <= lo)\n            return;\n        int mid = lo + (hi - lo) / 2;\n        sort(a, lo, mid);    // 将左半边排序\n        sort(a, mid + 1, hi);    // 将右半边排序\n        if(less(a[mid+1], a[mid]))    // 为 false 则认为数组已经是有序的，跳过 merge()\n            merge(a, lo, mid, hi);    // 归并结果\n    }\n    \n    public static void merge(Comparable[] a, int lo, int mid, int hi) {\n        // 将 a[lo..mid] 和 a[mid+1..hi] 归并\n        int i = lo, j = mid + 1;\n        \n        for(int k = lo; k <= hi; k++)    // 将 a[lo..hi] 复制到 aux[lo..hi]\n            aux[k] = a[k];\n        \n        for(int k = lo; k <= hi; k++)\n            if(i > mid)    // 左半边元素用尽\n                a[k] = aux[j++];\n            else if(j > hi)    // 右半边元素用尽\n                a[k] = aux[i++];\n            else if(less(aux[i], aux[j]))\n                a[k] = aux[i++];\n            else\n                a[k] = aux[j++];               \n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_2_Mergesort/MergeBU.java",
    "content": "package chapter2_2_Mergesort;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 自底向上的归并排序\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class MergeBU {\n    private static Comparable[] aux;    // 归并所需的辅助数组\n    \n    public static void sort(Comparable[] a) {\n        // 进行 lgN 次两两归并\n        int N = a.length;\n        aux = new Comparable[N];\n        for(int sz = 1; sz < N; sz = sz+sz)\n            for(int lo = 0; lo < N - sz; lo += sz+sz)\n                merge(a, lo, lo+sz-1, Math.min(lo+sz+sz-1, N-1));    // 最后一个子数组的大小只有在数组大小是 sz 的偶数倍时才会等于 sz，否则小于 sz\n    }\n    \n    public static void merge(Comparable[] a, int lo, int mid, int hi) {\n        // 将 a[lo..mid] 和 a[mid+1..hi] 归并\n        int i = lo, j = mid + 1;\n        \n        for(int k = lo; k <= hi; k++)    // 将 a[lo..hi] 复制到 aux[lo..hi]\n            aux[k] = a[k];\n        \n        for(int k = lo; k <= hi; k++)\n            if(i > mid)    // 左半边元素用尽\n                a[k] = aux[j++];\n            else if(j > hi)    // 右半边元素用尽\n                a[k] = aux[i++];\n            else if(less(aux[i], aux[j]))\n                a[k] = aux[i++];\n            else\n                a[k] = aux[j++];               \n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_3_Quicksort/Ex25.java",
    "content": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\nimport chapter1_4_Analysis_of_Algorithms.Stopwatch;\nimport chapter1_4_Analysis_of_Algorithms.ThreeSum;\nimport chapter2_1_Elementary_Sorts.Insertion;\nimport chapter2_1_Elementary_Sorts.SortCompare;\n\n/**\n * 快速排序切换到插入排序\n * @author huang\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Ex25 {\n    public static void main(String[] args) {\n        \n        for(int N = 1000; N <= 1000000; N *= 10) {\n            Comparable[] a = new Comparable[N];\n            for(int i = 0; i < N; i++)\n                a[i] = StdRandom.uniform(-1000000, 1000000);\n            for(int M = 0; M <= 30; M++) {\n                Comparable[] b = a.clone();\n                Stopwatch timer = new Stopwatch();\n                sort(b, 1);\n                double time = timer.elapsedTime();\n                StdOut.println(\"Array size: \" + N + \", M = \" + M + \", time: \" + time + \" seconds\");\n            }\n        }\n    }\n    \n    public static void sort(Comparable[] a, int M) {\n        StdRandom.shuffle(a);    // 消除对输入的依赖\n        sort(a,0, a.length - 1, M);\n    }\n    \n    private static void sort(Comparable[] a, int lo, int hi, int M) {\n        if(hi <= lo + M) {\n            insertSort(a, lo, hi);\n            return;\n        }\n        int j = partition(a, lo, hi);    // 切分\n        sort(a, lo, j-1, M);    // 将左半部分 a[lo .. j-1]\n        sort(a, j+1, hi, M);    // 将右半部分 a[j+1 .. hi]\n    }\n    \n    private static void insertSort(Comparable[] a, int lo, int hi) {\n        int N = a.length;\n        for(int i = lo; i < hi+1; i++) {\n            for(int j = i; j > 0 && less(a[j], a[j-1]); j--)\n                exch(a, j, j-1);\n        }\n    }\n    \n    private static int partition(Comparable[] a, int lo, int hi) {\n        // 将数组切分为 a[lo .. i-1]，a[i]，a[i+1 .. hi]\n        int i = lo, j = hi+1;    // 左右扫描指针\n        Comparable v = a[lo];    // 切分元素\n        while(true) {\n            // 扫描左右，检查扫描是否结束并交换元素\n            while(less(a[++i], v))\n                if(i == hi)\n                    break;\n            while(less(v, a[--j]))\n                if(j == lo)\n                    break;\n            if(i >= j)\n                break;\n            exch(a, i, j);\n        }\n        exch(a, lo, j);\n        return j;\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_3_Quicksort/Quick.java",
    "content": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\n/**\n * @author huang\n * 快速排序\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Quick {\n    public static void sort(Comparable[] a) {\n        StdRandom.shuffle(a);    // 消除对输入的依赖\n        sort(a,0, a.length - 1);\n    }\n    \n    private static void sort(Comparable[] a, int lo, int hi) {\n        if(hi <= lo)\n            return;\n        int j = partition(a, lo, hi);    // 切分\n        sort(a, lo, j-1);    // 将左半部分 a[lo .. j-1]\n        sort(a, j+1, hi);    // 将右半部分 a[j+1 .. hi]\n    }\n    \n    private static int partition(Comparable[] a, int lo, int hi) {\n        // 将数组切分为 a[lo .. i-1]，a[i]，a[i+1 .. hi]\n        int i = lo, j = hi+1;    // 左右扫描指针\n        Comparable v = a[lo];    // 切分元素\n        while(true) {\n            // 扫描左右，检查扫描是否结束并交换元素\n            while(less(a[++i], v))\n                if(i == hi)\n                    break;\n            while(less(v, a[--j]))\n                if(j == lo)\n                    break;\n            if(i >= j)\n                break;\n            exch(a, i, j);\n        }\n        exch(a, lo, j);\n        return j;\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_3_Quicksort/Quick3way.java",
    "content": "package chapter2_3_Quicksort;\n\nimport algs4.StdOut;\nimport algs4.StdRandom;\n\n/**\n * @author huang\n * 三向切分的快速排序\n */\n@SuppressWarnings({\"rawtypes\", \"unused\", \"unchecked\"})\npublic class Quick3way {\n    public static void sort(Comparable[] a) {\n        StdRandom.shuffle(a);    // 消除对输入的依赖\n        sort(a,0, a.length - 1);\n    }\n    \n    private static void sort(Comparable[] a, int lo, int hi) {\n        if(hi <= lo)\n            return;\n        int lt = lo, i = lo+1, gt = hi;     // lt: b 开始, gt: b 结束, i: c 开始\n        Comparable v = a[lo];\n        while(i <= gt) {\n            int cmp = a[i].compareTo(v);\n            if(cmp < 0)\n                exch(a, lt++, i++);\n            else if(cmp > 0)\n                exch(a, i, gt--);\n            else \n                i++;\n        }    // 现在 a[lo .. lt-1] < v = a[lt .. gt] < a[gt+1 .. hi] 成立\n        sort(a, lo, lt - 1);\n        sort(a, gt + 1, hi);\n    }\n    \n    private static int partition(Comparable[] a, int lo, int hi) {\n        // 将数组切分为 a[lo .. i-1]，a[i]，a[i+1 .. hi]\n        int i = lo, j = hi+1;    // 左右扫描指针\n        Comparable v = a[lo];    // 切分元素\n        while(true) {\n            // 扫描左右，检查扫描是否结束并交换元素\n            while(less(a[++i], v))\n                if(i == hi)\n                    break;\n            while(less(v, a[--j]))\n                if(j == lo)\n                    break;\n            if(i >= j)\n                break;\n            exch(a, i, j);\n        }\n        exch(a, lo, j);\n        return j;\n    }\n    \n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n}\n"
  },
  {
    "path": "code/chapter2_4_Priority_Queues/MaxPQ.java",
    "content": "package chapter2_4_Priority_Queues;\n\n/**\n * 基于堆的优先队列\n * \n * @author huang\n */\npublic class MaxPQ<Key extends Comparable<Key>> {\n\n    private Key[] pq; // 基于堆的完全二叉树\n    private int N = 0; // 存储于 pq[1 .. N] 中，pq[0] 没有使用\n\n    @SuppressWarnings(\"unchecked\")\n    MaxPQ(int maxN) { // 创建一个初始容量为 max 的优先队列\n        pq = (Key[]) new Comparable[maxN + 1];\n    }\n\n    // 向优先队列中插入一个元素\n    void insert(Key v) { \n        pq[++N] = v;\n        swim(N);\n    }\n\n    // 删除并返回最大元素\n    public Key delMax() { \n        Key max = pq[1];    // 从根结点得到最大元素\n        exch(1, N--);    // 将其和最后一个结点交换\n        pq[N+1] = null;    // 防止对象游离\n        sink(1);    // 恢复堆的有序性\n        return max;\n    }\n\n    boolean isEmpty() { // 返回队列是否为空\n        return N == 0;\n    }\n\n    int size() { // 返回优先队列中的元素个数\n        return N;\n    }\n\n    private boolean less(int i, int j) {\n        return pq[i].compareTo(pq[j]) < 0;\n    }\n\n    private void exch(int i, int j) {\n        Key t = pq[i];\n        pq[i] = pq[j];\n        pq[j] = t;\n    }\n\n    // 由下至上的堆有序化（上浮）的实现\n    private void swim(int k) {\n        while(k > 1 && less(k/2, k)) {\n            exch(k/2, k);\n            k = k/2;\n        }\n    }\n\n    // 由上至下的堆有序化（下沉）的实现\n    private void sink(int k) {\n        while(2 * k <= N) {\n            int j = 2 * k;\n            if(j < N && less(j, j+1))\n                j++;\n            if(!less(k, j))\n                break;\n            exch(k, j);\n            k = j;\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter2_4_Priority_Queues/TopM.java",
    "content": "package chapter2_4_Priority_Queues;\n\nimport algs4.MinPQ;\nimport algs4.Stack;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class TopM {\n    public static void main(String[] args) {\n        // 打印输入流中最大的 M 行\n        int M = Integer.parseInt(args[0]);\n        MinPQ<Transaction> pq = new MinPQ<>(M+1);\n        while(StdIn.hasNextLine()) {\n            // 为下一行输入创建一个元素并放入优先队列中\n            pq.insert(new Transaction(StdIn.readLine()));\n            if(pq.size() > M)\n                pq.delMin();    // 如果优先队列中存在 M+1 \n        }    // 最大的 M 个元素都在优先队列中\n        \n        Stack<Transaction> stack = new Stack<Transaction>();\n        while(!pq.isEmpty()) \n            stack.push(pq.delMin());\n        for(Transaction t : stack)\n            StdOut.println(t);\n    }\n}\n"
  },
  {
    "path": "code/chapter3_1_Symbol_Tables/BinarySearchST.java",
    "content": "package chapter3_1_Symbol_Tables;\n\nimport algs4.Queue;\n\n@SuppressWarnings(\"unchecked\")\npublic class BinarySearchST<Key extends Comparable<Key>, Value> {\n    private Key[] keys;\n    private Value[] vals;\n    private int N;\n    public BinarySearchST(int capacity) {\n        keys = (Key[]) new Comparable[capacity];\n        vals = (Value[]) new Object[capacity];\n    }\n    \n    private void resize(int max) {\n        // 将栈移动到一个大小为 max 的新数组\n        Key[] tempKeys = (Key[]) new Comparable[max];\n        Value[] tempValues = (Value[]) new Object[max];\n        for(int i = 0; i < N; i++) {\n            tempKeys[i] = keys[i];\n            tempValues[i] = vals[i];\n        }\n        keys = tempKeys;\n        vals = tempValues;\n    }\n    \n    public int size() {\n        return N;\n    }\n    \n    public Value get(Key key) {\n        if(isEmpty()) \n            return null;\n        int i = rank(key);\n        if(i < N && keys[i].compareTo(key) == 0)\n            return vals[i];\n        else\n            return null;\n    }\n    \n    public boolean isEmpty() {\n        return N == 0;\n    }\n    \n    public int rank(Key key) {\n        int lo = 0, hi = N-1;\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            int cmp = key.compareTo(keys[mid]);\n            if(cmp < 0)\n                hi = mid - 1;\n            else if(cmp > 0)\n                lo = mid + 1;\n            else\n                return mid;\n        }\n        return lo;\n    }\n    \n    public void put(Key key, Value val) {\n        // 查找键，找到则更新值，否则创建新的元素\n        int i = rank(key);\n        if(i < N && keys[i].compareTo(key) == 0) {\n            vals[i] = val;\n            return;\n        }\n        if(N == keys.length)    // 调整数组大小\n            resize(2 * keys.length);\n        for(int j = N; j > i; j--) {\n            keys[j] = keys[j-1];\n            vals[j] = vals[j-1];\n        }\n        keys[i] = key;\n        vals[i] = val;\n        N++;\n    }\n    \n    public Key min() {\n        return keys[0];\n    }\n    \n    public Key max() {\n        return keys[N-1];\n    }\n    \n    public Key select(int k) {\n        return keys[k];\n    }\n    \n    public Key ceiling(Key key) {\n        int i = rank(key);\n        return keys[i];\n    }\n    \n//    public Key floor(Key key) {\n//        \n//    }\n    \n    public Key delete(Key key) {\n        int i = rank(key);\n        if(!(i < N && keys[i].compareTo(key) == 0)) {\n            return null;\n        }\n        if(N < keys.length / 2)    // 调整数组大小\n            resize(keys.length / 2);\n        for(int j = i; j < N; j++) {\n            keys[j] = keys[j+1];\n            vals[j] = vals[j+1];\n        }\n        keys[N] = null;\n        vals[N] = null;\n        N--;\n        return key;\n    }\n    \n    public Iterable<Key> keys(Key lo, Key hi) {\n        Queue<Key> q = new Queue<Key>();\n        for(int i = rank(lo); i < rank(hi); i++)\n            q.enqueue(keys[i]);\n        if(contains(hi))\n            q.enqueue(keys[rank(hi)]);\n        return q;\n    }\n    \n    public boolean contains(Key key) {\n        int i = rank(key);\n        return i < N && keys[i].compareTo(key) == 0;\n    }\n}\n"
  },
  {
    "path": "code/chapter3_1_Symbol_Tables/FrequencyCounter.java",
    "content": "package chapter3_1_Symbol_Tables;\n\nimport algs4.ST;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * 符号表的用例\n * @author huang\n */\npublic class FrequencyCounter {\n    public static void main(String[] args) {\n        int minlen = Integer.parseInt(args[0]);    // 最小键长\n        ST<String, Integer> st = new ST<String, Integer>();\n        while(!StdIn.isEmpty()) {\n            // 构造符号表并统计频率\n            String word = StdIn.readString();\n            if(word.length() < minlen)\n                continue;    // 忽略较短的单词\n            if(!st.contains(word))\n                st.put(word, 1);\n            else\n                st.put(word, st.get(word)+1);\n        }\n        // 找出出现频率最高的单词\n        String max = \" \";\n        st.put(max, 0);\n        for(String word : st.keys())\n            if(st.get(word) > st.get(max))\n                max = word;\n        StdOut.println(max + \" \" + st.get(max));\n    }\n}\n"
  },
  {
    "path": "code/chapter3_1_Symbol_Tables/SequentialSearchST.java",
    "content": "package chapter3_1_Symbol_Tables;\n\npublic class SequentialSearchST<Key, Value>{\n    private Node first;    // 链表首结点\n    private class Node {\n        Key key;\n        Value val;\n        Node next;\n        public Node(Key key, Value val, Node next) {\n            this.key = key;\n            this.val = val;\n            this.next = next;\n        }\n    }\n    \n    public Value get(Key key) {\n        // 查找给定的键，返回相关联的值\n        for(Node x = first; x != null; x = x.next)\n            if(key.equals(x.key))\n                return x.val;    // 命中\n        return null;    // 未命中\n    }\n    \n    public void put(Key key, Value val) {\n        // 查找给定的键，找到则更新其值，否则在表中新建结点\n        for(Node x = first; x != null; x = x.next)\n            if(key.equals(x.key)) {\n                x.val = val;\n                return;    // 命中，更新\n            }\n        first = new Node(key, val, first);    // 未命中，新建结点\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter3_2_Binary_Search_Trees/BST.java",
    "content": "package chapter3_2_Binary_Search_Trees;\n\nimport algs4.Queue;\n\npublic class BST<Key extends Comparable<Key>, Value> {\n    private Node root;    // 二叉查找树的根结点\n    \n    private class Node {\n        private Key key;    // 键\n        private Value val;    // 值\n        private Node left, right;    // 指向子树的链接\n        private int N;    // 以该结点为根的子树中的结点总数\n        \n        public Node(Key key, Value val, int N) {\n            this.key = key;\n            this.val = val;\n            this.N = N;\n        }\n    }\n    \n    public int size() {\n        return size(root);\n    }\n    \n    private int size(Node x) {\n        if(x == null)\n            return 0;\n        else\n            return x.N;\n    }\n    \n    public Value get(Key key) {\n        return get(root, key);\n    }\n    \n    private Value get(Node x, Key key) {\n        // 在以 x 为根结点的子树中查找并返回 key 所对应的值\n        if(x == null)\n            return null;\n        int cmp = key.compareTo(x.key);\n        if(cmp < 0)\n            return get(x.left, key);\n        else if(cmp > 0)\n            return get(x.right, key);\n        else\n            return x.val;\n    }\n    \n    public void put(Key key, Value val) {\n        // 查找 key，找到则更新它的值，否则为它创建一个新的结点\n        root = put(root, key, val);\n    }\n    \n    private Node put(Node x, Key key, Value val) {\n        // 如果 key 存在于以 x 为根结点的子树中则更新它的值；\n        // 否则将以 key 和 val 为键值对的新结点插入到该子树中\n        if(x == null)\n            return new Node(key, val, 1);\n        int cmp = key.compareTo(x.key);\n        if(cmp < 0)\n            x.left = put(x.left, key, val);\n        else if(cmp > 0)\n            x.right = put(x.right, key, val);\n        else\n            x.val = val;\n        x.N = size(x.left) + size(x.right) + 1;\n        return x;\n    }\n    \n    public Key min() {\n        return min(root).key;\n    }\n    \n    private Node min(Node x) {\n        if(x.left == null)\n            return x;\n        return min(x.left);\n    }\n    \n    public Key max() {\n        return max(root).key;\n    }\n    \n    private Node max(Node x) {\n        if(x.right == null)\n            return x;\n        return min(x.right);\n    }\n    \n    public Key floor(Key key) {\n        Node x = floor(root, key);\n        if(x == null)\n            return null;\n        return x.key;\n    }\n    \n    private Node floor(Node x, Key key) {\n        if(x == null)\n            return null;\n        int cmp = key.compareTo(x.key);\n        if(cmp == 0)\n            return x;\n        if(cmp < 0)\n            return floor(x.left, key);\n        Node t = floor(x.right, key);\n        if(t != null)\n            return t;\n        else\n            return x;\n    }\n    \n    public Key select(int k) {\n        return select(root, k).key;\n    }\n    \n    private Node select(Node x, int k) {\n        // 返回排名为 k 的结点\n        if(x == null)\n            return null;\n        int t = size(x.left);\n        if(t > k)\n            return select(x.left, k);\n        else if(t < k)\n            return select(x.right, k-t-1);\n        else\n            return x;\n    }\n    \n    public int rank(Key key) {\n        return rank(key, root);\n    }\n    \n    private int rank(Key key, Node x) {\n        // 返回以 x 为根结点的子树中小于 x.key 的键的数量\n        if(x == null)\n            return 0;\n        int cmp = key.compareTo(x.key);\n        if(cmp < 0)\n            return rank(key, x.left);\n        else if(cmp > 0)\n            return 1 + size(x.left) + rank(key, x.left);\n        else\n            return size(x.left);\n    }\n    \n    public void deleteMin() {\n        root = deleteMin(root);\n    }\n    \n    private Node deleteMin(Node x) {\n        if(x.left == null)\n            return x.right;\n        x.left = deleteMin(x.left);\n        x.N = size(x.left) + size(x.right) + 1;\n        return x;\n    }\n    \n    public void delete(Key key) {\n        root = delete(root, key);\n    }\n    \n    private Node delete(Node x, Key key) {\n        if(x == null)\n            return null;\n        int cmp = key.compareTo(x.key);\n        if(cmp < 0)\n            x.left = delete(x.left, key);\n        else if(cmp > 0)\n            x.right = delete(x.right, key);\n        else {\n            if(x.right == null)\n                return x.left;\n            if(x.left == null)\n                return x.right;\n            Node t = x;\n            x = min(t.right);\n            x.right = deleteMin(t.right);\n            x.left = t.left;\n        }\n        x.N = size(x.left) + size(x.right) + 1;\n        return x;\n    }\n    \n    public Iterable<Key> keys() {\n        return keys(min(), max());\n    }\n    \n    public Iterable<Key> keys(Key lo, Key hi) {\n        Queue<Key> queue = new Queue<Key>();\n        keys(root, queue, lo, hi);\n        return queue;\n    }\n    \n    private void keys(Node x, Queue<Key> queue, Key lo, Key hi) {\n        if(x == null)\n            return;\n        int cmplo = lo.compareTo(x.key);\n        int cmphi = hi.compareTo(x.key);\n        if(cmplo < 0)\n            keys(x.left, queue, lo, hi);\n        if(cmplo <= 0 && cmplo >= 0)\n            queue.enqueue(x.key);\n        if(cmphi > 0)\n            keys(x.right, queue, lo, hi);\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter3_4_Hash_Tables/LinearProbingHashST.java",
    "content": "package chapter3_4_Hash_Tables;\n\nimport algs4.Queue;\n\n@SuppressWarnings(\"unchecked\")\npublic class LinearProbingHashST<Key, Value> {\n    private int N;    // 符号表中键值对的总数\n    private int M = 16;    // 线性探测表的大小\n    private Key[] keys;    // 键\n    private Value[] vals;    // 值\n    \n    public LinearProbingHashST() {\n        keys = (Key[]) new Object[M];\n        vals = (Value[]) new Object[M];\n    }\n    \n    public LinearProbingHashST(int cap) {\n        this.M = cap;\n        keys = (Key[]) new Object[M];\n        vals = (Value[]) new Object[M];\n    }\n    \n    public int size() {\n        return this.M;\n    }\n    \n    private int hash(Key key) {\n        return (key.hashCode() & 0x7fffffff) % M;\n    }\n    \n    private void resize(int cap) {\n        LinearProbingHashST<Key, Value> t;\n        t = new LinearProbingHashST<Key, Value>(cap);\n        for(int i = 0; i < M; i++)\n            if(keys[i] != null)\n                t.put(keys[i], vals[i]);\n        keys = t.keys;\n        vals = t.vals;\n        M = t.M;\n    }\n    \n    public void put(Key key, Value val) {\n        if(N >= M/2)\n            resize(2 * M);\n        int i;\n        for(i = hash(key); keys[i] != null; i = (i + 1) % M)\n            if(keys[i].equals(key)) {\n                vals[i] = val;\n                return;\n            }\n            keys[i] = key;\n            vals[i] = val;\n            N++;\n    }\n    \n    public Value get(Key key) {\n        for(int i = hash(key); keys[i] != null; i = (i + 1) % M)\n            if(keys[i].equals(key))\n                return vals[i];\n        return null;\n    }\n    \n    public boolean contains(Key key) {\n        return get(key) != null;\n    }\n    \n    public void delete(Key key) {\n        if(!contains(key))\n            return;\n        int i = hash(key);\n        while(!key.equals(keys[i]))\n            i = (i + 1) % M;\n        keys[i] = null;\n        vals[i] = null;\n        i = (i + 1) % M;\n        while(keys[i] != null) {\n            Key keyToRedo = keys[i];\n            Value valToRedo = vals[i];\n            keys[i] = null;\n            vals[i] = null;\n            N--;\n            put(keyToRedo, valToRedo);\n            i = (i + 1) % M;\n        }\n        N--;\n        if(N > 0 && N == M/8)\n            resize(M/2);\n    }\n    \n    public Iterable<Key> keys() {\n        Queue<Key> queue = new Queue<Key>();\n        for(int i = 0; i < M; i++)\n            if(keys[i] != null)\n                queue.enqueue(keys[i]);\n        return queue;\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter3_4_Hash_Tables/SeparateChainingHashST.java",
    "content": "package chapter3_4_Hash_Tables;\n\nimport java.util.Iterator;\n\nimport algs4.Queue;\nimport chapter3_1_Symbol_Tables.SequentialSearchST;\n\n@SuppressWarnings(\"unchecked\")\npublic class SeparateChainingHashST<Key, Value> {\n    private int N;    // 键值对总数\n    private int M;    // 散列表的大小\n    private SequentialSearchST<Key, Value>[] st;    // 存放链表对象的数组\n    \n    public SeparateChainingHashST() {\n        this(997);\n    }\n    \n    public SeparateChainingHashST(int M) {\n        // 创建 M 条链表\n        this.M = M;\n        st = (SequentialSearchST<Key, Value>[]) new SequentialSearchST[M];\n        for(int i = 0; i < M; i++)\n            st[i] = new SequentialSearchST<Key, Value>();\n    }\n    \n    private int hash(Key key) {\n        return (key.hashCode() & 0x7fffffff) % M;\n    }\n    \n    public Value get(Key key) {\n        return (Value) st[hash(key)].get(key);\n    }\n    \n    public void put(Key key, Value val) {\n        st[hash(key)].put(key, val);\n    }\n    \n    public Iterable<Key> keys() {\n        Queue<Key> queue = new Queue<>();\n        for(int i = 0; i < M; i++)\n            for(Iterator<Key> iter = (Iterator<Key>) st[i].keys(); iter.hasNext();)\n                queue.enqueue(iter.next());\n        return queue;\n    }\n}\n"
  },
  {
    "path": "code/chapter3_5_Searching_Applications/SparseVector.java",
    "content": "package chapter3_5_Searching_Applications;\n\nimport chapter3_4_Hash_Tables.LinearProbingHashST;\n\n/**\n * @author huang\n * 能够完成点乘的稀疏向量\n */\npublic class SparseVector {\n    private LinearProbingHashST<Integer, Double> st;\n    public SparseVector() {\n        st = new LinearProbingHashST<Integer, Double>();\n    }\n    public int size() {\n        return st.size();\n    }\n    public void put(int i, double x) {\n        st.put(i, x);\n    }\n    public double get(int i) {\n        if(!st.contains(i))\n            return 0.0;\n        return st.get(i);\n    }\n    public double dot(double[] that) {\n        double sum = 0.0;\n        for(int i : st.keys())\n            sum += that[i] * this.get(i);\n        return sum;\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter3_5_Searching_Applications/WhiteFilter.java",
    "content": "package chapter3_5_Searching_Applications;\n\nimport java.util.HashSet;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 白名单过滤器\n */\npublic class WhiteFilter {\n    public static void main(String[] args) {\n        HashSet<String> set;\n        set = new HashSet<String>();\n        In in = new In(args[0]);\n        while(!in.isEmpty())\n            set.add(in.readString());\n        while(!StdIn.isEmpty()) {\n            String word = StdIn.readString();\n            if(set.contains(word))\n                StdOut.print(word + \" \");\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Queue;\nimport algs4.Stack;\n\npublic class BreadthFirstPaths {\n    private boolean[] marked;  // 到达该顶点的最短路径已知吗？\n    private int[] edgeTo;  // 到达该顶点的已知路径上的最后一个顶点\n    private final int s;  // 起点\n    \n    public BreadthFirstPaths(Graph G, int s) {\n        marked = new boolean[G.V()];\n        edgeTo = new int[G.V()];\n        this.s = s;\n        bfs(G, s);\n    }\n    \n    private void bfs(Graph G, int s) {\n        Queue<Integer> queue = new Queue<Integer>();\n        marked[s] = true;  // 标记起点\n        queue.enqueue(s);  // 将它加入队列\n        while(!queue.isEmpty()) {\n            int v = queue.dequeue();  // 从队列中删去下一顶点\n            for(int w : G.adj(v))\n                if(!marked[w]) {\n                    edgeTo[w] = v;  // 保存最短路径的最后一条边\n                    marked[w] = true;  // 标记它，因为最短路径已知\n                    queue.enqueue(w);  // 并将它添加到队列中\n                }\n        }\n    }\n    \n    public boolean hasPathTo(int v) {\n        return marked[v];\n    }\n    \n    public Iterable<Integer> pathTo(int v) {\n        if(!hasPathTo(v))\n            return null;\n        Stack<Integer> path = new Stack<>();\n        for(int x = v; x != s; x = edgeTo[x])\n            path.push(x);\n        path.push(s);\n        return path;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/CC.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 查找连通分量\n * @author huang\n */\npublic class CC {\n    private boolean[] marked;\n    private int[] id;\n    private int count;  // 既用来计量连通分量，同时作为连通分量的下标\n    \n    public CC(Graph G) {\n        marked = new boolean[G.V()];\n        id = new int[G.V()];\n        for(int s = 0; s < G.V(); s++)\n            if(!marked[s]) {\n                dfs(G, s);\n                count++;\n            }\n    }\n    \n    private void dfs(Graph G, int v) {\n        marked[v] = true;\n        id[v] = count;\n        for(int w : G.adj(v))\n            if(!marked[w])\n                dfs(G, w);\n    }\n    \n    public boolean connected(int v, int w) {\n        return id[v] == id[w];\n    }\n    \n    public int id(int v) {\n        return id[v];\n    }\n    \n    public int count() {\n        return count;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/Cycle.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 利用深度优先，判断 G 是否是无向图（假设不存在自环或平行边）\n * @author huang\n */\npublic class Cycle {\n    private boolean[] marked;\n    private boolean hasCycle;\n    public Cycle(Graph G) {\n        marked = new boolean[G.V()];\n        for(int s = 0; s < G.V(); s++)\n            if(!marked[s])\n                dfs(G, s, s);\n    }\n    \n    private void dfs(Graph G, int v, int u) {\n        marked[v] = true;\n        for(int w : G.adj(v)) {\n            if(!marked[w])\n                dfs(G, w, v);\n            else if(w != u)    // v 是从 u 深度遍历得到的。因为不存在平行边，所以 w != v 即刻认为遇到了之前遍历过的点（即有环）\n                hasCycle = true;\n        }\n    }\n    \n    public boolean hasCycle() {\n        return hasCycle;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * 间隔的度数\n * @author huang\n */\npublic class DegreesOfSeparation {\n\n    public static void main(String[] args) {\n        \n        SymbolGraph sGraph = new SymbolGraph(args[0], args[1]);\n        Graph G = sGraph.G();\n        \n        String source = args[2];\n        if(!sGraph.contains(source)) {\n            StdOut.println(source + \"not in database.\");\n            return;\n        }\n        \n        int s = sGraph.index(source);\n        BreadthFirstPaths bfs = new BreadthFirstPaths(G, s);\n        \n        while(!StdIn.isEmpty()) {\n            String sink = StdIn.readLine();\n            if(sGraph.contains(sink)) {\n                int t = sGraph.index(sink);\n                if(bfs.hasPathTo(t))\n                    for(int v : bfs.pathTo(t))\n                        StdOut.println(\"    \" + sGraph.name(v));\n                else\n                    StdOut.println(\"Not connected\");\n            }\n            else\n                StdOut.println(\"Not in database.\");\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Stack;\n\n/**\n * edgeTo[w]=v 表示 v-w 是第一次访问 w 时经过的边\n * edgeTo[] 数组是一颗用父链接表示的以 s 为根且含有所有与 s 连通的顶点的树\n * @author huang\n */\npublic class DepthFirstPaths {\n    private boolean[] marked;  // 这个顶点上调用过 dfs() 了吗？\n    private int[] edgeTo;  // 从起点到一个顶点的已知路径上的最后一个顶点\n    private final int s;  // 起点\n    \n    public DepthFirstPaths(Graph G, int s) {\n        marked = new boolean[G.V()];\n        edgeTo = new int[G.V()];\n        this.s = s;\n        dfs(G, s);\n    }\n    \n    private void dfs(Graph G, int v) {\n        marked[v] = true;\n        for(int w : G.adj(v))\n            if(!marked[w]) {\n                edgeTo[w] = v;\n                dfs(G, w);\n            }\n    }\n    \n    public boolean hasPathTo(int v) {\n        return marked[v];\n    }\n    \n    public Iterable<Integer> pathTo(int v) {\n        if(!hasPathTo(v))\n            return null;\n        Stack<Integer> path = new Stack<>();\n        for(int x = v; x != s; x = edgeTo[x])\n            path.push(x);\n        path.push(s);\n        return path;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\npublic class DepthFirstSearch {\n    private boolean[] marked;\n    private int count;\n    \n    public DepthFirstSearch(Graph G, int s) {\n        marked = new boolean[G.V()];\n        dfs(G, s);\n    }\n    \n    private void dfs(Graph G, int v) {\n        marked[v] = true;\n        count++;\n        for(int w : G.adj(v))\n            if(!marked[w])\n                dfs(G, w);\n    }\n    \n    public boolean marked(int w) {\n        return marked[w];\n    }\n    \n    public int count() {\n        return count;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/Graph.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\n\npublic class Graph {\n    private final int V;    // 顶点数目\n    private int E;    // 边的数目\n    private Bag<Integer>[] adj;    // 邻接表\n    \n    @SuppressWarnings(\"unchecked\")\n    public Graph(int V) {\n        this.V = V;\n        this.E = 0;\n        adj = (Bag<Integer>[]) new Bag[V];    // 创建邻接表\n        for(int v = 0; v < V; v++)\n            adj[v] = new Bag<Integer>();\n    }\n    public Graph(In in) {\n        this(in.readInt());    // 读取 V 并将图初始化\n        int E = in.readInt();    // 读取 E\n        for(int i = 0; i < E; i++) {\n            // 添加一条边\n            int v = in.readInt();    // 读取一个顶点\n            int w = in.readInt();    // 读取另一个顶点\n            addEdge(v, w);    // 添加一条连接它们的边\n        }\n    }\n    public int V() {\n        return V;\n    }\n    public int E() {\n        return E;\n    }\n    public void addEdge(int v, int w) {\n        adj[v].add(w);\n        adj[w].add(v);\n        E++;\n    }\n    public Iterable<Integer> adj(int v) {\n        return adj[v];\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/SymbolGraph.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.ST;\n\npublic class SymbolGraph {\n    \n    private ST<String, Integer> st;    // 符号名 -> 索引\n    private String[] keys;    // 索引 -> 符号名\n    private Graph G;    // 使用索引表示顶点的图\n    \n    public SymbolGraph(String filename, String delim) {\n        st = new ST<String, Integer>();\n        In in = new In(filename);    // 第一遍\n        while(in.hasNextLine()) {\n            String[] a = in.readLine().split(delim);    // 读取字符串\n            for(int i = 0; i < a.length; i++)\n                if(!st.contains(a[i]))\n                    st.put(a[i], st.size());\n        }\n        keys = new String[st.size()];    // 用来获得顶点名的反向索引是一个数组\n        \n        for(String name : st.keys())\n            keys[st.get(name)] = name;\n        \n        G = new Graph(st.size());\n        in = new In(filename);    // 第二遍\n        while(in.hasNextLine()) {    // 构造图\n            String[] a = in.readLine().split(delim);   // 将每一行的第一个顶点和该行的其他顶点相连\n            int v = st.get(a[0]);\n            for(int i = 1; i < a.length; i++)\n                G.addEdge(v, st.get(a[i]));\n        }\n    }\n    \n    // key 是一个顶点吗\n    boolean contains(String key) {\n        return st.contains(key);\n    }\n    \n    // key 的索引\n    int index(String key) {\n        return st.get(key);\n    }\n    \n    // 索引 v 的顶点名\n    String name(int v) {\n        return keys[v];\n    }\n    \n    // 隐藏的 Graph 对象\n    Graph G() {\n        return G;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/TestCC.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * 找出一幅图的所有连通分量\n * @author huang\n */\npublic class TestCC {\n    @SuppressWarnings(\"unchecked\")\n    public static void main(String[] args) {\n        Graph G = new Graph(new In(args[0]));\n        CC cc = new CC(G);\n        \n        int M = cc.count();\n        StdOut.println(M + \" components\");\n        \n        Bag<Integer>[] components;\n        components = (Bag<Integer>[]) new Bag[M];\n        for(int i = 0; i < M; i++)\n            components[i] = new Bag<Integer>();\n        for(int v = 0; v < G.V(); v++) \n            components[cc.id(v)].add(v);\n        for(int i = 0; i < M; i++) {\n            for(int v : components[i])\n                StdOut.print(v + \" \");\n            StdOut.println();\n        }\n        \n    }\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/TestPaths.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * 单点路径问题\n * @author huang\n */\npublic class TestPaths {\n\n    public static void main(String[] args) {\n\n        Graph G = new Graph(new In(args[0]));\n        int s = Integer.parseInt(args[1]);\n        DepthFirstPaths search = new DepthFirstPaths(G, s);\n        for(int v = 0; v < G.V(); v++) {\n            StdOut.print(s + \" to \" + v + \": \");\n            if(search.hasPathTo(v))\n                for(int x : search.pathTo(v))\n                    if(x == s)\n                        StdOut.print(x);\n                    else\n                        StdOut.print(\"-\" + x);\n            StdOut.println();\n        }\n    }\n\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/TestSearch.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.In;\nimport algs4.StdOut;\n\npublic class TestSearch {\n\n    public static void main(String[] args) {\n        Graph G = new Graph(new In(args[0]));\n        int s = Integer.parseInt(args[1]);\n        Search search = new Search(G, s);\n        \n        for(int v = 0; v < G.V(); v++)\n            if(search.marked(v))\n                StdOut.println(v + \" \");\n        StdOut.println();\n        \n        if(search.count() != G.V())\n            StdOut.print(\"NOT \");\n        StdOut.println(\"connected\");\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class TestSymbolGraph {\n\n    public static void main(String[] args) {\n        String filename = args[0];\n        String delim = args[1];\n        SymbolGraph sGraph = new SymbolGraph(filename, delim);\n        \n        Graph G = sGraph.G();\n        \n        while(StdIn.hasNextLine()) {\n            String source = StdIn.readLine();\n            for(int w : G.adj(sGraph.index(source)))\n                StdOut.println(\"    \" + sGraph.name(w));\n        }\n    }\n\n}\n"
  },
  {
    "path": "code/chapter4_1_Undirected_Graphs/TwoColor.java",
    "content": "package chapter4_1_Undirected_Graphs;\n\n/**\n * 判断 G 是否为二分图\n * @author huang\n */\npublic class TwoColor {\n    private boolean[] marked;\n    private boolean[] color;\n    private boolean isTwoColorable = true;\n    public TwoColor(Graph G) {\n        marked = new boolean[G.V()];\n        color = new boolean[G.V()];\n        for(int s = 0; s < G.V(); s++)\n            if(!marked[s])\n                dfs(G, s);\n    }\n    \n    private void dfs(Graph G, int v) {\n        marked[v] = true;\n        for(int w : G.adj(v))\n            if(!marked[w]) {\n                color[w] = !color[v];\n                dfs(G, w);\n            }\n            else if(color[w] == color[v])\n                isTwoColorable = false;\n    }\n    \n    public boolean isBipartite() {\n        return isTwoColorable;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/DepthFirstOrder.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Queue;\nimport algs4.Stack;\n\npublic class DepthFirstOrder {\n    private boolean[] marked;\n    private Queue<Integer> pre;    // 所有顶点的前序排列\n    private Queue<Integer> post;    // 所有顶点的后序排列\n    private Stack<Integer> reversePost;    // 所有顶点的逆后序排列\n    \n    public DepthFirstOrder(Digraph G) {\n        pre = new Queue<>();\n        post = new Queue<>();\n        reversePost = new Stack<>();\n        marked = new boolean[G.V()];\n        \n        for(int v = 0; v < G.V(); v++)\n            if(!marked[v])\n                dfs(G, v);\n    }\n    \n    private void dfs(Digraph G, int v) {\n        pre.enqueue(v);\n        \n        marked[v] = true;\n        for(int w : G.adj(v))\n            if(!marked[w])\n                dfs(G, w);\n        post.enqueue(v);\n        reversePost.push(v);\n    }\n    \n    public Iterable<Integer> pre() {\n        return pre;\n    }\n    \n    public Iterable<Integer> post() {\n        return post;\n    }\n    \n    public Iterable<Integer> reversePost() {\n        return reversePost;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/Digraph.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\n\npublic class Digraph {\n    \n    private final int V;\n    private int E;\n    private Bag<Integer>[] adj;\n    \n    @SuppressWarnings(\"unchecked\")\n    public Digraph(int V) {    // 创建一幅含有 V 个顶点但没有边的有向图\n        this.V = V;\n        this.E = 0;\n        adj = (Bag<Integer>[]) new Bag[V];\n        for(int v = 0; v < V; v++) {\n            adj[v] = new Bag<Integer>();\n        }\n    }\n    \n    public Digraph(In in) {    // 从输入流 in 中读取一幅有向图\n        this(in.readInt());    // 读取 V 并将图初始化\n        int E = in.readInt();    // 读取 E\n        for(int i = 0; i < E; i++) {\n            // 添加一条边\n            int v = in.readInt();    // 读取一个顶点\n            int w = in.readInt();    // 读取另一个顶点\n            addEdge(v, w);    // 添加一条连接它们的边\n        }\n    }\n    \n    public int V() {    // 顶点总数\n        return V;\n    }\n    \n    public int E() {    // 边的总数\n        return E;\n    }\n    \n    void addEdge(int v, int w) {    // 向有向图中添加一条边 v -> w\n        adj[v].add(w);\n        E++;\n    }\n    \n    public Iterable<Integer> adj(int v) {    // 由 v 指出的边所连接的所有顶点\n        return adj[v];\n    }\n    \n    public Digraph reverse() {    // 该图的反向图\n        Digraph R = new Digraph(V);\n        for(int v = 0; v < V; v++)\n            for(int w : adj(v))\n                R.addEdge(w, v);\n        return R;\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/DirectedCycle.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Stack;\n\npublic class DirectedCycle {\n    private boolean[] marked;\n    private int[] edgeTo;\n    private Stack<Integer> cycle;    // 有向环中的所有顶点（如果存在）\n    private boolean[] onStack;    // 递归调用的栈上的所有顶点\n    \n    public DirectedCycle(Digraph G) {\n        onStack = new boolean[G.V()];\n        edgeTo = new int[G.V()];\n        marked = new boolean[G.V()];\n        for(int v = 0; v < G.V(); v++) {\n            if(!marked[v])\n                dfs(G, v);\n        }\n    }\n    \n    private void dfs(Digraph G, int v) {\n        onStack[v] = true;\n        marked[v] = true;\n        for(int w : G.adj(v))\n            if(this.hasCycle())\n                return;\n            else if(!marked[w]) {\n                edgeTo[w] = v;\n                dfs(G, w);\n            }\n            else if(onStack[w]) {\n                cycle = new Stack<Integer>();\n                for(int x = v; x != w; x = edgeTo[x])\n                    cycle.push(x);\n                cycle.push(w);\n                cycle.push(v);\n            }\n        onStack[v] = false;\n    }\n    \n    public boolean hasCycle() {\n        return cycle != null;\n    }\n    \n    public Iterable<Integer> cycle() {\n        return cycle;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/DirectedDFS.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.Bag;\nimport algs4.In;\nimport algs4.StdOut;\n\n/*\n * 深度优先搜索，解决单点可达性和多点可达性问题\n */\npublic class DirectedDFS {\n    private boolean[] marked;\n    \n    public DirectedDFS(Digraph G, int s) {\n        marked = new boolean[G.V()];\n        dfs(G, s);\n    }\n    \n    public DirectedDFS(Digraph G, Iterable<Integer> sources) {\n        marked = new boolean[G.V()];\n        for(int s : sources)\n            if(!marked[s])\n                dfs(G, s);\n    }\n    \n    private void dfs(Digraph G, int v) {\n        marked[v] = true;\n        for(int w : G.adj(v))\n            if(!marked[w])\n                dfs(G, w);\n    }\n    \n    public boolean marked(int v) {\n        return marked[v];\n    }\n    \n    public static void main(String[] args) {\n        Digraph G = new Digraph(new In(args[0]));\n        \n        Bag<Integer> sources = new Bag<Integer>();\n        for(int i = 1; i < args.length; i++)\n            sources.add(Integer.parseInt(args[i]));\n        \n        DirectedDFS reachable = new DirectedDFS(G, sources);\n        \n        for(int v = 0; v < G.V(); v++)\n            if(reachable.marked(v))\n                StdOut.print(v + \" \");\n        StdOut.println();\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/KosarajuSCC.java",
    "content": "package chapter4_2_Directed_Graphs;\n\n/*\n * 计算强连通分量的 Kosaraju 算法\n */\npublic class KosarajuSCC {\n    private boolean[] marked;    // 已访问过的顶点\n    private int[] id;    // 强连通分量的标识符\n    private int count;    // 强连通分量的数量\n    \n    public KosarajuSCC(Digraph G) {\n        marked = new boolean[G.V()];\n        id = new int[G.V()];\n        DepthFirstOrder order = new DepthFirstOrder(G.reverse());\n        for(int s : order.reversePost())\n            if(!marked[s]) {\n                dfs(G, s);\n                count++;\n            }\n    }\n    \n    private void dfs(Digraph G, int v) {\n        marked[v] = true;\n        id[v] = count;\n        for(int w : G.adj(v))\n            if(!marked[w])\n                dfs(G, w);\n    }\n    \n    public boolean stronglyConnected(int v, int w) {\n        return id[v] == id[w];\n    }\n    \n    public int id(int v) {\n        return id[v];\n    }\n    \n    public int count() {\n        return count;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/SymbolDigraph.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.In;\nimport algs4.ST;\n\npublic class SymbolDigraph {\n    \n    private ST<String, Integer> st;    // 符号名 -> 索引\n    private String[] keys;    // 索引 -> 符号名\n    private Digraph G;    // 使用索引表示顶点的图\n    \n    public SymbolDigraph(String filename, String delim) {\n        st = new ST<String, Integer>();\n        In in = new In(filename);    // 第一遍\n        while(in.hasNextLine()) {\n            String[] a = in.readLine().split(delim);    // 读取字符串\n            for(int i = 0; i < a.length; i++)\n                if(!st.contains(a[i]))\n                    st.put(a[i], st.size());\n        }\n        keys = new String[st.size()];    // 用来获得顶点名的反向索引是一个数组\n        \n        for(String name : st.keys())\n            keys[st.get(name)] = name;\n        \n        G = new Digraph(st.size());\n        in = new In(filename);    // 第二遍\n        while(in.hasNextLine()) {    // 构造图\n            String[] a = in.readLine().split(delim);   // 将每一行的第一个顶点和该行的其他顶点相连\n            int v = st.get(a[0]);\n            for(int i = 1; i < a.length; i++)\n                G.addEdge(v, st.get(a[i]));\n        }\n    }\n    \n    // key 是一个顶点吗\n    boolean contains(String key) {\n        return st.contains(key);\n    }\n    \n    // key 的索引\n    int index(String key) {\n        return st.get(key);\n    }\n    \n    // 索引 v 的顶点名\n    public String name(int v) {\n        return keys[v];\n    }\n    \n    // 隐藏的 Digraph 对象\n    public Digraph G() {\n        return G;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/Topological.java",
    "content": "package chapter4_2_Directed_Graphs;\n\nimport algs4.StdOut;\n\n/*\n * 拓扑排序\n */\npublic class Topological {\n    private Iterable<Integer> order;    // 顶点的拓扑排序\n    \n    public Topological(Digraph G) {\n        DirectedCycle cyclefinder = new DirectedCycle(G);\n        if(!cyclefinder.hasCycle()) {\n            DepthFirstOrder dfs = new DepthFirstOrder(G);\n            order = dfs.reversePost();    // 一幅有向无环图的拓扑顺序即为所有顶点的逆后序排列\n        }\n    }\n    \n    public Iterable<Integer> order() {\n        return order;\n    }\n    \n    public boolean isDAG() {\n        return order != null;\n    }\n    \n    public static void main(String[] args) {\n        String filename = args[0];\n        String separator = args[1];\n        SymbolDigraph sGraph = new SymbolDigraph(filename, separator);\n        \n        Topological top = new Topological(sGraph.G());\n        \n        for(int v : top.order())\n            StdOut.println(sGraph.name(v));\n    }\n}\n"
  },
  {
    "path": "code/chapter4_2_Directed_Graphs/TransitiveClosure.java",
    "content": "package chapter4_2_Directed_Graphs;\n\n/*\n * 有向图顶点对可达性\n */\npublic class TransitiveClosure {\n    private DirectedDFS[] all;\n    public TransitiveClosure(Digraph G) {\n        all = new DirectedDFS[G.V()];\n        for(int v = 0; v < G.V(); v++)\n            all[v] = new DirectedDFS(G, v);\n    }\n    \n    public boolean reachable(int v, int w) {\n        return all[v].marked(w);\n    }\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/Edge.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\n/*\n * 带权重的边\n */\npublic class Edge implements Comparable<Edge> {\n    private final int v;    // 顶点之一\n    private final int w;    // 另一个顶点\n    private final double weight;    // 边的权重\n    \n    public Edge(int v, int w, double weight) {\n        this.v = v;\n        this.w = w;\n        this.weight = weight;\n    }\n    \n    public double weight() {\n        return weight;\n    }\n    \n    // 边两端的顶点之一\n    public int either() {\n        return v;\n    }\n    \n    // 另一个顶点\n    public int other(int vertex) {\n        if(vertex == v)\n            return w;\n        else if(vertex == w)\n            return v;\n        else \n            throw new RuntimeException(\"Inconsistent edge\");\n    }\n    \n    public int compareTo(Edge that) {\n        if(this.weight() < that.weight())\n            return -1;\n        else if(this.weight() > that.weight())\n            return +1;\n        else \n            return 0;\n    }\n    \n    public String toString() {\n        return String.format(\"%d-%d %.2f\", v, w, weight);\n    }\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.Bag;\nimport algs4.In;\n\n/*\n * 加权无向图\n */\npublic class EdgeWeightedGraph {\n    private final int V;    // 顶点总数\n    private int E;    // 边的总数\n    private Bag<Edge>[] adj;    // 邻接表\n    \n    @SuppressWarnings(\"unchecked\")\n    public EdgeWeightedGraph(int V) {\n        this.V = V;\n        this.E = 0;\n        adj = (Bag<Edge>[]) new Bag[V];\n        for(int v = 0; v < V; v++)\n            adj[v] = new Bag<Edge>();\n    }\n    \n    public EdgeWeightedGraph(In in) {\n        this(in.readInt());    // 读取 V 并将图初始化\n        int E = in.readInt();    // 读取 E\n        for(int i = 0; i < E; i++) {\n            // 添加一条边\n            int v = in.readInt();    // 读取一个顶点\n            int w = in.readInt();    // 读取另一个顶点\n            double weight = in.readDouble();    // 读取权重\n            Edge e = new Edge(v, w, weight);\n            addEdge(e);    // 添加一条连接它们的边\n        }\n    }\n    \n    public int V() {\n        return V;\n    }\n    \n    public int E() {\n        return E;\n    }\n    \n    public void addEdge(Edge e) {\n        int v = e.either(),\n            w = e.other(v);\n        adj[v].add(e);\n        adj[w].add(e);\n        E++;\n    }\n    \n    public Iterable<Edge> adj(int v) {\n        return adj[v];\n    }\n    \n    // 图的所有边\n    public Iterable<Edge> edges() {\n        Bag<Edge> b = new Bag<Edge>();\n        for(int v = 0; v < V; v++)\n            for(Edge e : adj[v])\n                if(e.other(v) > v)\n                    b.add(e);\n        return b;\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.MinPQ;\nimport algs4.Queue;\n\npublic class KruskalMST {\n    private Queue<Edge> mst;\n    \n    public KruskalMST(EdgeWeightedGraph G) {\n        mst = new Queue<Edge>();\n        MinPQ<Edge> pq = new MinPQ<Edge>();\n        for(Edge e : G.edges())\n            pq.insert(e);\n        UF uf = new UF(G.V());\n        \n        while(!pq.isEmpty() && mst.size() < G.V() - 1) {\n            Edge e = pq.delMin();    // 从 pq 得到权重最小的边和它的顶点\n            int v = e.either(), w = e.other(v);\n            if(uf.connected(v, w))\n                continue;    // 忽略失效的边\n            uf.union(v, w);    // 合并分量\n            mst.enqueue(e);    // 将边添加到最小生成树中\n        }\n    }\n    \n    public Iterable<Edge> edges() {\n        return mst;\n    }\n    \n    public double weight() {\n        \n    }\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport java.beans.Visibility;\n\nimport algs4.MinPQ;\nimport algs4.Queue;\n\n/*\n * 最小生成树的 Prim 算法的延时实现\n */\npublic class LazyPrimMST {\n    private boolean[] marked;    // 最小生成树的顶点\n    private Queue<Edge> mst;    // 最小生成树的边 \n    private MinPQ<Edge> pq;    // 横切边（包括失效的边）\n    \n    public LazyPrimMST(EdgeWeightedGraph G) {\n        pq = new MinPQ<Edge>();\n        marked = new boolean[G.V()];\n        mst = new Queue<Edge>();\n        \n        visit(G, 0);\n        while(!pq.isEmpty()) {\n            Edge e = pq.delMin();    // 从 pq 中得到权重最小的边\n            \n            int v = e.either(),\n                w = e.other(v);\n            if(marked[v] && marked[w])\n                continue;    // 跳过失效的边\n            mst.enqueue(e);    // 将边加入到树中\n            if(!marked[v])    // 将顶点（v 或 w）添加到树中\n                visit(G, v);\n            if(!marked[w])\n                visit(G, w);\n        }\n    }\n    \n    private void visit(EdgeWeightedGraph G, int v) {\n        // 标记顶点 v 并将所有连接 v 和未被标记顶点的边加入 pq\n        marked[v] = true;\n        for(Edge e : G.adj(v))\n            if(!marked[e.other(v)])\n                pq.insert(e);\n    }\n    \n    public Iterable<Edge> edges() {\n        return mst;\n    }\n    \n    public double weight() {\n        \n    }\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.IndexMinPQ;\n\n/*\n * 最小生成树的 Prim（即时版本）\n */\npublic class PrimMST {\n    private Edge[] edgeTo;    // 距离树最近的边\n    private double[] distTo;    // distTo[w] = edgeTo[w].weight()\n    private boolean[] marked;    // 如果 v 在树中则为 true\n    private IndexMinPQ<Double> pq;    // 有效的横切边\n    \n    public PrimMST(EdgeWeightedGraph G) {\n        edgeTo = new Edge[G.V()];\n        distTo = new double[G.V()];\n        marked = new boolean[G.V()];\n        for(int v = 0; v < G.V(); v++) \n            distTo[v] = Double.POSITIVE_INFINITY;\n        pq = new IndexMinPQ<Double>(G.V());\n        \n        distTo[0] = 0.0;\n        pq.insert(0, 0.0);    // 用顶点 0 和权重 0 初始化 pq\n        while(!pq.isEmpty())\n            visit(G, pq.delMin());    // 将最近的顶点添加到树中\n    }\n    \n    private void visit(EdgeWeightedGraph G, int v) {\n        // 将顶点 v 添加到树中，更新数据\n        marked[v] = true;\n        for(Edge e : G.adj(v)) {\n            int w = e.other(v);\n            if(marked[w])    // v-w 失效\n                continue;\n            if(e.weight() < distTo[w]) {\n                // 连接 w 和树的最佳边 Edge 变为 e\n                edgeTo[w] = e;\n                distTo[w] = e.weight();\n                if(pq.contains(w))\n                    pq.change(w, distTo[w]);\n                else\n                    pq.insert(w, distTo[w]);\n            }\n        }\n    }\n    \n    public Iterable<Edge> edges() {\n        \n    }\n    \n    public double weight() {\n        \n    }\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/TestMST.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/*\n * 最小生成树测试\n */\npublic class TestMST {\n\n    public static void main(String[] args) {\n        \n        In in = new In(args[0]);\n        EdgeWeightedGraph G;\n        G = new EdgeWeightedGraph(in);\n        \n        MST mst = new MST(G);\n        for(Edge e : mst.edges())\n            StdOut.println(e);\n        StdOut.println(mst.weight());\n\n    }\n\n}\n"
  },
  {
    "path": "code/chapter4_3_Minimum_Spanning_Tree/UF.java",
    "content": "package chapter4_3_Minimum_Spanning_Tree;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\npublic class UF {\n    private int[] id; // 分量id（以触点作为索引）\n    private int count; // 分量数量\n\n    public UF(int N) {\n        // 初始化分量 id 数组\n        count = N;\n        id = new int[N];\n        for (int i = 0; i < N; i++)\n            id[i] = i;\n    }\n\n    public int count() {\n        return count;\n    }\n\n    public boolean connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    /* quick-find 算法 */\n//    public int find(int p) {\n//        return id[p];\n//    }\n//\n//    public void union(int p, int q) {\n//        // 将 p 和 q 归并到同样的分量中\n//        int pID = find(p);\n//        int qID = find(q);\n//        \n//        // 如果 p 和 q 已经在相同的分量之中则不需要采取任何行动\n//        if(pID == qID)\n//            return;\n//        \n//        // 将 p 的分量重命名为 q 的名称\n//        for(int i = 0; i < id.length; i++)\n//            if(id[i] == pID)\n//                id[i] = qID;\n//        count--;\n//    }\n    \n    /* quick-union 算法 */\n    private int find(int p) {\n        // 找出分量的名称\n        while(p != id[p])\n            p = id[p];\n        return p;\n    }\n    \n    public void union(int p, int q) {\n        // 将 p 和 q 的根节点统一\n        int pRoot = find(p);\n        int qRoot = find(q);\n        if(pRoot == qRoot)\n            return;\n        \n        id[pRoot] = qRoot;\n        \n        count--;\n    }\n\n    public static void main(String[] args) {\n        // 解决由StdIn得到的动态连通性问题\n        int N = StdIn.readInt();    // 读取触点数量\n        UF uf = new UF(N);    // 初始化 N 个分量\n        while (!StdIn.isEmpty()) {\n            int p = StdIn.readInt();\n            int q = StdIn.readInt();    // 读取整数对\n            if (uf.connected(p, q))     // 如果已经连通则忽略\n                continue;\n            uf.union(p, q);    // 归并分量\n            StdOut.println(p + \" \" + q);    // 打印连接\n        }\n        StdOut.println(uf.count + \"components\");\n    }\n}\n"
  },
  {
    "path": "code/chapter4_4_Shortest_Paths/DijkstraSP.java",
    "content": "package chapter4_4_Shortest_Paths;\n\nimport algs4.IndexMinPQ;\nimport algs4.Stack;\n\n/**\n * @author huang\n * 最短路径的 Dijkstra 算法\n */\npublic class DijkstraSP implements SP {\n    private DirectedEdge[] edgeTo;\n    private double[] distTo;\n    private IndexMinPQ<Double> pq;\n    \n    public DijkstraSP(EdgeWeightedDigraph G, int s) {\n        edgeTo = new DirectedEdge[G.V()];\n        distTo = new double[G.V()];\n        pq = new IndexMinPQ<Double>(G.V());\n        for(int v = 0; v < G.V(); v++)\n            distTo[v] = Double.POSITIVE_INFINITY;\n        distTo[s] = 0.0;\n        \n        pq.insert(s, 0.0);\n        while(!pq.isEmpty())\n            relax(G, pq.delMin());\n    }\n    \n    private void relax(EdgeWeightedDigraph G, int v) {\n        for(DirectedEdge e : G.adj(v)) {\n            int w = e.to();\n            if(distTo[w] > distTo[w] + e.weight()) {\n                distTo[w] = distTo[v] + e.weight();\n                edgeTo[w] = e;\n                if(pq.contains(w))\n                    pq.change(w, distTo[w]);\n                else\n                    pq.insert(w, distTo[w]);\n            }\n        }\n    }\n     \n    public double distTo(int v) {\n        return distTo[v];\n    }\n    \n    public boolean hasPathTo(int v) {\n        return distTo[v] < Double.POSITIVE_INFINITY;\n    }\n    \n    public Iterable<DirectedEdge> pathTo(int v) {\n        if(!hasPathTo(v))\n            return null;\n        Stack<DirectedEdge> path = new Stack<DirectedEdge>();\n        for(DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()])\n            path.push(e);\n        return path;\n    }\n}\n"
  },
  {
    "path": "code/chapter4_4_Shortest_Paths/DirectedEdge.java",
    "content": "package chapter4_4_Shortest_Paths;\n\n/**\n * @author huang\n * 加权有向边的数据类型\n */\npublic class DirectedEdge {\n    private final int v;    // 边的起点\n    private final int w;    // 边的终点\n    private final double weight;    // 边的权重\n    \n    public DirectedEdge(int v, int w, double weight) {\n        this.v = v;\n        this.w = w;\n        this.weight = weight;\n    }\n    \n    public double weight() {\n        return weight;\n    }\n    \n    public int from() {\n        return v;\n    }\n    \n    public int to() {\n        return w;\n    }\n    \n    public String toString() {\n        return String.format(\"%d->%d %.2f\", v, w, weight);\n    }\n}\n"
  },
  {
    "path": "code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java",
    "content": "package chapter4_4_Shortest_Paths;\n\nimport algs4.Bag;\nimport algs4.In;\n\n/**\n * @author huang\n * 加权有向图的数据类型\n */\npublic class EdgeWeightedDigraph {\n    private final int V;    // 顶点总数\n    private int E;    // 边的总数\n    private Bag<DirectedEdge>[] adj;    // 邻接表\n    \n    @SuppressWarnings(\"unchecked\")\n    public EdgeWeightedDigraph(int V) {\n        this.V = V;\n        this.E = 0;\n        adj = (Bag<DirectedEdge>[]) new Bag[V];\n        for(int v = 0; v < V; v++)\n            adj[v] = new Bag<DirectedEdge>();\n    }\n    \n    public EdgeWeightedDigraph(In in) {\n        this(in.readInt());\n        int E = in.readInt();\n        for(int i = 0; i < E; i++) {\n            DirectedEdge edge = new DirectedEdge(in.readInt(), in.readInt(), in.readDouble());\n            addEdge(edge);\n        }\n    }\n    \n    public int V() {\n        return V;\n    }\n    \n    public int E() {\n        return E;\n    }\n    \n    public void addEdge(DirectedEdge e) {\n        adj[e.from()].add(e);\n        E++;\n    }\n    \n    public Iterable<DirectedEdge> adj(int v) {\n        return adj[v];\n    }\n    \n    public Iterable<DirectedEdge> edges() {\n        Bag<DirectedEdge> bag = new Bag<>();\n        for(int v = 0; v < V; v++)\n            for(DirectedEdge e : adj[v])\n                bag.add(e);\n        return bag;\n    }\n    \n}\n"
  },
  {
    "path": "code/chapter4_4_Shortest_Paths/SP.java",
    "content": "package chapter4_4_Shortest_Paths;\n\n/**\n * @author huang\n * 最短路径的 API\n */\npublic interface SP {\n    // 从顶点 s 到 v 的距离，如果不存在则路径为无穷大\n    double distTo(int v);\n    // 是否存在从顶点 s 到 v 的路径\n    boolean hasPathTo(int v);\n    // 从顶点 s 到 v 的路径，如果不存在则为 null\n    Iterable<DirectedEdge> pathTo(int v);\n}\n"
  },
  {
    "path": "code/chapter4_4_Shortest_Paths/TestSP.java",
    "content": "package chapter4_4_Shortest_Paths;\n\nimport algs4.In;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 最短路径测试\n */\npublic class TestSP {\n    public static void main(String[] args) {\n        EdgeWeightedDigraph G;\n        G = new EdgeWeightedDigraph(new In(args[0]));\n        int s = Integer.parseInt(args[1]);\n        SP sp = new DijkstraSP(G, s);\n        \n        for(int t = 0; t < G.V(); t++) {\n            StdOut.print(s + \" to \" + t);\n            StdOut.printf(\" (%4.2f): \", sp.distTo(t));\n            if(sp.hasPathTo(t))\n                for(DirectedEdge e : sp.pathTo(t))\n                    StdOut.print(e + \"    \");\n            StdOut.println();\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter5_3_Substring_Search/BoyerMoore.java",
    "content": "package chapter5_3_Substring_Search;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * Boyer-Moore 字符串查找算法（启发式地处理不匹配地字符）\n */\npublic class BoyerMoore {\n    \n    private int[] right;\n    private String pat;\n\n    // 计算跳跃表\n    public BoyerMoore(String pat) {\n        this.pat = pat;\n        int M = pat.length();\n        int R = 256;\n        right = new int[R];\n        for(int c = 0; c < R; c++)\n            right[c] = -1;    // 不包含在模式字符串中的字符的值为 -1\n        for(int j = 0; j < M; j++)       // 包含在模式字符串中的字符的值为\n            right[pat.charAt(j)] = j;    // 它在其中出现的最右位置\n    }\n    \n    // 在 txt 中查找模式字符串\n    public int search(String txt) {\n        int N = txt.length();\n        int M = pat.length();\n        int skip;\n        for(int i = 0; i <= N-M; i += skip) {\n            // 模式字符串和文本在位置 i 匹配吗？\n            skip = 0;\n            for(int j = M-1; j >= 0; j--)\n                if(pat.charAt(j) != txt.charAt(i+j)) {\n                    skip = j - right[txt.charAt(i+j)];\n                    if(skip < 1)\n                        skip = 1;\n                    break;\n                }\n            if(skip == 0)\n                return i;    // 找到匹配\n        }\n        return N;    // 未找到匹配\n    }\n    \n    public static void main(String[] args) {\n        String pat = args[0];\n        String txt = args[1];\n        BoyerMoore bm = new BoyerMoore(pat);\n        StdOut.println(\"text:   \" + txt);\n        int offset = bm.search(txt);\n        StdOut.print(\"pattern: \");\n        for(int i = 0; i < offset; i++)\n            StdOut.print(\" \");\n        StdOut.println(pat);\n    }\n\n}\n"
  },
  {
    "path": "code/chapter5_3_Substring_Search/KMP.java",
    "content": "package chapter5_3_Substring_Search;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * Knuth-Morris-Pratt 字符串查找算法\n */\npublic class KMP {\n\n    private String pat;\n    private int[][] dfa;\n    public KMP(String pat) {\n        this.pat = pat;\n        int M = pat.length();\n        int R = 256;\n        dfa = new int[R][M];\n        dfa[pat.charAt(0)][0] = 1;\n        for(int X = 0, j = 1; j < M; j++) {\n            // 计算 dfa[][j]\n            for(int ch = 0; ch < R; ch++)\n                dfa[ch][j] = dfa[ch][X];    // 复制匹配失败情况下的值\n            dfa[pat.charAt(j)][j] = j+1;  // 设置匹配成功情况下的值\n            X = dfa[pat.charAt(j)][X];    // 更新重启状态\n        }\n    }\n    \n    public int search(String txt) {\n        int i, j, N = txt.length(), M = pat.length();\n        for(i = 0, j = 0; i < N && j < M; i++)\n            j = dfa[txt.charAt(i)][j];\n        if(j == M)\n            return i - M;    // 找到匹配（到达模式字符串的结尾）\n        else\n            return N;    // 未找到匹配（到达文本字符串的结尾）\n    }\n    \n    public static void main(String[] args) {\n        String pat = args[0];\n        String txt = args[1];\n        KMP kmp = new KMP(pat);\n        StdOut.println(\"text:   \" + txt);\n        int offset = kmp.search(txt);\n        StdOut.print(\"pattern: \");\n        for(int i = 0; i < offset; i++)\n            StdOut.print(\" \");\n        StdOut.println(pat);\n    }\n\n}\n"
  },
  {
    "path": "code/chapter5_3_Substring_Search/RabinKarp.java",
    "content": "package chapter5_3_Substring_Search;\n\nimport java.math.BigInteger;\nimport java.util.Random;\n\nimport algs4.StdOut;\n\n/**\n * @author huang\n * Rabin-Karp 指纹字符串查找算法\n */\npublic class RabinKarp {\n    private String pat;    /**仅拉斯维加斯算法需要**/  // 模式字符串\n    private long patHash;    // 模式字符串的散列值\n    private int M;    // 模式字符串的长度\n    private long Q;    // 一个很大的素数\n    private int R = 256;    // 字母表的大小\n    private long RM;    // R^(M-1) % Q\n    \n    public RabinKarp(String pat) {\n        this.pat = pat;    /**仅拉斯维加斯算法需要**/  // 保存模式字符串\n        this.M = pat.length();\n        Q = longRandomPrime();\n        RM = 1;\n        for(int i = 1; i <= M-1; i++)    // 计算 R^(M-1) % Q\n            RM = (R * RM) % Q;           // 用于减去第一个数字时的计算\n        patHash = hash(pat, M);\n    }\n    \n    public boolean check(int i) {    // 蒙特卡洛算法直接返回 true\n        return true;    // 对于拉斯维加斯算法，检查模式与 txt(i..i-M+1) 匹配\n    }\n    \n    private long hash(String key, int M) {    // Horner 方法计算 key[0..M-1] 的散列值\n        long h = 0;\n        for(int j = 0; j < M; j++)\n            h = (R * h + key.charAt(j)) % Q;\n        return h;\n    }\n    \n    private int search(String txt) {\n        int N = txt.length();\n        long txtHash = hash(txt, M);\n        if(patHash == txtHash && check(0))     // 一开始就匹配成功\n            return 0;\n        for(int i = M; i < N; i++) {    // 减去第一个数字，加上最后一个数字，再次检查匹配\n            txtHash = (txtHash + Q - RM*txt.charAt(i-M) % Q) % Q;\n            txtHash = (txtHash*R + txt.charAt(i)) % Q;\n            if(patHash == txtHash)\n                if(check(i - M + 1))\n                    return i - M + 1;\n        }\n        return N;\n    }\n    \n    /**\n     * Exercise 5.3.33\n     */\n    private static long longRandomPrime() {\n        BigInteger prime = BigInteger.probablePrime(31, new Random());\n        return prime.longValue();\n    }\n\n    public static void main(String[] args) {\n        String pat = args[0];\n        String txt = args[1];\n        RabinKarp rk = new RabinKarp(pat);\n        StdOut.println(\"text:    \" + txt);\n        int offset = rk.search(txt);\n        StdOut.print(\"pattern: \");\n        for (int i = 0; i < offset; i++) {\n            StdOut.print(\" \");\n        }\n        StdOut.println(pat);\n    }\n}\n"
  },
  {
    "path": "code/chapter6_3_Suffix_Arrays/KWIC.java",
    "content": "package chapter6_3_Suffix_Arrays;\n\nimport algs4.In;\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * keyword-in-context\n * 上下文的关键词的索引用例\n */\npublic class KWIC {\n    public static void main(String[] args) {\n        In in = new In(args[0]);\n        int context = Integer.parseInt(args[1]);    //  关键词的前后若干个字符\n        \n        String text = in.readAll().replaceAll(\"\\\\s+\", \" \");\n        int N = text.length();\n        SuffixArray sa = new SuffixArray(text);\n        \n        while(StdIn.hasNextLine()) {\n            String q = StdIn.readLine();\n            for(int i = sa.rank(q); i < N && sa.select(i).startsWith(q); i++) {\n                int from = Math.max(0, sa.index(i) - context);\n                int to = Math.min(N-1, from + q.length() + 2 * context);\n                StdOut.println(text.substring(from, to));\n            }\n            StdOut.println();\n        }\n    }\n}\n"
  },
  {
    "path": "code/chapter6_3_Suffix_Arrays/LRS.java",
    "content": "package chapter6_3_Suffix_Arrays;\n\nimport algs4.StdIn;\nimport algs4.StdOut;\n\n/**\n * @author huang\n * 最长重复子字符串算法的用例\n */\npublic class LRS {\n    public static void main(String[] args) {\n        String text = StdIn.readAll();\n        int N = text.length();\n        SuffixArray sa = new SuffixArray(text);\n        String lrs = \"\";\n        for(int i = 1; i < N; i++) {\n            int length = sa.lcp(i);\n            if(length > lrs.length())\n                lrs = sa.select(i).substring(0, length);\n        }\n        StdOut.println(lrs);\n    }\n}\n"
  },
  {
    "path": "code/chapter6_3_Suffix_Arrays/SuffixArray.java",
    "content": "package chapter6_3_Suffix_Arrays;\n\nimport chapter2_3_Quicksort.Quick3way;\n\n/**\n * @author huang\n * 后缀数组（初级实现）\n */\npublic class SuffixArray {\n    private final String[] suffixes;    // 后缀数组\n    private final int N;    // 字符串（和数组）的长度\n    \n    public SuffixArray(String s) {\n        N = s.length();\n        suffixes = new String[N];\n        for(int i = 0; i < N; i++)\n            suffixes[i] = s.substring(i);\n        Quick3way.sort(suffixes);\n    }\n    \n    public int length() {\n        return N;\n    }\n    \n    public String select(int i) {\n        return suffixes[i];\n    }\n    \n    public int index(int i) {\n        return N - suffixes[i].length();\n    }\n    \n    private static int lcp(String s, String t) {\n        int N = Math.min(s.length(), t.length());\n        for(int i = 0; i < N; i++)\n            if(s.charAt(i) != t.charAt(i))\n                return i;\n        return N;\n    }\n    \n    public int lcp(int i) {\n        return lcp(suffixes[i], suffixes[i-1]);\n    }\n    \n    public int rank(String key) {\n        // 二分查找\n        int lo = 0, hi = N - 1;\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            int cmp = key.compareTo(suffixes[mid]);\n            if(cmp < 0)\n                hi = mid - 1;\n            else if(cmp > 0)\n                lo = mid + 1;\n            else\n                return mid;\n        }\n        return lo;\n    }\n}\n"
  },
  {
    "path": "code/yuki.config.json",
    "content": "{\n  \"title\": \"代码目录\",\n  \"repository\": {\n    \"index\": \"https://github.com/bighuang624/Algorithms-notes\",\n    \"branch\": \"master/code\"\n  },\n  \"startLevel\": 2,\n  \"ignore\": {\n    \"dir\": [\".git\"],\n    \"extname\": [\".md\"],\n    \"file\": [\n      \"yuki.config.json\",\n      \".gitignore\",\n      \"README.md\",\n      \".DS_Store\"\n    ]\n  }\n}"
  },
  {
    "path": "docs/.nojekyll",
    "content": ""
  },
  {
    "path": "docs/Context/6.1_事件驱动模拟.md",
    "content": "# 6.1 事件驱动模拟\n\n\n\n### 性能\n\n对 N 个能够相互碰撞的粒子系统，**基于事件的模拟**在初始化时最多需要 N^2 次优先队列操作，在碰撞时最多需要 N 次优先队列操作（且对于每个无效的事件都需要一次额外的操作）。\n\n2.4 节的优先队列实现保证每次操作都是对数级别，因此每次碰撞所需时间是线性对数级别的。\n\n"
  },
  {
    "path": "docs/Context/6.2_B-树.md",
    "content": "# 6.2 B- 树\n\n作用：快速访问大量数据中的特定元素\n\n### 成本模型\n\n我们用**页**表示一块连续的数据，用**探查**表示访问一个页。因此外部查找算法的成本模型为**页的访问**次数（无论读写）。\n\n"
  },
  {
    "path": "docs/Context/6.3_后缀数组.md",
    "content": "# 6.3 后缀数组\n\n* 问题描述：在长度为数百万个字符的字符串中找出其**最长重复子字符串**。\n* 暴力解法：将字符串中每个起始位置为 i 的子字符串与另一个起始位置为 j 的子字符串相比较，记录匹配的最长子字符串。运行时间至少是字符串长度的**平方**级别。\n\n### 后缀排序\n\n方法：\n\n1. 用 Java 的`substring()`方法创建一个由字符串 s 的所有后缀字符串（由字符串的所有位置开始得到的后缀字符串）组成的数组；\n2. 将该数组排序，**最长重复子字符串会出现在数组中的相邻位置**；\n3. 遍历排序后的数组一遍即可在相邻元素中找到最长的公共前缀。\n\n### 应用：定位字符串\n\n通过后缀排序和二分查找，我们可以迅速在大量文本中定位某个特定的子字符串（例如使用文本编辑器或浏览网页时）。\n\n### 后缀数组的 API\n\n| public class SuffixArray | 说明 | \n| :----: | :----: |\n| SuffixArray(String text) | 为文本 text 构造后缀数组 | \n| int length() | 文本 text 的长度 | \n| String select(int i) | 后缀数组中的第 i 个元素（0 <= i <= N-1） | \n| int index(int i) | select(i) 的索引（0 <= i <= N-1） | \n| int lcp(int i) | select(i) 和 select(i-1) 的最长公共前缀的长度（1 <= i <= N-1） | \n| int rank(String key) | 小于键 key 的后缀数量 | \n\n### 用例\n\n最长重复子字符串算法的用例：\n\n```java\n/**\n * @author huang\n * 最长重复子字符串算法的用例\n */\npublic class LRS {\n    public static void main(String[] args) {\n        String text = StdIn.readAll();\n        int N = text.length();\n        SuffixArray sa = new SuffixArray(text);\n        String lrs = \"\";\n        for(int i = 1; i < N; i++) {\n            int length = sa.lcp(i);\n            if(length > lrs.length())\n                lrs = sa.select(i).substring(0, length);\n        }\n        StdOut.println(lrs);\n    }\n}\n```\n\n上下文的关键词的索引用例：\n\n```java\n/**\n * @author huang\n * keyword-in-context\n * 上下文的关键词的索引用例\n */\npublic class KWIC {\n    public static void main(String[] args) {\n        In in = new In(args[0]);\n        int context = Integer.parseInt(args[1]);    //  关键词的前后若干个字符\n        \n        String text = in.readAll().replaceAll(\"\\\\s+\", \" \");\n        int N = text.length();\n        SuffixArray sa = new SuffixArray(text);\n        \n        while(StdIn.hasNextLine()) {\n            String q = StdIn.readLine();\n            for(int i = sa.rank(q); i < N && sa.select(i).startsWith(q); i++) {\n                int from = Math.max(0, sa.index(i) - context);\n                int to = Math.min(N-1, from + q.length() + 2 * context);\n                StdOut.println(text.substring(from, to));\n            }\n            StdOut.println();\n        }\n    }\n}\n```\n\n### 代码实现\n\n```java\n/**\n * @author huang\n * 后缀数组（初级实现）\n */\npublic class SuffixArray {\n    private final String[] suffixes;    // 后缀数组\n    private final int N;    // 字符串（和数组）的长度\n    \n    public SuffixArray(String s) {\n        N = s.length();\n        suffixes = new String[N];\n        for(int i = 0; i < N; i++)\n            suffixes[i] = s.substring(i);\n        Quick3way.sort(suffixes);\n    }\n    \n    public int length() {\n        return N;\n    }\n    \n    public String select(int i) {\n        return suffixes[i];\n    }\n    \n    // 后缀字符串的长度说明其起始位置\n    public int index(int i) {\n        return N - suffixes[i].length();\n    }\n    \n    private static int lcp(String s, String t) {\n        int N = Math.min(s.length(), t.length());\n        for(int i = 0; i < N; i++)\n            if(s.charAt(i) != t.charAt(i))\n                return i;\n        return N;\n    }\n    \n    public int lcp(int i) {\n        return lcp(suffixes[i], suffixes[i-1]);\n    }\n    \n    public int rank(String key) {\n        // 二分查找\n        int lo = 0, hi = N - 1;\n        while(lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            int cmp = key.compareTo(suffixes[mid]);\n            if(cmp < 0)\n                hi = mid - 1;\n            else if(cmp > 0)\n                lo = mid + 1;\n            else\n                return mid;\n        }\n        return lo;\n    }\n}\n```\n\n### 性能\n\n使用三向字符串快速排序，构造长度为 N 的随机字符串的后缀数组，平均所需的空间与 N 成正比，字符比较次数与 ~2NlnN 成正比（渐近于将 N 个随机字符串排序的成本）。\n\n### 改进思路\n\nSuffixArray 的初级实现在最坏情况下性能糟糕，因为排序和查找最长重复子字符串所需的时间都可能是平方级别。\n\nWinter 算法可以在**线性时间**内解决最长重复子字符串问题，其基础是构造一棵由所有后缀字符串组成的字典查找树。显然在解决许多实际问题时，该算法对空间要求较大。\n\n[Manber 算法](https://algs4.cs.princeton.edu/63suffix/Manber.java.html)在线性对数时间内构造后缀数组，并有一个同时完成预处理和对后缀数组排序以支持**常数时间**的`lcp()`方法。\n\n"
  },
  {
    "path": "docs/Context/6.4_网络流算法.md",
    "content": "# 6.4 网络流算法\n\n### 定义\n\n* 一个**流量网络**是一张边的权重（这里称为**容量**）为正的加权有向图。\n* 一个 **st- 流量网络**有两个已知的顶点，即起点 s 和终点 t。\n* st- 流量网络中的 **st- 流量配置**是由一组和每条边相关联的值组成的集合，这个值被称为**边的流量**。如果所有边的流量均小于边的容量且满足每个顶点的**局部平衡**（即净流量 = 流入量 - 流出量 = 0，s 和 t 除外），那么就称这种流量配置方案是**可行的**。\n* **最大流量问题**：给定一个 st- 流量网络，找到一种 st- 流量配置，使得从 s 到 t 的流量最大化。\n\n### API\n\nFlowEdge 并不基于之前的 DirectedEdge，因为需要使每条边都出现在它的两个顶点的邻接表中才能实现剩余网络。**剩余网络**能够增减流量并检测一条边是否已经饱和（无法再增大流量）或者是否为空（无法再减小流量）。\n\n流量网络中的边的 API：\n\n| public class FlowEdge | 说明 | \n| :----: | :----: |\n| FlowEdge(int v, int w, double cap) | |\n| int from() | 这条边的起始顶点 |\n| int to()  | 这条边的目的顶点 |\n| int other(int v) | 边的另一个顶点 |\n| double capacity() | 边的容量 |\n| double flow() | 边中的流量 |\n| double residualCapacityTo(int v) | v 的剩余流量 |\n| double addResidualFlowTo(int v, double delta) | 将 v 的流量增加 delta |\n| String toString() | 对象的字符串表示 |\n\n流量网络的 API：\n\n| public class FlowNetwork | 说明 | \n| :----: | :----: |\n| FlowNetwork(int V) | 创建一个含有 V 个顶点的空网格 |\n| FlowNetwork(In in) | 从输入流中构造流量网络 |\n| int V() | 顶点总数 |\n| int E() | 边的总数 |\n| void addEdge(FlowEdge e) | 向流量网络中添加边 e |\n| Iterable<FlowEdge> adj(int v) | 从 v 指出的边 |\n| Iterable<FlowEdge> edges() | 流量网络中的所有边 |\n| String toString() | 对象的字符串表示 |\n\n### Ford-Fulkerson 算法\n\n一种计算网络中流量分配的方法：\n\n1. 找到任一条从起点到终点的有向路径，增大流量为该路径上所有边中未使用容量的最小值；\n2. 找到另一条路径，如此反复，直到所有从起点到终点的路径上至少有一条边是饱和的。\n\n上述方法只在某些情况下能够计算出网络中的最大流量。因此我们将依据变为网络所对应的无向图中从起点到终点的路径。\n\n一些概念如下：\n\n* 正向边：沿着路径从起点向终点前进时，经过方向与流量方向相同的边；\n* 逆向边：经过方向与流量方向相反的边；\n* **增广路径**：满足所有正向边非饱和、所有逆向边非空的路径。\n\n**Ford-Fulkerson 最大流量算法**：网络中的初始流量为 0，沿着任意从起点到终点（且不含有饱和的正向边或是空逆向边）的增光路径增大流量，直到网络中不存在这样的路径为止。\n\n### 证明：最大流-最小切分定理\n\n**st- 切分**：一个将顶点 s 和顶点 t 分配于不同集合中的切分。\n\n**最大流-最小切分定理**：令 f 为一个 st- 流量网络，以下三种条件是等价的：\n\n* 存在某个 st- 切分，其容量和 f 的流量相等；\n* f 到达了最大流量；\n* f 中已经不存在任何增广路径。"
  },
  {
    "path": "docs/Context/6.5_问题规约.md",
    "content": "# 6.5 问题归约\n\n将很多看似复杂的问题归约为简单的问题，再用特定算法解决。\n\n但是注意不要犯下“Maslow 的锤子”的错误：沉迷于若干问题解决模型，从而妨碍发现更好的解决方法。\n\n### 排序问题\n\n以下问题可以被归约为排序问题：\n\n* 寻找中位数；\n* 统计不同的值；\n* 最小平均完成时间的调度问题。\n\n### 最短路径问题\n\n以下问题能够归约为加权图中的最短路径问题：\n\n* 非负权重的无向图中的单点最短路径问题；\n* 优先级限制下的并行调度问题；\n* 套汇问题。\n\n### 最大流量问题\n\n以下问题可以归约为最大流量问题：\n\n* 就业安置；\n* 产品配送；\n* 网络可靠性。\n\n### 线性规划\n\n运筹学的基础之一是**线性规划（Linear Programming，LP）**：给定一个由 M 个**线性不等式**组成的集合和含有 N 个决策变量的线性等式，以及一个由该 N 个决策变量组成的线性**目标函数**，找出能够使目标函数的值最大化的一组变量值，或者证明不存在这样的赋值方案。\n\n<img style=\"height: 280px;\" alt=\"Linear Programming\" src=\"https://upload-images.jianshu.io/upload_images/2702529-c75e987b97f3f643.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240\">\n\n以下问题均可归约为线性规划问题：\n\n* 最大流量问题；\n* 最短路径问题；\n* 许多许多其他问题。\n\n“许多许多其他问题”的含义如下：\n\n1. 添加约束条件和扩展线性规划模型非常简单；\n2. 问题的归约是有传递性的；\n3. **各种最优化问题都能够直接构造为线性规划问题**。\n\n解决线性规划问题的高效算法：\n\n* 单纯形法（Simplex Algorithm）；\n* 椭球法（Ellipsoid Algorithm）；\n* 内点法（Interior Point Methods）。"
  },
  {
    "path": "docs/Context/6.6_不可解性.md",
    "content": "# 6.6 不可解性\n\n一台“图灵机”就是一台能够读取输入、变换状态和打印输出的有限状态机。它来自于两个重要的思想：\n\n* 普遍性：图灵机可以模拟所有物理可实现的计算设备。这被称为**丘奇-图灵论题**。\n* 可计算性：图灵机无法解决的问题是存在的。\n\n还有第三个关于计算设备效率的思想：\n\n* **扩展的丘奇-图灵论题**：在任意计算设备上解决某个问题的某个程序所需的运行时间的增长数量级都是在图灵机上（或是任意其他计算设备上）解决该问题的某个程序的多项式倍数。\n\n最近几年，量子计算的概念使得一些研究者开始怀疑扩展的丘奇-图灵论题的正确性。\n\n### 指数级别的运行时间\n\n不可解性理论的目的在于将能够区别**多项式时间内**解决的问题和**在最坏情况下（可能）需要指数级别（2^N）时间**才能解决的问题。\n\n一般认为，指数时间的算法无法保证在合理的时间内解决规模超过（例如）100 的问题。\n\n### 搜索问题\n\n* **搜索问题**：有解且**验证它的解的正确性**所需的时间不会超过输入规模的多项式的问题（只与解的验证有关）；\n* **解决**了一个搜索问题：一个算法给出了一个解或已证明解不存在；\n* **NP**：所有搜索问题的集合。\n* **P**：能够在多项式时间内**解决**的所有搜索问题的集合。或者说，能够保证在合理时间范围内解决的所有问题的集合。一般来说，用**不可解**来表示不包含在集合 P 中的问题。\n\n虽然在技术上并不等价，但**搜索问题**、**决定性问题**（解是否存在）、**最优化问题**（最优解是什么）一般都能够相互归约。\n\n### 非确定性\n\nNP 中的 N 表示的是**非确定性（nondeterminism）**。其意思是断言当一个算法面对若干个选项时，它有能力“猜出”正确的选项。在图灵机中，非确定性只是定义为一个给定状态和一个给定输入时的两个不同的后继状态，解则是能够得到期望结果的所有路径。\n\n非确定性看似强大，但没人能**证明**它能够帮助解决任何问题。这就导致人们始终探寻一个问题的答案：\n\n**P=NP 成立吗？**\n\n因为许多重要的实际问题都属于 NP 但不一定属于 P（即已知的最快确定性算法需要指数级别的时间）。如果能够证明它不属于 P，就可以放弃寻找高效率的算法；反之则存在发现某种高效算法的可能性。\n\n### 多项式时间问题的相互归约\n\n证明问题 A 是可以归约为问题 B 的：\n\n1. 将 A 的实例归约为 B 的实例；\n2. 解决 B 的实例；\n3. 将 B 的实例的解归约为 A 的实例的解。\n\n因此，如果一个问题 A 已知是难以解决的，且 A 在多项式时间内能够归约为问题 B，那么问题 B 必然也是难以解决的。\n\n### NP-完全性\n\n若 NP 中的所有问题都能在多项式时间内归纳为搜索问题 A，那么则称问题 A 是 **NP-完全的**。\n\nNP-完全问题的意思是，我们不期望能够找到多项式时间的算法。\n\n### Cook-Levin 定理\n\nCook-Levin 定理：布尔可满足性问题是 NP-完全的。\n\nCook-Levin 定理，加上围绕各种 NP-完全问题所进行的多项式时间内的归约，得到两种可能性：\n\n* 或者 P=NP，即所有搜索问题都能够在多项式时间内得到解决；\n* 或者 P 不等于 NP，即存在某些搜索问题无法在多项式时间内得到解决。\n\n无论 P=NP 是否成立，目前的实际状态是所有 NP-完全问题的已知最佳算法在最坏情况下都需要指数级别的时间。\n\n### 处理 NP-完全性\n\n要证明 NP 中的一个问题是 NP-完全的，需要证明某个已知的 NP-完全问题能够在多项式时间内归约为它。如果成功，则说明找到一个高效算法是不可能的。\n\n处理 NP-完全性的一些尝试：\n\n1. 修改问题，寻找“近似”算法来给出接近但非最佳的解：欧几里得旅行销售员问题、梯度下降；\n2. 给出一种能够有效解决实际应用中所出现的问题的实例算法；\n3. 使用“回溯法”来避免检查所有可能的解，以期找到尽可能“高效”的指数级别算法。\n"
  },
  {
    "path": "docs/Fundamentals/1.3_背包、队列和栈.md",
    "content": "# 1.3 背包、队列和栈\n\n## 可迭代的集合类型\n\nforeach 语句：\n\n```java\nQueue<Transaction> collection = new Queue<Transaction>();\n\nfor(Transaction t : collection) {\n    StdOut.println(t);\n}\n```\n\n## 背包\n\n背包是一种**不支持从中删除元素**的集合数据类型。迭代的顺序不确定且与用例无关，因此使用 Bag 可以说明**元素的处理顺序不重要**。\n\n## 先进先出队列\n\n任何服务性策略的基本原则都是公平，先进先出策略准则是优先服务等待最久的人。\n\n在应用中使用队列的主要原因是在用集合保存元素的同时**保存他们的相对顺序**。\n\n## 栈的实现思路\n\n1. 先用数组实现一个只能处理 String 值、要求用例指定一个容量且不支持迭代的栈。\n2. 修改以实现一个**泛型**的栈。\n3. 在`push()`和`pop()`方法中增加容量判断来调用`resize()`方法。`resize()`方法将栈移动到一个新的大小为 max 的数组中并返回，这样可以**调整数组大小**。\n4. 之前`pop()`的实现仅仅是对 index 的操纵，被弹出的元素的引用仍然存在于数组中，但实际上已成**孤儿**，不会再被访问。这时应将其设置为`null`，让内存被回收。\n5. 集合类数据类型的基本操作之一就是能够使用 Java 的 foreach 语句通过**迭代**遍历并处理集合中的每个元素。\n\n  任意可迭代的集合数据类型中都需要实现：\n  * 集合数据类型必须实现一个`iterator()`方法并返回一个`Iterator`对象；\n  * `Iterator`类必须包含两个方法：`hasNext()`和`next()`。\n\n  ```java\n  // implement Iterable <Item> 对应的接口\n  public interface Iterable<Item> {\n      Iterator<Item> iterator();\n  }\n  ```\n\n  ```java\n  // 集合数据类型需要实现 iterator 方法\n  import java.util.Iterator;\n\n  // iterator 方法并返回一个 Iterator 对象\n  public Iterator<Item> iterator() {\n      return new ReverseArrayIterator();\n  }\n  ```\n  \n  ```java\n  // 迭代器接口\n  public interface Iterator<Item> {\n      boolean hasNext();\n      Item next();\n      void remove();\n  }\n  ```\n  \n  ```java\n  // ReverseArrayIterator 的实现\n  private class ReverseArrayIterator implements Iterator<Item> {\n      private int i = N;\n      \n      public boolean hasNext() { return i > 0; }\n      public Item next() { return a[--i]; }\n      public void remove() {}\n  }\n  ```\n  \n  这样，无需知晓类的实现细节也能使用迭代。\n  \n## 栈实现的分析\n\n以上实现几乎达到了任意集合类型实现的最佳性能：\n\n* 每项操作的用时都与集合大小无关；\n* 空间需求总是不超过集合大小乘以一个整数。\n\n但以上实现的缺点在于`push()`和`pop()`操作会调整数组的大小：这项操作的耗时和栈大小成正比。\n\n使用链表来实现可以克服这个缺点，使操作所需时间总是和集合的大小无关。\n\n## 基础数据结构——数组与链表\n\n| 数据结构 | 优点 | 缺点 |\n| :----: | :----: | :----: |\n| 数组 | 通过索引可以直接访问任意元素 | 在初始化时就需要知道元素的数量 |\n| 链表 | 使用的空间大小和元素数量成正比 | 需要通过引用访问任意元素 |\n"
  },
  {
    "path": "docs/Fundamentals/1.4_算法分析.md",
    "content": "# 1.4 算法分析\n\n## 数学模型\n\n我们用`~f(N)`表示所有随着 N 的增大除以 f(N) 的结果趋近于 1 的函数，用`g(N)~f(N)`表示`g(N)/f(N)`随着 N 的增大趋近于 1。则 f(N) 为 g(N) 的增长的**数量级**。\n\n对于大多数程序，得到其运行时间的数学模型所需的步骤如下：\n\n* 确定**输入模型***（自己的理解：输入的数据，重要的是数据规模）*，定义问题的规模；\n* 识别**内循环**；\n* 根据内循环中的操作确定**成本模型***（自己的理解：耗时间的操作）*；\n* 对于给定的输入，判断这些操作的执行频率。\n\n一般来说，我们希望为各种基础问题找到对数级别、线性级别或是线性对数级别（NlogN）的算法。\n\n### 重要资料\n\np116.表1.4.5 算法中的常见函数／表1.4.6 算法分析中常用的近似函数\n\n![屏幕快照 2017-10-18 15.44.01.png](http://upload-images.jianshu.io/upload_images/2702529-72f9b7c0bff489ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n## 内存\n\n### 对象\n\n要知道一个对象所使用的内存量，需要将所有实例变量使用的内存与**对象本身的开销（一般是 16 字节）**相加。这些开销包括一个指向对象的类的引用、垃圾收集信息以及同步信息。另外，一般内存的使用都会被**填充为 8 字节（64 位计算机中的机器字）的倍数**。\n\n### 链表\n\n嵌套的非静态（内部）类，还需要额外的 8 字节（用于一个指向外部类的引用）。\n\n### 数组\n\n一个**原始数据类型**的数组一般需要 24 字节的头信息（16 字节的对象开销，*4 字节用于保存长度*以及 4 填充字节）再加上保存值所需的内存。\n\n一个**对象**的数组就是一个对象的引用的数组。例如一个含有 N 个 Date 对象的数组需要使用 24 字节（数组开销）加上 8N 字节（所有引用）加上每个对象的 32 字节，共 (24 + 40N) 字节。\n\n**二维数组**是一个数组的数组（每个数组都是一个对象）。例如一个 M * N 的 double 类型的二维数组需要使用 24 字节（数组的数组的开销）加上 8M 字节（所有元素数组的引用）加上 24M 字节（所有元素数组的开销）加上 8MN 字节（M 个长度为 N 的 double 类型的数组），总共（8MN + 32M + 24）~ 8MN 字节。\n\n### 字符串\n\nJava 中 String 的标准实现含有 4 个实例变量：一个指向字符数组的引用（8 字节）和 3 个 int 值（各 4 字节）。第一个 int 值描述的是字符数组中的偏移量，第二个 int 值是一个计数器（字符串的长度），第三个 int 值是一个散列值（在某些情况下节省一些计算）。因此，**每个 String 对象共会使用 40 字节**（16 字节表示对象，3 个 int 实例变量共 12 字节，加上数组引用的 8 字节和 4 个填充字节），这是除字符数组之外字符串所需的内存空间。\n\n一个长度为 N 的 String 对象一般需要使用 40 字节（String 对象本身）加上（24 + 2N）字节（字符数组），总共（64 + 2N）字节。\n\n调用`substring()`方法创建子字符串时，重用了相同的 value[] 数组，因此只会使用 40 字节的内存。即**一个子字符串所需的额外内存是一个常数，构造一个子字符串所需的时间也是常数**。"
  },
  {
    "path": "docs/Fundamentals/1.5_案例研究：union-find算法.md",
    "content": "# 1.5 案例研究：union-find 算法\n\n## 动态连通性\n\n动态连通性问题：设计一个数据结构来保存程序已知的所有整数对的足够多的信息，并用它们来判断一对新对象是否是相连的。\n\n解决该问题的算法被称为 union-find。成本模型：在研究实现 union-find 的 API 的各种算法时，我们统计的是**数组的访问次数**（访问任意数组元素的次数，无论读写）。\n\n路径压缩的加权 quick-union 算法是最优的算法，但并非所有操作*都能在常数时间内完成*。\n\n## 展望\n\n研究各种基础问题的基本步骤：\n\n1. 完整而详细地定义问题，找出解决问题所必需的基本抽象操作并定义一份 API。\n2. 简洁地实现一种初级算法，给出一个精心组织的开发用例并使用实际数据作为输入。\n3. 当实现所能解决的问题的最大规模达不到期望时决定改进还是放弃。\n4. 逐步改进实现，通过经验性分析或（和）数学分析验证改进后的效果。\n5. 用更高层次的抽象表示数据结构或算法来设计更高级的改进版本。\n6. 如果可能，尽量为最坏情况下的性能提供保证，但在处理普通数据时也要有良好的性能。\n7. 在适当的时候将更细致的深入研究留给有经验的研究者并继续解决下一个问题。\n\n## 看一下别人的总结\n\n[算法(1)：Union-Find | Weber](http://binweber.top/2018/02/15/algs_1/)\n"
  },
  {
    "path": "docs/Graphs/4.1_无向图.md",
    "content": "# 4.1 无向图\n\n## 术语表\n\n* 自环：一条连接一个顶点和其自身的边；\n* 平行边：连接同一对顶点的两条边；\n* 多重图：含有平行边的图；\n* 简单图：没有平行边或自环的图；\n* 子图：由一幅图的所有边的一个子集（以及它们所依附的所有顶点）组成的图；\n\n* **路径**：由边顺序连接的一系列顶点；\n* 简单路径：一条没有重复顶点的路径；\n* 环：一条至少含有一条边且起点与终点相同的路径；\n* 简单环：一条（除了起点和终点必须相同之外）不含有重复顶点和边的环；\n\n* 连通图：从任意一个顶点都存在一条路径到达另一个任意顶点的图；\n* 一幅**非连通的图**由若干连通的部分组成，它们都是其极大连通子图。一般来说，**要处理一张图就需要一个个地处理它的连通分量（子图）**；\n\n* 树：一幅无环连通图；\n* 森林：互不相连的树组成的集合；\n* 连通图的生成树：它的一幅子图，它含有图中的所有顶点且是一棵树；\n* 图的生成树森林：它的所有连通子图的生成树的集合；\n\n* 图的密度：已经连接的**顶点对**占所有可能被连接的**顶点对**的比例；\n\n* 二分图：一种能将所有结点分成两部分的图，其中图的每条边所连接的两个顶点都分别属于不同的部分；\n\n## 树的数学性质\n\n当且仅当一幅含有 V 个结点的图 G 满足下列 5 个条件之一时，它就是一棵树：\n\n* G 有 V-1 条边且不含有环；\n* G 有 V-1 条边且是连通的；\n* G 是连通的，但删除任意一条边都会使它不再连通；\n* G 是无环图，但添加任意一条边都会产生一条环；\n* G 中的任意一对顶点之间仅存在一条简单路径。\n\n## 图的表示方法\n\n* 邻接矩阵\n* 边的数组\n* 邻接表数组\n\n## 深度优先搜索（DFS）\n\n### 实现方法\n\n在访问其中一个顶点时：\n\n* 将它**标记为已访问**；\n* 递归地访问它的所有没被标记过的邻居顶点。\n\n### 命题\n\n* 深度优先搜索标记与起点连通的所有顶点所需的时间和顶点的度数之和成正比。\n* 深度优先搜素中每条边都会被访问两次。\n* 深度优先搜索的预处理使用的时间和空间与 V+E 成正比，且可以在常数时间内处理关于图的连通性查询。\n\n### 解决问题\n\n* 连通性：两个给定的顶点是否连通；\n* 单点路径：能够解决**找出**两个给定顶点间的路径的问题；\n* 检测环：给定的图是否为无环图；\n* 双色问题：给定的图是否为二分图；\n\n## 广度优先搜索（BFS）\n\n### 实现方法\n\n使用一个队列来保存所有已经被标记过但其邻接表还未被检查过的顶点。先将起点加入队列，然后重复以下步骤直到队列为空：\n\n* 取队列中的下一个顶点 v 并标记它；\n* 将与 v 相邻的所有未被标记过的顶点加入队列。\n\n### 命题\n\n* 广度优先搜索所需时间在最坏情况下和 V+E 成正比。\n\n## 总结\n\n问题 | 解决方法 \n:-----------: | :-----------: \n单点连通性        | [DepthFirstSearch](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java)   \n单点路径         | [DepthFirstPaths](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java)       \n单点最短路径         | [BreadthFirstPaths](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java)   \n连通性         | [CC](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/CC.java)、union-find  \n检测环         | [Cycle](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Cycle.java)  \n双色问题（图的二分性）         | [TwoColor](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TwoColor.java)"
  },
  {
    "path": "docs/Graphs/4.2_有向图.md",
    "content": "# 4.2 有向图\n\n## 有向图中的可达性\n\n单点可达性：存在一条从顶点 s 到达顶点 v 的**有向路径**。\n\n### 标记－清除的垃圾收集\n\n标记－清除的垃圾回收策略会对每个对象保留一个位做垃圾收集之用。它会**周期性地运行一个类似于 DirectedDFS 的有向图可达性算法**来标记所有**可以被访问到**的对象，然后清理所有对象，回收**没有被标记**的对象，以腾出内存供新的对象使用。\n\n## 拓扑排序\n\n* 当且仅当一幅有向图是无环图时才能进行拓扑排序。\n* 一幅有向无环图的拓扑顺序即为所有顶点的**逆后序排列**（证明见 p376）。\n\n顶点的三种排列顺序：\n\n* 前序：在递归调用之前将顶点加入队列。\n* 后序：在递归调用之后将顶点加入队列。\n* **逆后序**：在递归调用之**后**将顶点压入**栈**。\n\n命题：Topological 类的实现使用了**深度优先搜索**对有向无环图进行拓扑排序，所需时间和 **V+E 成正比**。\n\n证明：第一遍深度优先搜索保证了不存在有向环，第二遍深度优先搜索产生了顶点的逆后序排列，两次搜索都访问了所有的顶点和所有的边。\n\n## 有向图中的强连通性\n\n### 定义\n\n* 如果两个顶点 v 和 w 是互相可达的，则称它们为**强连通**的。\n* 如果一幅有向图中的**任意**两个顶点都是强连通的，则称这幅有向图也是**强连通**的。\n* **强连通分量**：相互均为强连通的顶点的最大子集。\n\n两个顶点是强连通的当且仅当它们都在一个普通的有向环中。\n\n### Kosaraju 算法\n\nKosaraju 算法用于在有向图中高效计算强连通分量，具体操作（证明见 p381）：\n\n1. 在给定的一幅有向图 G 中，使用 DepthFirstOrder（深度优先搜索）来计算它的反向图 G^R 的逆后序排列。\n2. 在 G 中进行标准的深度优先搜索，但是要按照刚才计算得到的顺序而非标准的顺序来访问所有未被标记的顶点。\n3. 在构造函数中，所有在同一个递归 dfs() 调用中被访问到的顶点都在同一个**强连通分量**中。\n\n命题：Kosaraju 算法的预处理所需的**时间和空间与 V+E 成正比**且支持常数时间的有向图强连通性的查询。\n\n证明：该算法会处理有向图的反向图并进行两次深度优先搜索。这三步所需的时间都与 V+E 成正比。反向复制一幅有向图所需的空间与 V+E 成正比。\n\n### 传递闭包\n\n定义：有向图 G 的**传递闭包**是由相同的一组顶点组成的另一幅有向图，在传递闭包中存在一条从 v 指向 w 的边当且仅当在 G 中 w 是从 v 可达的。\n\n根据约定，每个顶点对于自己都是可达的，因此传递闭包会含有 V 个自环。\n\n一般来说，一幅有向图的传递闭包中所含的边比原图多得多。因为传递闭包一般都很稠密，我们通常将它们表示为一个布尔值矩阵，其中 v 行 w 列的值为 true 当且仅当 w 是从 v 可达的。\n\n书上提供的 TransitiveClosure **不适用**于在实际应用中可能遇到的大型有向图，因为**构造函数所需的空间和 V^2 成正比，所需的时间和 V(V+E) 成正比**。\n\n目前，我们还没有找到用远小于平方级别的空间支持常数级别的查询的一般解决方案。\n\n## 总结\n\n问题 | 解决方法 \n:-----------: | :-----------: \n单点和多点的可达性        | [DirectedDFS](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedDFS.java)     \n单点有向路径         | DepthFirstDirectedPaths        \n单点最短有向路径         | BreadthFirstDirectedPaths     \n有向环检测         | [DirectedCycle](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedCycle.java)   \n深度优先的顶点排序         | [DepthFirstOrder](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DepthFirstOrder.java)    \n优先级限制下的调度问题         | [Topological](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Topological.java)     \n拓扑排序         | [Topological](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Topological.java) \n强连通行         | [KosarajuSCC](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/KosarajuSCC.java) \n顶点对的可达性         | [TransitiveClosure](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/TransitiveClosure.java)\n\n\n\n"
  },
  {
    "path": "docs/Graphs/4.3_最小生成树.md",
    "content": "# 4.3 最小生成树\n\n本节研究最小生成树问题：给定一幅**加权无向图**，找到它的一棵最小生成树。\n\n## 术语表\n\n* 图的**生成树**：它的一棵含有其所有顶点的无环连通子图。\n* 一幅**加权图**的**最小生成树（MST）**：它的一棵权值（树中所有边的权值之和）最小的生成树。\n\n## 约定\n\n* 只考虑连通性。\n* 边的权重不一定表示距离。\n* 边的权重可能是 0 或者负数。\n* 所有边的权重都各不相同。\n\n## 原理\n\n### 切分定理\n\n#### 原理\n\n* 用一条边连接树中的任意两个顶点都会产生一个新的环；\n* 从树中删去一条边将会得到两棵独立的树。\n\n#### 定义\n\n* 图的一种**切分**：将图的所有顶点分为两个非空且不重叠的两个集合；\n* **横切边**：一条连接两个属于不同集合的顶点的边。\n\n#### 命题（切分定理）\n\n在一幅加权图中，给定任意的切分，它的**横切边中的权重最小者**必然属于图的最小生成树。\n\n#### 证明\n\n反证法。详见 p392。\n\n### 最小生成树的贪心算法\n\n#### 命题\n\n下面这种方法会将含有 V 个顶点的任意加权连通图中属于最小生成树的边标记为黑色：\n\n初始状态下所有边均为灰色，找到一种切分，它产生的横切边均不为黑色。将它权重最小的横切边标记为黑色。反复，直到标记了 V-1 条黑色边为止。\n\n## Prim 算法\n\n每一步都会为一棵生长中的树添加一条边。一开始这棵树只有一个顶点，然后会向它添加 V-1 条边，每次总是将下一条**连接树中的顶点与不在树中的顶点且权重最小的边**加入树中（即由树中的顶点所定义的切分中的一条横切边）。\n\n### 延时实现\n\nPrim 算法的延时实现使用了一条优先队列来保存所有的横切边、一个由顶点索引的数组来标记树的顶点以及一条队列来保存最小生成树的边。这种延时实现会在优先队列中**保留**失效的边。\n\n#### 开销\n\nPrim 算法的延时实现计算一幅含有 V 个顶点和 E 条边的连通加权无向图的最小生成树所需的**空间与 E 成正比**，所需的**时间与 ElogE 成正比（最坏情况）**。\n\n**证明**：\n\n优先队列中最多可能有 E 条边，这就是空间需求的上限。\n\n算法的瓶颈在于优先队列的`insert()`和`delMin()`方法中比较边的权重的次数。在最坏情况下，一次插入的成本为 ~lgE，删除最小元素的成本为 ~2lgE。因为最多只能插入 E 条边，删除 E 次最小元素，因此所需的时间与 ElogE 成正比（最坏情况）。\n\n### 即时实现\n\n我们感兴趣的只是连接树顶点和非树顶点中**权重最小**的边。当我们将顶点 v 添加到树中时，对于每个非树顶点 w 产生的变化只可能使得 w 到最小生成树的距离更近。因此，我们只需要在优先队列中保存每个非树顶点 w 的一条边：**将它与树中顶点连接起来的权重最小的那条边**。\n\nPrim 算法的即时实现将有效的横切边保存在了一条索引优先队列中。\n\n#### 开销\n\nPrim 算法的即时实现计算一幅含有 V 个顶点和 E 条边的连通加权无向图的最小生成树所需的**空间与 V 成正比**，所需的**时间与 ElogV 成正比（最坏情况）**。\n\n**证明**：\n\n因为优先队列中的顶点树最多为 V，且使用了三条由顶点索引的数组，所以所需的空间的上限和 V 成正比。\n\n算法会进行 V 次插入操作，V 次删除最小元素的操作和（在最坏情况下）E 次改变优先级的操作。已知在基于堆实现的索引优先队列中所有这些操作的增长数量级为 logV，所以将所有这些加起来可知算法所需时间和 ElogV 成正比。\n\n## Kruskal 算法\n\n按照边的权重顺序（从小到大）处理它们，将边加入最小生成树中，**加入的边不会与已经加入的边构成环**，直到树中含有 V-1 条边为止。我们从一片由 V 棵单顶点的树构成的森林开始并不断将两颗树合并（用可以找到的最短边），直到只剩下一棵树，它就是最小生成树。\n\n#### 开销\n\nKruskal 算法的计算一幅含有 V 个顶点和 E 条边的连通加权无向图的最小生成树所需的**空间与 E 成正比**，所需的**时间与 ElogE 成正比（最坏情况）**。\n\n**证明**：\n\n算法的实现在构造函数中使用所有边初始化优先队列，成本最多为 E 次比较。\n\n优先队列构造完成后，其余的部分和 Prim 算法完全相同。优先队列中最多可能含有 E 条边，即所需的空间的上限。每次操作的成本最多为 2lgE 次比较，这就是时间上限的由来。\n\n## 总结与展望\n\n各种最小生成树算法 V 个顶点 E 条边，最坏情况下的增长数量级：\n\n算法 | 空间 | 时间\n:----------- | :-----------: | :----------- \n[延时的 Prim 算法](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java)        | E | ElogE    \n[即时的 Prim 算法](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java)         | V | ElogV       \n[Kruskal](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java)         | E | ElogE     \nFredman-Tarjan         | V | E+VlogV \nChazelle         | V | 非常接近但还没有达到 E    \n理想情况         | V | E?     \n\n一方面，目前还没有理论能够证明，不存在能在线性时间内得到任意图的最小生成树的算法；另一方面，发明能够在线性时间内计算稀疏图的最小生成树的算法仍然没有进展。\n"
  },
  {
    "path": "docs/Graphs/4.4_最短路径.md",
    "content": "# 4.4 最短路径\n\n本节研究最短路径问题：找到从一个顶点到达另一个顶点的**成本最小**的路径。\n\n## 最短路径的性质\n\n### 需要解决的问题\n\n* 并不是所有顶点都是可达的：为了简化问题，约定图都是强连通的（每个顶点从另外任意一个顶点都是可达的）。\n* 负权重会使问题更复杂：经典 Bellman-Ford 算法可以解决。\n* 最短路径一般都是简单的：我们的算法会忽略构成环的零权重边，因此找到的最短路径都不会含有环。\n* 可能存在平行边和自环：平行边中权重最小者才会被选中，权重为零的自环会被忽略。\n\n### 最短路径树（SPT）\n\n**定义**：给定一幅加权有向图和一个顶点 s，以 s 为起点的一棵**最短路径树**是图的一幅子图，它包含 s 和从 s 可达的所有顶点。这棵有向树的根结点为 s，树的每条路径都是有向图中的一条最短路径。\n\n## 加权有向图的数据结构\n\n### 最短路径的数据结构\n\n表示最短路径所需的数据结构：\n\n* **最短路径树中的边**：和深度优先搜索、广度优先搜索和 Prim 算法一样，使用一个**由顶点索引的 DirectedEdge 对象的父链接数组 edgeTo[]**，其中 edgeTo[v] 的值为树中连接 v 和它的父结点的边（也是从 s 到 v 的最短路径上的最后一条边）。\n* **到达起点的距离**：使用一个**由顶点索引的数组 distTo[]**，其中 distTo[v] 为从 s 到 v 的已知最短路径的长度。\n\n约定（s 是寻找的起点）：\n\n* edgeTo[s] 的值为 null，distTo[s] 的值为 0。\n* 从起点到不可达的顶点的距离均为`Double.POSITIVE_INFINITY`。\n\n### 边的松弛\n\n**放松**边 v->w 意味着检查从 s 到 w 的最短路径是否是先从 s 到 v，然后再由 v 到 w。如果是，则根据这个情况更新数据结构中的内容。\n\n边的放松操作之后可能出现两种情况：\n\n* 边失效（`distTo[w] <= distTo[v] + e.weight()`）；\n* v->w 就是到达 w 的最短路径，更新 edgeTo[w] 和 distTo[w]（这可能会使另一些边失效，但也有可能产生一些新的有效边）。\n\n实际上，实现会放松从一个给定顶点指出的所有边。\n\n## 最短路径算法的理论基础\n\n\n## Dijkstra 算法\n\nDijkstra 算法能够解决**边权重非负**的加权有向图的单起点最短路径问题。\n\n思想：**每次添加离起点最近的非树顶点**。\n\n### 数据结构\n\n### 开销\n\n在一幅含有 V 个顶点和 E 条边的加权有向图中，使用 Dijkstra 算法计算根结点为给定起点的最短路径树所需的**空间与 E 成正比**，所需的**时间与 ElogE 成正比（最坏情况）**。\n\n### 与 Prim 算法的比较"
  },
  {
    "path": "docs/README.md",
    "content": "<h1 align=\"center\">《算法（第4版）》笔记</h1>\n\n<p align=\"center\"><a href=\"http://kyonhuang.top\"><img src=\"https://img.shields.io/badge/%E4%BD%9C%E8%80%85-KyonHuang-7AD6FD.svg\"></a></p>\n\n<div style=\"text-align: center; width: 100%;\">\n<img alt=\"\" src=\"https://upload-images.jianshu.io/upload_images/2702529-ba5800799763d197.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240\" style=\"display: inline-block; height: 180px\" />\n</div>\n\n### Github\n\n[项目地址](https://github.com/bighuang624/Algorithms-notes)\n\n如果您觉得有帮助，不妨**点一个 star** 以资鼓励。\n\n### 代码\n\n相关代码详见[代码目录](https://github.com/bighuang624/Algorithms-notes/blob/master/code)\n\n## Cheatsheet\n\n[Algorithms and Data Structures Cheatsheet](https://algs4.cs.princeton.edu/cheatsheet/)\n\n![Cheatsheet](https://raw.githubusercontent.com/bighuang624/Algorithms-notes/master/Cheatsheet.png)"
  },
  {
    "path": "docs/Searching/3.1_符号表.md",
    "content": "# 3.1 符号表\n\n**符号表**是一种存储键值对的数据结构，支持两种操作：\n\n* **插入（put）**，即将一组新的键值对存入表中；\n* **查找（get）**，即根据给定的键得到相应的值。\n\n## API\n\n符号表是一种典型的**抽象数据类型**。\n\n实现遵循以下规则：\n\n* 每个键只对应着一个值（表中**不允许存在重复的键**）。\n* 当用例代码向表中存入的键值对和表中已有的键（及关联的值）**冲突**时，**新的值会替代旧的值**。\n* 键不能为空。\n* 值不能为空。这个规定是我们的 API 定义中当键不存在时`get()`方法会反悔空。\n\n### 迭代\n\n对于符号表，我们不使用`implements Iterable<Key>`来强制所有实现必须包含`iterator()`方法来返回一个实现了`hasNext()`和`next()`方法的迭代器，而是定义了`keys()`方法来返回一个`Iterable<Key>`对象以方便用例遍历所有的键。\n\n## 有序符号表\n\n许多符号表的实现都利用了 Comparable 接口带来的键的有序性来更好地实现`put()`和`get()`方法。\n\n### 成本模型\n\n在学习符号表的实现时，我们会统计**比较**的次数（等价性测试或是键的相互比较）。在内循环不进行比较（极少）的情况下，我们会统计**数组的访问次数**。\n\n## 无序链表中的顺序查找\n\n符号表中使用的数据结构的一个简单选择是链表，每个结点存储一个键值对。\n\n在含有 N 对键值的基于（无序）链表的符号表中，未命中的查找和插入操作都需要 N 次比较。命中的查找在最坏情况下需要 N 次比较，特别地，向一个空表中插入 N 个不同的键需要 ~N^2/2 次比较。\n\n## 有序数组中的二分查找\n\n有序符号表的一种实现使用一对平行的数组，一个存储键一个存储值。这份实现的核心在于`rank()`方法，它返回表中小于给定键的键的数量（不管表中是否存在该键）。\n\n## 对二分查找的分析\n\n在 N 个键的**有序数组**中进行二分查找最多需要 (lgN+1) 次比较（无论是否成功）。\n\n向大小为 N 的**有序数组**中插入一个新的元素在最坏情况下需要访问 ~2N 次数组，因此向一个空符号表中插入 N 个元素在最坏情况下需要访问 ~N^2 次数组。\n\n## 预览\n\n| 算法（数据结构） | N 次插入后最坏情况下的查找成本 | N 次插入后最坏情况下的插入成本 | N 次随机插入后平均情况下的查找成本 | N 次随机插入后平均情况下的查找成本 | 是否高效支持有序性相关的操作\n| :----: | :----: | :----: | :----: | :----: | :----: |\n| 顺序查找（无序链表） | N | N | N/2 | N | 否\n| 二分查找（有序数组） | lgN | 2N | lgN | N | 是\n\n现代应用需要**同时**能够支持高效的查找和插入两种操作的符号表实现。\n\n为了将二分查找的效率和链表的灵活性结合起来，**二叉查找树**应运而生。\n\n| 使用的数据结构 | 实现 | 优点 | 缺点\n| :----: | :----: | :----: | :----: |\n| 链表（顺序查找） | [SequentialSearchST]() | 适用于小型问题 | 对于大型符号表很慢\n| 有序数组（二分查找） | [BinarySearchST]() | 最优的查找效率和空间需求，能够进行有序性相关的操作 | 插入操作很慢\n| 二叉查找树 | [BST]() | 实现简单，能够进行有序性操作相关的操作 | \n| 平衡二叉查找树 | [RedBlackBST]() | 最优的查找和插入效率，能够进行有序性相关的操作 | \n| 散列表 | [SeparateChainHashST]()<p>[LinearProbingHashST]() | 能够快速地查找和插入常见类型的数据 | \n\n\n\n"
  },
  {
    "path": "docs/Searching/3.2_二叉查找树.md",
    "content": "# 3.2 二叉查找树\n\n**定义**：一棵**二叉查找树（BST，或二叉搜索树）**是一棵二叉树，其中每个结点都含有一个 Comparable 的键（以及相关联的值）且每个结点的键都大于其左子树中的任意结点的键而小于右子树的任意结点的键。\n\n## 基本实现\n\n### 数据表示\n\n二叉查找树上的一个结点，**左链接**指向一棵**小于**该结点的所有键组成的二叉查找树，**右链接**指向一棵由**大于**该结点的所有键组成的二叉查找树。\n\n### 查找\n\n在二叉查找树中查找一个键的递归算法：如果树是空的，则查找未命中；如果被查找的键和根结点的键相等，查找命中，否则我们就（递归地）在适当的子树中继续查找。如果被查找的键较小就选择左子树，较大则选择右子树。\n\n### 删除*\n\n对于删除一个拥有两个子结点的情况，在删除结点 x 后用它的**后继结点**填补它的位置。因为 x 有一个右子结点，因此它的后继结点就是**其右子树中的最小结点**。这样的替换仍然能保证树的有序性，因为 x.key 和它的后继结点的键之间不存在其他的键。\n\n用 4 个简单的步骤能够完成将 x 替换为它的后继结点的任务：\n\n1. 将指向即将被删除的结点的链接保存为 t；\n2. 将 x 指向它的后继结点`min(t.right)`；\n3. 将 x 的**右链接**（原本指向一棵所有结点都大于 x.key 的二叉查找树）指向`deleteMin(t.right)`，也就是在删除后所有结点仍然大于 x.key 的子二叉查找树；\n4. 将 x 的**左链接**（本为空）设为 t.left（其下所有的键都小于被删除的结点和它的后继结点）。\n\n对于某些大规模的实际应用，这种方法可能会有一点性能上的问题。\n\n## 分析\n\n使用二叉查找树的算法的运行时间取决于树的形状，而树的形状又取决于键被插入的先后顺序。\n\n* **最好**情况：一棵含有 N 个结点的树是完全平衡的，每条空链接和根结点的距离都为 ~lgN。\n* **最坏**情况：搜索路径上可能有 N 个结点。\n\n在由 N 个随机键构造的二叉查找树中，查找命中平均所需的比较次数为 ~2lnN（约 1.39 lgN）。\n\n在由 N 个随机键构造的二叉查找树中插入操作和查找未命中平均所需的比较次数为 ~2lnN（约 1.39 lgN）。\n\n## 简单的符号表实现的成本总结\n\n| 算法（数据结构） | N 次插入后最坏情况下的查找成本 | N 次插入后最坏情况下的插入成本 | N 次随机插入后平均情况下的查找成本 | N 次随机插入后平均情况下的查找成本 | 是否高效支持有序性相关的操作\n| :----: | :----: | :----: | :----: | :----: | :----: |\n| 顺序查找（无序链表） | N | N | N/2 | N | 否\n| 二分查找（有序数组） | lgN | 2N | lgN | N | 是\n| 二叉树查找（二叉查找树） | N | N | 1.39lgN | 1.39lgN | 是\n\n随机键构造的二叉查找树的平均高度为树中结点数的对数级别。而对于不随机的构造树的键，有**平衡二叉查找树**来保证无论键的插入顺序如何，树的高度都将是总键数的对数。"
  },
  {
    "path": "docs/Searching/3.3_平衡查找树.md",
    "content": "# 3.3 平衡查找树\n\n前几种算法在最坏情况下的性能还是很糟糕。本节中介绍一种二分查找树并能保证无论如何构造它，它的运行时间都是对数级别的。\n\n理想情况下，我们希望能够保持二分查找树的平衡性，以使树高为 ~lgN，这样就能保证所有查找都能在 ~lgN 次比较内结束。\n\n## 2-3 查找树\n\n**定义**：一棵 **2-3 查找树**或为一棵空树，或由以下结点组成：\n\n* **2-结点**，含有一个键（及其对应的值）和两条链接，左链接指向的 2-3 树中的键都小于该结点，右链接指向的 2-3 树中的键都大于该结点；\n* **3-结点**，含有两个键（及其对应的值）和三条链接，左链接指向的 2-3 树中的键都小于该结点，**中链接**指向的 2-3 树中的键都位于该结点的两个键之间，右链接指向的 2-3 树中的键都大于该结点。\n\n将指向一棵空树的链接称为**空链接**，一棵**完美平衡**的 2-3 查找树中的所有空链接到根结点的距离都应该是相同的。\n\n### 插入\n\n在一棵大小为 N 的 2-3 树中，查找和插入操作访问的结点必然不超过 lgN 个。\n\n## \n\n尽管可以用不同的数据类型表示 2-结点和 3-结点，但这种直白的表示方法需要维护两种不同类型不同类型的结点，将被查找的键和结点中的每个键进行比较，将链接和其中信息从一种结点复制到另一种结点，\n\n## 红黑二叉查找树\n\n**定义**：**红黑树**是含有红黑链接并满足下列条件的二叉查找树：\n\n* 红链接均为左链接；\n* 没有任何一个结点同时和两条红链接相连；\n* 该树是**完美黑色平衡**的，即任意空链接到根结点的路径上的黑链接数量相同。\n\n**红链接**将两个 2-结点连接起来构成一个 3-结点，**黑链接**则是 2-3 树中的普通链接。确切来说，3-结点被表示为由一条**左斜**的红色链接相连的两个 2-结点（其中一个是另一个的左子结点）。\n\n## 各种符号表实现的成本总结\n\n| 算法（数据结构） | N 次插入后最坏情况下的查找成本 | N 次插入后最坏情况下的插入成本 | N 次随机插入后平均情况下的查找成本 | N 次随机插入后平均情况下的查找成本 | 是否高效支持有序性相关的操作\n| :----: | :----: | :----: | :----: | :----: | :----: |\n| 顺序查找（无序链表） | N | N | N/2 | N | 否\n| 二分查找（有序数组） | lgN | 2N | lgN | N | 是\n| 二叉树查找（BST） | N | N | 1.39lgN | 1.39lgN | 是\n| 2-3 树查找（红黑树） | 2lgN | 2lgN | lgN | lgN | 是\n"
  },
  {
    "path": "docs/Searching/3.4_散列表.md",
    "content": "# 3.4 散列表\n\n使用散列的查找算法分为两步：\n\n1. 使用**散列函数**将被查找的键转化为数组的一个索引；\n2. **处理碰撞冲突**。\n\n两种解决碰撞的方法：**拉链法**和**线性探测法**。\n\n散列表是算法在**时间**和**空间**上做出权衡的经典例子，只需要调整散列算法的参数就可以在空间和时间之间做出取舍。使用散列表可以实现在一般应用中拥有（均摊后）**常数级别**的查找和插入操作的符号表。\n\n## 散列函数\n\n如果我们有一个能够保存 M 个键值对的数组，则需要能够将**任意键**转化为**该数组范围内的索引（[0, M-1] 范围内的整数）**的**散列函数**，这个散列函数应该**易于计算**并且能够**均匀分布**所有的键。\n\n### 键为正整数\n\n将**整数**散列的最常用方法是**除留余数法**：选择大小为**素数**（特别地，不是 2 的幂） M 的数组，对于任意正整数 k，计算 k 除以 M 的余数。\n\n如果 M 不是素数，可能无法均匀地散列散列值。\n\n### 键为浮点数\n\n两种方法：\n\n* 对于 0 到 1 之间的实数，可以乘以 M 并四舍五入得到一个 0 至 M-1 之间的索引值。但这种方式会使键的高位起的作用更大，最低位对散列的结果没有影响；\n* 将键表示二进制数，然后使用除留余数法（Java 使用同样的方法）。\n\n### 键为字符串\n\n一种叫 Horner 方法的经典算法用 N 次乘法、加法和取余来计算一个字符串的散列值。\n\n```java\nint hash = 0;\nfor (int i = 0; i < s.length(); i++)\n    hash = (R * hash + s.charAt(i)) % M;\n```\n\n只要 R 足够小，不造成溢出（这里我认为是指 int 类型的溢出），那么结果就能够落在 0 到 M-1 之内。\n\n### 键为组合\n\n可以用 String 类型一样的方法进行混合处理。例如对于由两个数字表示的 day、两个数字表示的 month、四个数字表示的 year 所构成的键类型 Date，可以这样计算散列值：\n\n```java\nint hash = (((day * R + month) % M) * R + year) % M;\n```\n\n### Java 的相关处理\n\nJava 令所有数据类型都继承了一个能够返回一个 32 比特整数的`hashCode()`方法，且每一种数据类型的`hashCode()`方法都必须和`equals()`方法一致，即`a.equals(b) == true`说明`a.hashCode() == b.hashCode()`（但反过来不一定成立）。\n\n如果要为自定义的数据类型定义散列函数，需要同时重写`hashCode()`和`equals()`两个方法。\n\n### 将`hashCode()`的返回值转化为数组索引\n\n因为需要的是数组索引而非一个 32 位的整数，在实现中会将默认的`hashCode()`方法和除留余数法结合产生一个 0 到 M-1 的整数：\n\n```java\nprivate int hash(Key k) {\n    return (x.hashCode() & 0x7fffffff) % M;\n}\n```\n\n这段代码会将符号位屏蔽（将一个 32 位整数变为一个 31 位非负整数），然后用除留余数法计算它除以 M 的余数。\n\n### 软缓存\n\n如果散列值的计算很耗时，可以考虑将**每个键的散列值缓存起来**，即在每个键中使用一个 hash 变量来保存它的`hashCode()`的返回值。\n\n### 小结\n\n总的来说，要为一个数据类型实现一个优秀的散列方法需要满足三个条件：\n\n* 一致性：等价的键必然产生相等的散列值；\n* 高效性：计算简便；\n* 均匀性：均匀地散列所有的键。\n\n其中，保证均匀性的最好方法是保证键的每一位都在散列值的计算中起到了相同的作用。\n\n实现散列函数时有一个指导思想，称作**均匀散列假设**：我们使用的散列函数能够均匀并独立地将所有的键散布于 0 到 M-1 之间。这是一个实际无法达到的理想模型。\n\n## 基于拉链法的散列表\n\n**拉链法**：将大小为 M 的数组中的每个元素指向一条链表，链表中的每个结点都存储了散列值为该元素的索引的键值对。\n\n查找分两步：首先根据散列值找到对应的链表，然后沿着链表顺序查找相应的键。\n\n命题：在一张含有 M 条链表和 N 个键的散列表中，（在均匀散列假设成立的前提下）任意一条链表中的键的数量均在 N/M 的常数因子范围内的概率无限趋向于 1。\n\n性质：在一张含有 M 条链表和 N 个键的散列表中，未命中查找和插入操作所需的比较次数为 ~N/M。\n\n### 散列表的大小\n\n选择适当的数组大小 M，既不会因为空链表而浪费大量内存，也不会因为链表太长而在查找上浪费太多时间。拉链法的一个**好处**是这并不是关键性的选择，对性能的影响没有那么大。\n\n一种更可靠的方案是动态调整链表数组的大小，这样无论在符号表中有多少键值对都能保证链表较短。\n\n### 有序性相关的操作\n\n散列最主要的目的在于均匀地将键散布开来，因此在计算散列后键的顺序信息就丢失了。如果要执行有序性相关的操作，散列表不是最合适的选择，因为这些操作的运行时间都会是线性的。\n\n## 基于线性探测法的散列表\n\n实现散列表的另一种方式是用大小为 M 的数组保存 N 个键值对，其中 M > N，需要依靠数组中的**空位**解决碰撞冲突。基于这种策略的所有方法被统称为**开放地址**散列表，其中最简单的是**线性探测法**：当碰撞发生时（当一个键的散列值已经被另一个不同的键占用），直接检查散列表中的下一个位置（将索引值加 1）。这样的线性探测可能会产生三种结果：\n\n* 命中，该位置的键和被查找的键相同；\n* 未命中，键为空（该位置没有键）；\n* 继续查找，该位置的键和被查找的键不同。\n\n### 删除操作\n\n实现删除操作时，直接将该键所在的位置设为 null 是不行的，因为这会使得在此位置之后的元素无法被查找。因此，我们需要将簇中被删除的右侧的所有键重新插入散列表。\n\n和拉链法一样，开放地址类的散列表的性能也依赖于 a = N/M 的比值，但意义有所不同。我们将 a 称为散列表的**使用率**：\n\n* 对于基于拉链法的散列表，a 是每条链表的长度，因此一般大于 1；\n* 对于基于线性探测的散列表，a 是表中已被占用的空间的比例，不可能大于 1，且不允许达到 1（散列表被占满，未命中的查找会导致无限循环）。会动态调整保证使用率在 1/8 到 1/2 之间。\n\n### 键簇\n\n线性探测的平均成本取决于**元素在插入数组后聚集成的一组连续的条目**，也叫做**键簇**。短小的键簇才能保证较高的效率。\n\n基于均匀散列假设，数组的每个位置都有相同的可能性被插入一个新键，长键簇更长的可能性比短键簇更大，因为新建的散列值无论落在簇中的任何位置都会使簇的长度加 1。\n\n### 性能分析\n\n在一张大小为 M 并含有 N = aM 个键的基于线性探测的散列表中，基于均匀散列假设，\n\n* 命中的查找所需的探测次数为：~1/2 (1 + 1/(1 - a))\n* 未命中的查找所需的探测次数为：~1/2 (1 + 1/(1 - a)^2)\n\n## 调整数组大小\n\n动态调整数组大小可以为我们保证 a 不大于 1/2。\n\n* 对于拉链法，如果能够准确估计用例所需的散列表的大小 N，调整数组的工作不是必须的，选取一个适当的 M 即可；\n* 对于线性探测法，调整数组的大小是必须的，因为当用例插入的键值对数量超过预期时，它的查找时间不仅会变得非常长，还会在散列表被填满时进入无限循环。\n\n假设一张散列表能够自己调整数组的大小，初始为空。基于均匀散列假设，执行任意顺序的 t 次**查找**、**插入**和**删除**操作所需的时间和 t 成正比，所使用的内存量总是在表中的键的总数的常数因子范围内。\n\n## 总结\n\n### 符号表的内存使用\n\n| 方法 | N 个元素所需的内存（引用类型） |\n| :--: | :--: |\n| 基于拉链法的散列表 | ~48N+32M |\n| 基于线性探测的散列表 | 在 ~32N 和 ~128N 之间 |\n| 各种二叉查找树 | ~56N |\n\n### 散列表无法达到理论最优性能原因\n\n* 每种类型的键都需要一个优秀的散列函数；\n* 性能保证来自于散列函数的质量；\n* 散列函数的计算可能复杂而且昂贵；\n* 难以支持有序性相关的符号表操作。\n\n\n"
  },
  {
    "path": "docs/Searching/3.5_应用.md",
    "content": "# 3.5 应用\n\n## 对符号表实现的选择\n\n| 算法（数据结构） | N 次插入后最坏情况下的查找成本 | N 次插入后最坏情况下的插入成本 | N 次随机插入后平均情况下的查找成本 | N 次随机插入后平均情况下的查找成本 | 是否高效支持有序性相关的操作\n| :----: | :----: | :----: | :----: | :----: | :----: |\n| 顺序查找（无序链表） | N | N | N/2 | N | 否\n| 二分查找（有序数组） | lgN | 2N | lgN | N | 是\n| 二叉树查找（BST） | N | N | 1.39lgN | 1.39lgN | 是\n| 2-3 树查找（红黑树） | 2lgN | 2lgN | lgN | lgN | 是\n| 拉链法*（链表数组） | <lgN | < lgN | N/(2M) | N/M | 否\n| 线性探测法*（并行数组） | clgN | clgN | <1.5 | <2.5 | 否\n\n*需要均匀并独立的散列函数\n\n对于典型的应用程序，应该在散列表和二叉查找树之间进行选择。\n\n散列表的优点：\n\n* 代码更简单；\n* 查找时间最优（常数级别，只要能有满足或近似满足均匀性假设的高效散列函数即可）；\n\n二叉查找树的优点：\n\n* 抽象结构更简单（无需设计散列函数）；\n* 红黑树可以保证最坏情况下的性能且能够支持的操作更多（如排名、选择、排序和范围查找）。\n\n### Java 标准库\n\nJava 的 java.util.TreeMap 和 java.util.HashMap 分别是基于红黑树和拉链法的散列表的符号表实现。\n\n## 稀疏向量\n\n实现矩阵和向量的乘法时，对于 N 行 N 列的矩阵，向量的大小也为 N，用数组实现时所需的时间和空间都与 N^2 成正比，这是不能接受的。\n\n鉴于矩阵常常是稀疏的（即其中大多数项都是 0），可以用 HashST 来实现一个稀疏向量类 [SparseVector](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/SparseVector.java)，所需时间仅和 N 加上矩阵中的非零元素的数量成正比。\n\n"
  },
  {
    "path": "docs/Sorting/2.1_初级排序算法.md",
    "content": "# 2.1 初级排序算法\n\n## 游戏规则\n\n### 排序算法类的模板\n\n```java\npublic class Example {\n    public static void sort(Comparable[] a) {\n        // 各类排序算法\n    }\n\n    private static boolean less(Comparable v, Comparable w) {\n        // 对元素进行比较\n        return v.compareTo(w) < 0;\n    }\n\n    private static void exch(Comparable[] a, int i, int j) {\n        // 将元素交换位置\n        Comparable t = a[i];\n        a[i] = a[j];\n        a[j] = t;\n    }\n\n    private static void show(Comparable[] a) {\n        // 在单行中打印数组\n        for(int i = 0; i < a.length; i++)\n            StdOut.print(a[i] + \" \");\n        StdOut.println();\n    }\n\n    public static boolean isSorted(Comparable[] a) {\n        // 测试数组元素是否有序\n        for(int i = 1; i < a.length; i++)\n            if(less(a[i], a[i - 1]))\n                return false;\n        return true;\n    }\n\n    public static void main(String[] args) {\n        // 从标准输入读取字符串，将它们排序并输出\n        String[] a = In.readStrings();\n        sort(a);\n        assert isSorted(a);\n        show(a);\n    }\n}\n```\n\n### 验证\n\n尽管一般都会测试代码并从数学上证明算法的正确性，但在实现每个排序算法时在测试代码中添加一条`assert isSorted(a);`来确认排序后数组元素都是有序的。\n\n### 运行时间\n\n**排序成本模型**：在研究排序算法时，我们需要计算**比较**和**交换**的数量。对于不交换元素的算法，我们会计算**访问数组的次数**。\n\n### 额外的内存时间\n\n排序算法可以分为两类：除了函数调用所需的栈和固定数目的实例变量之外无需额外内存的**原地排序算法**，以及需要额外内存空间来存储另一份数组副本的其他排序算法。\n\n### 数据类型\n\n数据模版适用于任何**实现了 Comparable 接口的数据类型**。Java 中封装数字的类型 Integer 和 Double，以及 String 和其他许多高级数据类型（如 File 和 URL）都实现了 Comparable 接口。\n\n而在**创建自己的数据类型**时，只要实现 Comparable 接口就能保证用例代码可以将其排序。要做到这一点，只需要实现一个`compareTo()`方法来定义目标类型对象的**自然次序**。\n\n## 选择排序\n\n最简单的排序算法，不断选择剩余元素之中的最小者，与遍历到的当前元素交换位置。\n\n```java\npublic static void sort(Comparable[] a) {\n    // 将 a[] 按升序排列\n    int N = a.length;\n    for(int i = 0 ; i < N; i++) {\n        // 将 a[i] 和 a[i...N]中最小的元素交换\n        int min = i;    // 最小元素的索引\n        for(int j = i+1; j < N; j++)\n            if(less(a[j], a[min]))\n                min = j;\n        exch(a, i, min);\n    }\n}\n```\n\n对于长度为 N 的数组，选择排序需要大约 N^2/2 次比较和 N 次交换。\n\n选择排序的特点：\n\n* 运行时间和输入无关：一个已经有序的数组或是主键全部相等的数组和一个元素随机排列的数组所用的排序时间一样长；\n* 数据移动是最少的：每次交换都会改变两个数组元素的值，因此选择排序用了 N 次交换——交换次数和数组的大小是**线性**关系。其他算法大多都是线性对数或是平方级别。\n\n## 插入排序\n\n每次将正在遍历的元素插入到其他已经有序的元素中的适当位置。与选择排序一样，当前索引左边的所有元素都是有序的，但它们的最终位置还不确定。为了给更小的元素腾出空间，它们可能会向右移动。当索引到达数组的右端时，数组排序就完成了。\n\n```java\npublic static void sort(Comparable[] a) {\n    // 将 a[] 按升序排列\n    int N = a.length;\n    for(int i = 1; i < N; i++) {\n        // 将 a[i] 插入到 a[i-1]、a[i-2]、a[i-3]...之中   \n        /** 有改进空间，见练习 2.1.25  */\n        for(int j = i; j > 0 && less(a[j], a[j-1]); j--)\n            exch(a, j, j-1);\n    }\n}\n```\n\n对于随机排列的长度为 N 且主键不重复的数组，平均情况下插入排序需要 ~N^2/4 次比较以及 ~N^2/4 次交换。最坏情况下需要 ~N^2/2 次比较和 ~N^2/2 次交换，最好情况下需要 N-1 次比较和 0 次交换。\n\n插入排序所需的时间取决于输入中元素的初始顺序。因此，插入排序对于**部分有序**的数组十分高效，也很适应小规模数组。\n\n选择排序和插入排序的可视化对比：\n\n![选择排序和插入排序的可视化对比](https://algs4.cs.princeton.edu/21elementary/images/bars.png)\n\n## 希尔排序\n\n**希尔排序**是一种基于插入排序的快速的排序算法，为了加快速度简单地改进了插入排序，交换不相邻的元素以对数组的局部进行排序，并最终用插入排序将局部有序的数组排序。\n\n**思想**：使数组中任意间隔为 h 的元素都是有序的。这样的数组被称为 **h 有序数组**。换句话说，一个 h 有序数组就是 h 个互相独立的有序数组编织在一起的一个数组。\n\n![2017-12-16 21 04 05](https://algs4.cs.princeton.edu/21elementary/images/h-sorted.png)\n\n希尔排序更高效的原因是它权衡了子数组的规模和有序性。排序之初各个子数组都很短，排序之后的子数组都是部分有序的，这两种情况都很适合插入排序。\n\n使用递增序列 1，4，13，40，121，364...的希尔排序所需的比较次数不会超出 N 的若干倍乘以递增序列的长度。\n\n希尔排序的代码量很小，且不需要使用额外的内存空间。对于中等大小的数组，它的运行时间是可以接受的。\n\n```java\npublic static void sort(Comparable[] a) {\n    // 将 a[] 按升序排列\n    int N = a.length;\n    int h = 1;\n    while(h < N / 3)\n        h = 3 * h + 1;    // 1, 4, 13, 40, 121, 364, 1093, ...\n    while(h >= 1) {\n        // 将数组变为 h 有序\n        for(int i = h; i < N; i++) {\n            // 将 a[i] 插入到 a[i-h]，a[i-2*h]，a[i-3*h]... 之中\n            for(int j = i; j >= h && less(a[j], a[j -h]); j -= h)\n                exch(a, j, j-h);\n        }\n        h /= 3;\n    }\n}\n```\n\n\n\n"
  },
  {
    "path": "docs/Sorting/2.2_归并排序.md",
    "content": "# 2.2 归并排序\n\n**归并**：将两个有序的数组归并成一个更大的有序数组。\n\n归并排序能保证将任意长度为 N 的数组排序所需时间和 NlogN 成正比；但主要缺点是所需的额外空间和 N 成正比。\n\n每一次归并将涉及的所有元素复制到一个辅助数组中，再把归并的结果放回原数组中。\n\n## 自顶向下的归并排序\n\n归并算法是算法设计中**分治思想**的典型应用。\n\n**比较次数**：对于长度为 N 的任意数组，自顶向下的归并排序需要 1/2NlgN 至 NlgN 次比较。\n\n注：N = 2 ^ n  ==>  n = lgN\n\n**访问数组次数**：对于长度为 N 的任意数组，自顶向下的归并排序最多需要访问数组 6NlgN 次。\n\n### 性能优化点\n\n#### 对小规模子数组使用插入排序\n\n**递归**会使**小规模问题**中方法的调用过于频繁，所以改进对它们的处理方法就能改进整个算法。\n\n对排序来说，插入排序（或选择排序）可能在小数组上比归并排序更快。\n\n## 自底向上的归并排序\n\n对于长度为 N 的任意数组，自底向上的归并排序需要 1/2NlgN 至 NlgN 次比较，最多需要访问数组 6NlgN 次。\n\n自底向上的归并排序比较适合用**链表**组织的数据。将链表按大小为 1 的子链表进行排序，然后是大小为 2 的子链表，然后是大小为 4 的子链表等。这种方法只需要重新组织链表链接就能将链表**原地**排序。\n\n## 排序算法的复杂度\n\n**命题**：没有任何基于比较的算法能够保证使用少于 lg(N!) ~ NlgN 次比较将长度为 N 的数组排序。\n\n**证明**：\n\n假设没有重复的主键（因为这是所有排序算法的必要需求）。N 个不同的主键会有 N! 种不同的排列。\n\n任何基于比较的排序算法都对应着一颗高 h 的比较树，其中`N! <= 叶子结点的数量 <= 2^h`。h 的值就是最坏情况下的比较次数，因此对不等式的两边取对数可得到任意算法的比较次数至少是 lgN!。\n\n根据斯特灵公式可得 lgN! ~ NlgN。\n\n注：斯特灵公式：`lgN! = lg1 + lg2 + ... + lgN ~ NlgN`\n\n归并排序是一种渐进最优的基于比较排序的算法。也就是说，归并排序在最坏情况下的比较次数和任意基于比较的排序算法所需的最少比较次数都是 ~NlgN。\n\n\n"
  },
  {
    "path": "docs/Sorting/2.3_快速排序.md",
    "content": "# 2.3 快速排序\n\n**特点：**\n\n* 原地排序（只需要一个很小的辅助栈）；\n* 将长度为 N 的数组排序所需的时间和 NlgN 成正比。\n\n## 基本算法\n\n快速排序的**切分**方法：\n\n一般策略是先随意地选取 a[lo] 作为**切分元素**，即那个会被排定的元素，然后我们从数组的左端开始向右扫描直到找到一个**大于等于**它的元素，再从数组的右端开始向左扫描直到找到一个小于等于它的元素。这两个元素显然是没有排定的，因此我们交换它们的位置。\n\n如此继续，我们就可以保证左指针 i 的左侧元素都不大于切分元素，右指针 j 的右侧元素都不小于切分元素。当两个指针相遇时，我们只需要将切分元素 a[lo] 和左子数组最右侧的元素（a[j]）交换然后返回 j 即可。\n\n## 性能特点\n\n快速排序的两个速度优势：\n\n1. 切分方法的内循环会用一个递增的索引将数组元素和一个定值比较，而归并排序、希尔排序等还在内循环中移动数据；\n2. 比较次数少。\n\n将长度为 N 的无重复数组排序，快速排序平均需要 ~2NlnN 次比较（以及 1/6 的交换）。\n\n### 潜在缺点\n\n快速排序的最好情况是每次都正好能将数组对半分。而**在切分不平衡**时，这个程序可能会最多需要约 **N^2/2** 次比较。例如，如果第一次从最小的元素切分，第二次从第二小的元素切分，如此这般，每次调用只会移除一个元素。\n\n因此，我们在快速排序前将数组随机排序，以避免上述情况。\n\n## 算法改进\n\n### 切换到插入排序\n\n和大多数递归排序算法一样，改进快速排序性能的一个简单办法基于以下两点：\n\n* 对于小数组，快速排序比插入排序慢；\n* 因为递归，快速排序的`sort()`方法在小数组中也会调用自己。\n\n因此，在排序**小数组**时应该切换到插入排序。\n\n### 三取样切分\n\n使用子数组中的一小部分元素的中位数来切分数组。这样做得到的切分更好，但代价是需要计算中位数。\n\n### 熵最优的排序\n\n在**有大量重复元素**的情况下，快速排序的递归性会使元素全部重复的子数组经常出现，这就有很大的改进潜力，将当前实现的线性对数级的性能提高到**线性级别**。\n\n一个简单的想法是将数组切分为**三部分**，分别对应小于、等于和大于切分元素的数组元素。这种做法被称为“三向切分”。\n\n命题 1：不存在任何基于比较的排序算法能够保证在 NH-N 次比较之内将 N 个元素排序，其中 H 为由主键值出现频率定义的香农信息量。\n\n命题 2：对于大小为 N 的数组，三向切分的快速排序需要 ~(2ln2)NH 次比较。其中 H 为由主键值出现频率定义的香农信息量。\n\n**香农信息素**是对信息含量的一种标准的度量方法。给定包含 k 个不同值的 N 个主键，对于从 1 到 k 的每个 i，定义 fi 为第 i 个主键值出现的次数，pi 为 fi/N，即为随机抽取一个数组元素时第 i 个主键值出现的概率。那么所有主键的**香农信息素**可以定义为：\n\nH = -(p1lgp1 + p2lgp2 + .. + pklgpk)\n"
  },
  {
    "path": "docs/Sorting/2.4_优先队列.md",
    "content": "# 2.4 优先队列\n\n优先队列最重要的操作就是**插入元素**和**删除最大元素**。\n\n**应用场景：**在某些数据处理的场合，**总数据量太大**（可以认为输入是无限的），无法排序（甚至无法全部装进内存）。如果将每个新的输入和已知的 M 个最大（或最小）元素比较，除非 M 较小，否则这种比较的代价会非常高昂。如果有了**优先队列**，就只用一个能存储 M 个元素的队列即可。\n\n## 初级实现\n\n* 数组实现（无序）：惰性方法，仅在必要的时候找出最大元素；\n* 数组实现（有序）：积极方法：在插入时就保持列表有序，使后续操作更高效；\n* 链表表示法\n\n在上述优先队列的初级实现中，**删除最大元素**和**插入元素**这两个操作之一在最坏情况下需要**线性**时间来完成。\n\n| 数据结构 | 插入元素 | 删除最大元素 |\n| :----: | :----: | :----: |\n| 有序数组 | N | 1 |\n| 无序数组 | 1 | N |\n| 堆 | logN | logN |\n| 理想情况 | 1 | 1 |\n\n## 堆的定义\n\n当一棵二叉树的每个结点都**大于等于**它的两个子结点时，它被称为**堆有序**。\n\n根结点是堆有序的二叉树中的最大结点。\n\n### 二叉堆表示法\n\n如果使用指针来表示堆有序的二叉树，那么每个元素都需要**三个指针**来找到它的上下结点。\n\n但使用完全二叉树，只需要数组而不需要指针就可以表示，十分方便。具体方法是将二叉树的结点按照**层级顺序**放入数组中。\n\n**定义**：**二叉堆**（后文简称为堆）是一组能够用堆有序的完全二叉树排序的元素，并在数组中按照层级储存（不使用数组的第一个位置）。\n\n在一个堆中，位置`k`的结点的父结点的位置为`⌊k/2⌋`，子结点位置分别为`2k`和`2k+1`。\n\n**高性能的原因**：利用在数组中无需指针即可沿树上下移动的便利。\n\n注：完全二叉树：除最后一层外，每一层上的结点数均达到最大值；在最后一层上只缺少右边的若干结点。\n\n一棵大小为 N 的完全二叉树的高度为`⌊lgN⌋`。\n\n## 堆的算法\n\n**堆的有序化**：打破堆的状态，然后再遍历堆并按照要求将堆的状态恢复。\n\n**插入元素**时，将新元素加到数组末尾，增加堆的大小并让这个新元素上浮到合适的位置。\n\n**删除最大元素**时，从数组顶端删去最大的元素并将数组的最后一个元素放到顶端，减小堆的大小并让这个元素下沉到合适的位置。\n\n这样，**删除最大元素**和**插入元素**这两个操作的用时和队列的大小仅成**对数**关系。对于一个含有 N 个元素的基于堆的优先队列，插入元素操作只需不超过 (lgN+1) 次比较，删除最大元素的操作需要不超过 2lgN 次比较。\n\n## 堆排序\n\n用下沉操作由 N 个元素构造堆只需少于 2N 次比较以及少于 N 次交换。\n\n将 N 个元素排序，堆排序只需少于 (2NlgN+2N) 次比较（以及一半次数的交换）。\n\n### 特点\n\n**堆排序的优点**：所知的唯一能够同时最优地利用空间和时间的方法；\n\n**堆排序的缺点**：**无法利用缓存**。数组元素很少和相邻的其他元素进行比较，因此缓存未命中的次数要远远高于大多数比较都在相邻元素间进行的算法（如快速排序、归并排序、希尔排序）。\n\n**堆排序的使用场景**：当空间十分紧张时（例如在嵌入式系统或低成本的移动设备中）很流行，但现代系统的许多应用很少使用它。"
  },
  {
    "path": "docs/Sorting/2.5_应用.md",
    "content": "# 2.5 应用\n\n## 稳定性\n\n如果一个排序算法能够保留数组中**重复元素的相对位置**则可以被称为是**稳定**的。\n\n* 稳定的排序算法：插入排序、归并排序\n* 不稳定的排序算法：选择排序、希尔排序、快速排序和堆排序\n\n一般只有在稳定性是必要的情况下，稳定的排序算法才有优势。\n\n## 各种排序算法的性能特点\n\n| 算法 | 是否稳定 | 是否为原地排序 | 时间复杂度 | 空间复杂度 | 备注\n| :----: | :----: | :----: | :----: | :----: | :----: |\n| 选择排序 | 否 | 是 | N^2 | 1 | \n| 插入排序 | 是 | 是 | 介于 N 和 N^2 之间 | 1 | 取决于输入元素的排列情况 \n| 希尔排序 | 否 | 是 | NlogN? | 1 | \n| 快速排序 | 否 | 是 | NlogN | lgN | 运行效率由概率提供保证 \n| 三向快速排序 | 否 | 是 | 介于 N 和 NlogN 之间 | lgN | 运行效率由概率保证，同时也取决于输入元素的分布情况 \n| 归并排序 | 是 | 否 | NlogN | N | \n| 堆排序 | 否 | 是 | NlogN | 1 | \n\n快速排序是最快的通用排序算法。\n\n### Java 系统库的排序算法\n\nJava 的系统程序员选择对**原始数据**类型使用（三向切分的）快速排序，对**引用类型**使用归并排序。暗示着用速度和空间（对于原始数据类型）来换取稳定性（对于引用类型）。\n\n\n"
  },
  {
    "path": "docs/Strings/5.2_单词查找树.md",
    "content": "# 5.2 单词查找树\n\n* 查找命中所需的时间与被查找的键的长度成正比；\n* 查找未命中只需检查若干个字符。\n\n## 单词查找树\n\n单词查找树是由链接的结点所组成的数据结构，这些链接可能为空，也可能指向其他结点。每个结点都含有 R 条链接，其中 R 为字母表的大小（即字母表中字母的数量）。\n\n**值为空的结点在符号表中没有对应的键，它们的存在是为了简化单词查找树中的查找操作。**\n\n### 查找操作\n\n### 插入操作\n\n### 结点的表示\n\n## 单词查找树的性质\n\n单词查找树的链表结构（形状）和键的插入或删除顺序无关：对于任意给定的一组键，其单词查找树都是唯一的。\n\n## 三向单词查找树\n\n## 总结\n\n如果空间足够，R 向单词查找树的速度是最快的，能够在**常数**次字符比较内完成查找。\n\n对应大型字母表，R 向单词查找树所需的空间可能无法满足时，三向查找树是最佳的选择，因为它对“字符”比较次数是**对数级别**的比较，而二叉查找树中键的比较次数是对数级别的。\n\n![字符串查找算法特点](https://user-images.githubusercontent.com/18595460/34460004-4c0ccdf2-ee3c-11e7-9786-2c380daaf47d.png)\n"
  },
  {
    "path": "docs/Strings/5.3_子字符串查找.md",
    "content": "# 5.3 子字符串查找\n\n* 问题描述：给定一段长度为 N 的文本和一个长度为 M 的**模式（pattern）**字符串，在文本中找到一个和该模式相符的子字符串。\n* 限制：模式相对文本较短（M 可能等于 100 或者 1000），而文本相对模式很长（N 可能等于 100 万或者 10 亿）。\n\n## 暴力子字符串查找算法\n\n在最坏情况下运行时间与 MN 成正比；但由于绝大多数比较在第一个字符时就会产生不匹配，实际运行时间一般与 M+N 成正比。\n\n实现 1：\n\n```java\npublic static int search(String pat, String txt) {\n    int M = pat.length();\n    int N = txt.length();\n    for(int i = 0; i <= N-M; i++) {\n        int j;\n        for(j = 0; j < M; j++)\n            if(txt.charAt(j+i) != pat.charAt(j))\n                break;\n        if(j == M)\n            return i;    // 找到匹配\n    }\n    return N;    // 未找到匹配\n}\n```\n\n实现 2：显式回退\n\n```java\npublic static int search(String pat, String txt) {\n    int M = pat.length();\n    int N = txt.length();\n    int i, j;\n    for(i = 0, j = 0; i < N && j < M; i++) {\n        if(txt.charAt(i) == pat.charAt(j))\n            j++;\n        else {\n            i -= j;\n            j = 0;\n        }\n    }\n    if(j == M)\n        return i - M;    // 找到匹配\n    else\n        return N;    // 未找到匹配\n}\n```\n\n## KMP 子字符串查找算法\n\n基本思想：在匹配失败之前，一部分文本的内容已经和模式相匹配。因此不该完全从头开始匹配。\n\n设置：\n\n* 文本指针 i，模式指针 j\n* 数组 dfa[][]：记录匹配失败时模式指针 j 应该回退多远。\n\n在查找中，`dfa[txt.charAt(i)][j]`是在比较了`txt.charAt(i)`和`pat.charAt(j)`之后应该和`txt.charAt(i+1)`比较的模式字符位置。\n\n### DFA 模拟\n\n![kmp-dfa](https://user-images.githubusercontent.com/18595460/38723782-bc4dffd4-3f34-11e8-8cf3-a35ace403528.png)\n\n自动机每次从左向右从文本中读取一个字符并移动到一个新的状态。\n\n```java\nfor(i = 0, j = 0; i < N && j < M; i++)\n    j = dfa[txt.charAt(i)][j];\n```\n\n* 对于一个匹配的转换，j 就向右移动一位，因为`dfa[pat.charAt(j)][j]`的值总是`j+1`；\n* 对于一个非匹配转换，j 就向左移动。\n\n循环结束后，若`j == M`，说明找到匹配，返回`i - M`。\n\n### 构造 DFA\n\n当在`pat.charAt(j)`处匹配失败时，如果回退了文本指针并在右移一位之后重新扫描已知的文本字符，DFA 的状态会是什么？  =>  **重启状态 X**：将 DFA 重置到的适当状态，如同已经回退过文本指针一样。\n\n例如，对于 A B A B A C，要判断在 j=5 时匹配失败后 DFA 应该怎么做。通过 DFA 可以知道完全回退之后算法会扫描 B A B A 并达到状态 3，因此可以**将`dfa[][3]`复制到`dfa[][5]`**并将 C 所对应的元素的值设为 6（因为`pat.charAt(5)`是 C）。\n\n因为在计算 DFA 的第 j 个状态时，只需要知道 DFA 是如何处理前 j-1 个字符的，所以总能从尚不完整的 DFA 中得到所需信息。\n\n```java\ndfa[pat.charAt(0)][0] = 1;\nfor(int X = 0, j = 1; j < M; j++) {\n    // 计算 dfa[][j]\n    for(int ch = 0; ch < R; ch++)\n        dfa[ch][j] = dfa[ch][X];    // 复制匹配失败情况下的值\n    dfa[pat.charAt(j)][j] = j+1;  // 设置匹配成功情况下的值\n    X = dfa[pat.charAt(j)][X];    // 更新重启状态（和前面自动机从文本读取字符并移动相似）\n}\n```\n\n### 代码实现\n\n```java\npublic class KMP {\n\n    private String pat;\n    private int[][] dfa;\n    public KMP(String pat) {\n        this.pat = pat;\n        int M = pat.length();\n        int R = 256;\n        dfa = new int[R][M];\n        dfa[pat.charAt(0)][0] = 1;\n        for(int X = 0, j = 1; j < M; j++) {\n            // 计算 dfa[][j]\n            for(int ch = 0; ch < R; ch++)\n                dfa[ch][j] = dfa[ch][X];    // 复制匹配失败情况下的值\n            dfa[pat.charAt(j)][j] = j+1;  // 设置匹配成功情况下的值\n            X = dfa[pat.charAt(j)][X];    // 更新重启状态\n        }\n    }\n    \n    public int search(String txt) {\n        int i, j, N = txt.length(), M = pat.length();\n        for(i = 0, j = 0; i < N && j < M; i++)\n            j = dfa[txt.charAt(i)][j];\n        if(j == M)\n            return i - M;    // 找到匹配（到达模式字符串的结尾）\n        else\n            return N;    // 未找到匹配（到达文本字符串的结尾）\n    }\n}\n```\n\n### 性能总结\n\n对于长度为 M 的模式字符串和长度为 N 的文本，KMP 字符串查找算法**访问的字符不会超过 M+N 个**：模式字符串每个字符一次，文本字符串最坏情况下每个字符一次。\n\nKMP 比暴力算法的速度优势并不十分明显，但优点是不需要在输入中回退。因此，**KMP 更适合在长度不确定的输入流中进行查找**，需要回退的算法在这种情况下则需要复杂的缓冲机制（但当回退很容易时，可以比 KMP 快得多）。\n\n## Boyer-Moore 字符串查找算法\n\n基本思想：使用数组`right[]`记录字母表中的每个字符串在模式中出现的**最靠右**的地方（如果字符在模式中不存在则表示为 -1）。这个值表示如果该字符造成匹配失败时，应该向右跳跃多远。\n\n```java\nfor(int c = 0; c < R; c++)\n    right[c] = -1;    // 不包含在模式字符串中的字符的值为 -1\nfor(int j = 0; j < M; j++)       // 包含在模式字符串中的字符的值为\n    right[pat.charAt(j)] = j;    // 它在其中出现的最右位置\n```\n\n文本索引 i 从左向右移动，匹配时模式索引 j **从右向左**移动。匹配失败会遇到以下三种情况：\n\n* 如果造成匹配失败的字符不包含在模式字符串中，`i`增加`j+1`；\n* 如果造成匹配失败的字符包含在模式字符串中，则对齐，`i`增加`j-right[txt.charAt(i+j)]`；\n* 如果这种情况无法增大`i`（例如，对齐导致模式字符串向左移动），那就直接将`i`加 1 来保证模式字符串至少向右移动了一个位置。\n\n其中，通过将不在模式字符串的字符`ch`的`right[ch]`设置为 -1，可以将情况 1 合并到情况 2 中。\n\n![boyer-moore](https://user-images.githubusercontent.com/18595460/38733263-d01cf2d0-3f53-11e8-9928-44833bc02153.jpg)\n\n### 代码实现\n\n```java\npublic class BoyerMoore {\n    \n    private int[] right;\n    private String pat;\n\n    // 计算跳跃表\n    public BoyerMoore(String pat) {\n        this.pat = pat;\n        int M = pat.length();\n        int R = 256;\n        right = new int[R];\n        for(int c = 0; c < R; c++)\n            right[c] = -1;    // 不包含在模式字符串中的字符的值为 -1\n        for(int j = 0; j < M; j++)       // 包含在模式字符串中的字符的值为\n            right[pat.charAt(j)] = j;    // 它在其中出现的最右位置\n    }\n    \n    // 在 txt 中查找模式字符串\n    public int search(String txt) {\n        int N = txt.length();\n        int M = pat.length();\n        int skip;\n        for(int i = 0; i <= N-M; i += skip) {\n            // 模式字符串和文本在位置 i 匹配吗？\n            skip = 0;\n            for(int j = M-1; j >= 0; j--)\n                if(pat.charAt(j) != txt.charAt(i+j)) {\n                    skip = j - right[txt.charAt(i+j)];\n                    if(skip < 1)\n                        skip = 1;\n                    break;\n                }\n            if(skip == 0)\n                return i;    // 找到匹配\n        }\n        return N;    // 未找到匹配\n    }\n}\n```\n\n### 性能总结\n\n在许多实际应用场景中，模式字符串中仅含有字母表中的若干字符是很常见的，因此几乎所有的比较都会使算法跳过 M 个字符。\n\n由此可知，在一般情况下，对于长度为 N 的文本和长度为 M 的模式字符串，Boyer-Moore 算法需要 ~N/M 次字符比较。\n\n## Rabin-Karp 指纹字符串查找算法\n\n“指纹”表示算法基于**散列**并用极少信息表示了模式字符串。\n\n![Rabin-Karp.png](https://upload-images.jianshu.io/upload_images/2702529-4b3cf0a06d503a2d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### 验证正确性\n\n为了确保得到了一个匹配的字符串（而非散列值相同），可能需要添加回退文本指针并逐个字符串比较的代码，这种方式被称为**拉斯维加斯**算法。\n\n相对的，将散列表规模设为任意大的一个值以将冲突概率降低到绝对小的方法被称为**蒙特卡洛**算法。\n\n### 性能总结\n\n* 使用蒙特卡洛算法的 Rabin-Karp 子字符串查找算法的运行时间是线性级别的，且出错的概率极小；\n* 使用拉斯维加斯算法的 Rabin-Karp 子字符串查找算法能够保证正确性且性能及其接近线性级别。\n\n## 总结\n\n* 暴力查找算法：\n  * 优点：实现简单，且在一般的情况下都工作良好；\n  * 缺点：所需时间可能与 MN 成正比；\n  * Java 的 String 类型的`indexOf()`方法使用。\n\n* [KMP 算法](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/KMP.java)：\n  * 优点：保证线性级别的性能，且不需要在正文中回退；\n  * 缺点：需要额外的内存空间。\n\n* [Boyer-Moore 算法](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/BoyerMoore.java)：\n  * 优点：一般情况下性能为亚线性级别（可能是线性级别的 M 倍）；\n  * 缺点：需要额外的内存空间。\n\n* [Rabin-Karp 算法](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/RabinKarp.java)：\n  * 优点：线性级别；\n  * 缺点：内循环很长（若干次算术运算，而其他算法只需要比较字符）。\n\n![cost-of-substring-searching](https://user-images.githubusercontent.com/18595460/38733998-9f872d40-3f56-11e8-8e37-d517e014ed2a.jpg)\n\n\n"
  },
  {
    "path": "docs/_sidebar.md",
    "content": "- **第 1 章 基础**\n  - 1.1 基础编程模型\n  - 1.2 数据抽象\n  - [1.3 背包、队列和栈](Fundamentals/1.3_背包、队列和栈)\n  - [1.4 算法分析](Fundamentals/1.4_算法分析)\n  - [1.5 案例研究：union-find算法](Fundamentals/1.5_案例研究：union-find算法)\n- **第 2 章 排序**\n  - [2.1 初级排序算法](Sorting/2.1_初级排序算法)\n  - [2.2 归并排序](Sorting/2.2_归并排序)\n  - [2.3 快速排序](Sorting/2.3_快速排序)\n  - [2.4 优先队列](Sorting/2.4_优先队列)\n  - [2.5 应用](Sorting/2.5_应用)\n- **第 3 章 查找**\n  - [3.1 符号表](Searching/3.1_符号表)\n  - [3.2 二叉查找树](Searching/3.2_二叉查找树)\n  - [3.3 平衡查找树](Searching/3.3_平衡查找树)\n  - [3.4 散列表](Searching/3.4_散列表)\n  - [3.5 应用](Searching/3.5_应用)\n- **第 4 章 图**\n  - [4.1 无向图](Graphs/4.1_无向图)\n  - [4.2 有向图](Graphs/4.2_有向图)\n  - [4.3 最小生成树](Graphs/4.3_最小生成树)\n  - [4.4 最短路径](Graphs/4.4_最短路径)\n- **第 5 章 字符串**\n  - 5.1 字符串排序\n  - [5.2 单词查找树](Strings/5.2_单词查找树)\n  - [5.3 子字符串查找](Strings/5.3_子字符串查找)\n  - 5.4 正则表达式\n  - 5.5 数据压缩\n- **第 6 章 背景**\n  - [6.1 事件驱动模拟](Context/6.1_事件驱动模拟)\n  - [6.2 B- 树](Context/6.2_B-树)\n  - [6.3 后缀数组](Context/6.3_后缀数组)\n  - [6.4 网络流算法](Context/6.4_网络流算法)\n  - [6.5 问题规约](Context/6.5_问题规约)\n  - [6.6 不可解性](Context/6.6_不可解性)"
  },
  {
    "path": "docs/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <title>《算法（第4版）》笔记</title>\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n  <meta name=\"description\" content=\"《算法（第4版）》笔记\">\n  <meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0\">\n  <link rel=\"stylesheet\" href=\"//unpkg.com/docsify/lib/themes/vue.css\">\n</head>\n<body>\n  <div id=\"app\">加载中...</div>\n  <script>\n    window.$docsify = {\n      name: '《算法（第4版）》笔记',\n      repo: 'https://github.com/bighuang624/Algorithms-notes',\n      loadSidebar: true,\n      subMaxLevel: 4,\n      themeColor: '#F5A623',\n      executeScript: true,\n      auto2top: true,\n      search: {\n        placeholder: '搜索'\n      }\n    }\n  </script>\n  <script src=\"//unpkg.com/docsify/lib/docsify.min.js\"></script>\n  <script src=\"//unpkg.com/docsify/lib/plugins/external-script.js\"></script>\n  <script src=\"//unpkg.com/docsify/lib/plugins/search.js\"></script>\n</body>\n</html>\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"Algorithms-notes\",\n  \"version\": \"1.0.0\",\n  \"description\": \"《算法（第4版）》笔记\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n    \"preupdate\": \"cd code && yuki && cd .. && git add docs code README.md\",\n    \"update\": \"git commit -m\",\n    \"postupdate\": \"git push origin master\" \n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/bighuang624/LeetCode-everyday.git\"\n  },\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"bugs\": {\n    \"url\": \"https://github.com/bighuang624/LeetCode-everyday/issues\"\n  },\n  \"homepage\": \"https://github.com/bighuang624/LeetCode-everyday#readme\"\n}\n"
  },
  {
    "path": "每一节可以再看一遍的题.md",
    "content": "## 每一节可以再看一遍的题\n\n### 1.1\n\n1.1.9 将一个正整数 N 用二进制表示并转换为一个 String 类型的 s\n"
  },
  {
    "path": "相关问题解决方法.md",
    "content": "## Eclipse命令行参数使用\n\nRun---->Run Configurations----->右边 Arguments 里 Program arguments 中写。\n\n如果写的是文件，默认该文件要放在项目的根目录里。当然也可以换位置，勾选 Working directory 的 Other，然后选择文件目录即可。"
  }
]