Repository: bighuang624/Algorithms-notes Branch: master Commit: e598780a9ecf Files: 169 Total size: 543.9 KB Directory structure: gitextract_vx5c0m3w/ ├── .gitignore ├── README.md ├── code/ │ ├── README.md │ ├── algs4/ │ │ ├── Alphabet.java │ │ ├── Bag.java │ │ ├── BinarySearch.java │ │ ├── BinaryStdIn.java │ │ ├── BinaryStdOut.java │ │ ├── Counter.java │ │ ├── DepthFirstOrder.java │ │ ├── Draw.java │ │ ├── DrawListener.java │ │ ├── Heap.java │ │ ├── HexDump.java │ │ ├── In.java │ │ ├── IndexMinPQ.java │ │ ├── Interval1D.java │ │ ├── Interval2D.java │ │ ├── MinPQ.java │ │ ├── Out.java │ │ ├── Particle.java │ │ ├── Picture.java │ │ ├── PictureDump.java │ │ ├── Point2D.java │ │ ├── Queue.java │ │ ├── SET.java │ │ ├── ST.java │ │ ├── Stack.java │ │ ├── StdDraw.java │ │ ├── StdIn.java │ │ ├── StdOut.java │ │ └── StdRandom.java │ ├── chapter1_1_Programming_Model/ │ │ ├── BinarySearch.java │ │ ├── BouncingBall.java │ │ ├── Ex1.java │ │ ├── Ex10.java │ │ ├── Ex11.java │ │ ├── Ex13.java │ │ ├── Ex14.java │ │ ├── Ex15.java │ │ ├── Ex19.java │ │ ├── Ex2.java │ │ ├── Ex20.java │ │ ├── Ex3.java │ │ ├── Ex30.java │ │ ├── Ex31.java │ │ ├── Ex32.java │ │ ├── Ex6.java │ │ ├── Ex7a.java │ │ ├── Ex7b.java │ │ ├── Ex7c.java │ │ ├── Ex8.java │ │ ├── Ex9.java │ │ ├── RightTriangle.java │ │ ├── Sattolo.java │ │ └── StdDrawTest.java │ ├── chapter1_2_Data_Abstraction/ │ │ ├── Accumulator.java │ │ ├── AccumulatorTest.java │ │ ├── Cat.java │ │ ├── Date.java │ │ ├── Flips.java │ │ ├── FlipsMax.java │ │ ├── Interval2DTest.java │ │ ├── Rolls.java │ │ ├── StaticSETofInts.java │ │ ├── VisualAccumulator.java │ │ ├── VisualAccumulatorTest.java │ │ ├── WhiteList.java │ │ ├── in1.txt │ │ └── in2.txt │ ├── chapter1_3_Bags_Queues_Stacks/ │ │ └── ResizingArrayStack.java │ ├── chapter1_4_Analysis_of_Algorithms/ │ │ ├── DoublingRatio.java │ │ ├── DoublingTest.java │ │ ├── Stopwatch.java │ │ ├── StopwatchTest.java │ │ └── ThreeSum.java │ ├── chapter1_5_Case_Study_Union_Find/ │ │ ├── UF.java │ │ └── WeightedQuickUnionUF.java │ ├── chapter2_1_Elementary_Sorts/ │ │ ├── Insertion.java │ │ ├── Selection.java │ │ ├── Shell.java │ │ └── SortCompare.java │ ├── chapter2_2_Mergesort/ │ │ ├── Merge.java │ │ └── MergeBU.java │ ├── chapter2_3_Quicksort/ │ │ ├── Ex25.java │ │ ├── Quick.java │ │ └── Quick3way.java │ ├── chapter2_4_Priority_Queues/ │ │ ├── MaxPQ.java │ │ └── TopM.java │ ├── chapter3_1_Symbol_Tables/ │ │ ├── BinarySearchST.java │ │ ├── FrequencyCounter.java │ │ └── SequentialSearchST.java │ ├── chapter3_2_Binary_Search_Trees/ │ │ └── BST.java │ ├── chapter3_4_Hash_Tables/ │ │ ├── LinearProbingHashST.java │ │ └── SeparateChainingHashST.java │ ├── chapter3_5_Searching_Applications/ │ │ ├── SparseVector.java │ │ └── WhiteFilter.java │ ├── chapter4_1_Undirected_Graphs/ │ │ ├── BreadthFirstPaths.java │ │ ├── CC.java │ │ ├── Cycle.java │ │ ├── DegreesOfSeparation.java │ │ ├── DepthFirstPaths.java │ │ ├── DepthFirstSearch.java │ │ ├── Graph.java │ │ ├── SymbolGraph.java │ │ ├── TestCC.java │ │ ├── TestPaths.java │ │ ├── TestSearch.java │ │ ├── TestSymbolGraph.java │ │ └── TwoColor.java │ ├── chapter4_2_Directed_Graphs/ │ │ ├── DepthFirstOrder.java │ │ ├── Digraph.java │ │ ├── DirectedCycle.java │ │ ├── DirectedDFS.java │ │ ├── KosarajuSCC.java │ │ ├── SymbolDigraph.java │ │ ├── Topological.java │ │ └── TransitiveClosure.java │ ├── chapter4_3_Minimum_Spanning_Tree/ │ │ ├── Edge.java │ │ ├── EdgeWeightedGraph.java │ │ ├── KruskalMST.java │ │ ├── LazyPrimMST.java │ │ ├── PrimMST.java │ │ ├── TestMST.java │ │ └── UF.java │ ├── chapter4_4_Shortest_Paths/ │ │ ├── DijkstraSP.java │ │ ├── DirectedEdge.java │ │ ├── EdgeWeightedDigraph.java │ │ ├── SP.java │ │ └── TestSP.java │ ├── chapter5_3_Substring_Search/ │ │ ├── BoyerMoore.java │ │ ├── KMP.java │ │ └── RabinKarp.java │ ├── chapter6_3_Suffix_Arrays/ │ │ ├── KWIC.java │ │ ├── LRS.java │ │ └── SuffixArray.java │ └── yuki.config.json ├── docs/ │ ├── .nojekyll │ ├── Context/ │ │ ├── 6.1_事件驱动模拟.md │ │ ├── 6.2_B-树.md │ │ ├── 6.3_后缀数组.md │ │ ├── 6.4_网络流算法.md │ │ ├── 6.5_问题规约.md │ │ └── 6.6_不可解性.md │ ├── Fundamentals/ │ │ ├── 1.3_背包、队列和栈.md │ │ ├── 1.4_算法分析.md │ │ └── 1.5_案例研究:union-find算法.md │ ├── Graphs/ │ │ ├── 4.1_无向图.md │ │ ├── 4.2_有向图.md │ │ ├── 4.3_最小生成树.md │ │ └── 4.4_最短路径.md │ ├── README.md │ ├── Searching/ │ │ ├── 3.1_符号表.md │ │ ├── 3.2_二叉查找树.md │ │ ├── 3.3_平衡查找树.md │ │ ├── 3.4_散列表.md │ │ └── 3.5_应用.md │ ├── Sorting/ │ │ ├── 2.1_初级排序算法.md │ │ ├── 2.2_归并排序.md │ │ ├── 2.3_快速排序.md │ │ ├── 2.4_优先队列.md │ │ └── 2.5_应用.md │ ├── Strings/ │ │ ├── 5.2_单词查找树.md │ │ └── 5.3_子字符串查找.md │ ├── _sidebar.md │ └── index.html ├── package.json ├── 每一节可以再看一遍的题.md └── 相关问题解决方法.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Compiled class file *.class # Log file *.log # BlueJ files *.ctxt # Mobile Tools for Java (J2ME) .mtj.tmp/ # Package Files # *.jar *.war *.ear *.zip *.tar.gz *.rar # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* ================================================ FILE: README.md ================================================ # 《算法(第4版)》笔记及代码 [](http://kyonhuang.top) ## 笔记 推荐阅览 html 版本的笔记,由 [docsify](https://docsify.js.org/#/zh-cn/) 动态生成文档网站。 [在线阅览地址](http://kyonhuang.top/Algorithms-notes/) ## 目录 * [《每一节可以再看一遍的题》](https://github.com/bighuang624/Algorithms-notes/blob/master/每一节可以再看一遍的题.md) * [《相关问题解决方法》](https://github.com/bighuang624/Algorithms-notes/blob/master/相关问题解决方法.md) ### Fundamentals * [《1.3_背包、队列和栈》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.3_背包、队列和栈.md) * [《1.4_算法分析》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.4_算法分析.md) * [《1.5_案例研究:union-find算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Fundamentals/1.5_案例研究:union-find算法.md) ### Sorting * [《2.1_初级排序算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.1_初级排序算法.md) * [《2.2_归并排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.2_归并排序.md) * [《2.3_快速排序》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.3_快速排序.md) * [《2.4_优先队列》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.4_优先队列.md) * [《2.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Sorting/2.5_应用.md) ### Searching * [《3.1_符号表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.1_符号表.md) * [《3.2_二叉查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.2_二叉查找树.md) * [《3.3_平衡查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.3_平衡查找树.md) * [《3.4_散列表》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.4_散列表.md) * [《3.5_应用》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Searching/3.5_应用.md) ### Graphs * [《4.1_无向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.1_无向图.md) * [《4.2_有向图》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.2_有向图.md) * [《4.3_最小生成树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.3_最小生成树.md) * [《4.4_最短路径》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Graphs/4.4_最短路径.md) ### Strings * [《5.2_单词查找树》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.2_单词查找树.md) * [《5.3_子字符串查找》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Strings/5.3_子字符串查找.md) ### Context * [《6.3_后缀数组》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.3_后缀数组.md) * [《6.4_网络流算法》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.4_网络流算法.md) * [《6.5_问题规约》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.5_问题规约.md) * [《6.6_不可解性》](https://github.com/bighuang624/Algorithms-notes/blob/master/docs/Context/6.6_不可解性.md) ## 代码 相关代码详见[代码目录](https://github.com/bighuang624/Algorithms-notes/blob/master/code) ## Cheatsheet [Algorithms and Data Structures Cheatsheet](https://algs4.cs.princeton.edu/cheatsheet/)  ## 参考资料 [算法(第4版)课后练习答案及相关问题解决方案 - 孙强Jimmy的技术博客 - CSDN博客](http://blog.csdn.net/u013541140/article/details/53222770) ================================================ FILE: code/README.md ================================================ # 代码目录 ### algs4 * [Alphabet.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Alphabet.java) * [Bag.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Bag.java) * [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinarySearch.java) * [BinaryStdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdIn.java) * [BinaryStdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/BinaryStdOut.java) * [Counter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Counter.java) * [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DepthFirstOrder.java) * [Draw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Draw.java) * [DrawListener.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/DrawListener.java) * [Heap.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Heap.java) * [HexDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/HexDump.java) * [In.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/In.java) * [IndexMinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/IndexMinPQ.java) * [Interval1D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval1D.java) * [Interval2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Interval2D.java) * [MinPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/MinPQ.java) * [Out.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Out.java) * [Particle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Particle.java) * [Picture.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Picture.java) * [PictureDump.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/PictureDump.java) * [Point2D.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Point2D.java) * [Queue.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Queue.java) * [SET.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/SET.java) * [ST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/ST.java) * [Stack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/Stack.java) * [StdDraw.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdDraw.java) * [StdIn.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdIn.java) * [StdOut.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdOut.java) * [StdRandom.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/algs4/StdRandom.java) ### chapter1_1_Programming_Model * [BinarySearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BinarySearch.java) * [BouncingBall.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/BouncingBall.java) * [Ex1.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex1.java) * [Ex10.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex10.java) * [Ex11.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex11.java) * [Ex13.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex13.java) * [Ex14.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex14.java) * [Ex15.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex15.java) * [Ex19.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex19.java) * [Ex2.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex2.java) * [Ex20.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex20.java) * [Ex3.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex3.java) * [Ex30.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex30.java) * [Ex31.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex31.java) * [Ex32.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex32.java) * [Ex6.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex6.java) * [Ex7a.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7a.java) * [Ex7b.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7b.java) * [Ex7c.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex7c.java) * [Ex8.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex8.java) * [Ex9.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Ex9.java) * [RightTriangle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/RightTriangle.java) * [Sattolo.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/Sattolo.java) * [StdDrawTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_1_Programming_Model/StdDrawTest.java) ### chapter1_2_Data_Abstraction * [Accumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Accumulator.java) * [AccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/AccumulatorTest.java) * [Cat.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Cat.java) * [Date.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Date.java) * [Flips.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Flips.java) * [FlipsMax.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/FlipsMax.java) * [Interval2DTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Interval2DTest.java) * [Rolls.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/Rolls.java) * [StaticSETofInts.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/StaticSETofInts.java) * [VisualAccumulator.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulator.java) * [VisualAccumulatorTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/VisualAccumulatorTest.java) * [WhiteList.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/WhiteList.java) * [in1.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in1.txt) * [in2.txt](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_2_Data_Abstraction/in2.txt) ### chapter1_3_Bags_Queues_Stacks * [ResizingArrayStack.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_3_Bags_Queues_Stacks/ResizingArrayStack.java) ### chapter1_4_Analysis_of_Algorithms * [DoublingRatio.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingRatio.java) * [DoublingTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/DoublingTest.java) * [Stopwatch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/Stopwatch.java) * [StopwatchTest.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/StopwatchTest.java) * [ThreeSum.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_4_Analysis_of_Algorithms/ThreeSum.java) ### chapter1_5_Case_Study_Union_Find * [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/UF.java) * [WeightedQuickUnionUF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter1_5_Case_Study_Union_Find/WeightedQuickUnionUF.java) ### chapter2_1_Elementary_Sorts * [Insertion.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Insertion.java) * [Selection.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Selection.java) * [Shell.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/Shell.java) * [SortCompare.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_1_Elementary_Sorts/SortCompare.java) ### chapter2_2_Mergesort * [Merge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/Merge.java) * [MergeBU.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_2_Mergesort/MergeBU.java) ### chapter2_3_Quicksort * [Ex25.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Ex25.java) * [Quick.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick.java) * [Quick3way.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_3_Quicksort/Quick3way.java) ### chapter2_4_Priority_Queues * [MaxPQ.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/MaxPQ.java) * [TopM.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter2_4_Priority_Queues/TopM.java) ### chapter2_5_Sorting_Applications ### chapter3_1_Symbol_Tables * [BinarySearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/BinarySearchST.java) * [FrequencyCounter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/FrequencyCounter.java) * [SequentialSearchST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_1_Symbol_Tables/SequentialSearchST.java) ### chapter3_2_Binary_Search_Trees * [BST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_2_Binary_Search_Trees/BST.java) ### chapter3_4_Hash_Tables * [LinearProbingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/LinearProbingHashST.java) * [SeparateChainingHashST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_4_Hash_Tables/SeparateChainingHashST.java) ### chapter3_5_Searching_Applications * [SparseVector.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/SparseVector.java) * [WhiteFilter.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter3_5_Searching_Applications/WhiteFilter.java) ### chapter4_1_Undirected_Graphs * [BreadthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/BreadthFirstPaths.java) * [CC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/CC.java) * [Cycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Cycle.java) * [DegreesOfSeparation.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DegreesOfSeparation.java) * [DepthFirstPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstPaths.java) * [DepthFirstSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/DepthFirstSearch.java) * [Graph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/Graph.java) * [SymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/SymbolGraph.java) * [TestCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestCC.java) * [TestPaths.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestPaths.java) * [TestSearch.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSearch.java) * [TestSymbolGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TestSymbolGraph.java) * [TwoColor.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_1_Undirected_Graphs/TwoColor.java) ### chapter4_2_Directed_Graphs * [DepthFirstOrder.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DepthFirstOrder.java) * [Digraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Digraph.java) * [DirectedCycle.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedCycle.java) * [DirectedDFS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/DirectedDFS.java) * [KosarajuSCC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/KosarajuSCC.java) * [SymbolDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/SymbolDigraph.java) * [Topological.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/Topological.java) * [TransitiveClosure.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_2_Directed_Graphs/TransitiveClosure.java) ### chapter4_3_Minimum_Spanning_Tree * [Edge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/Edge.java) * [EdgeWeightedGraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/EdgeWeightedGraph.java) * [KruskalMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/KruskalMST.java) * [LazyPrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/LazyPrimMST.java) * [PrimMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/PrimMST.java) * [TestMST.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/TestMST.java) * [UF.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_3_Minimum_Spanning_Tree/UF.java) ### chapter4_4_Shortest_Paths * [DijkstraSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DijkstraSP.java) * [DirectedEdge.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/DirectedEdge.java) * [EdgeWeightedDigraph.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/EdgeWeightedDigraph.java) * [SP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/SP.java) * [TestSP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter4_4_Shortest_Paths/TestSP.java) ### chapter5_3_Substring_Search * [BoyerMoore.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/BoyerMoore.java) * [KMP.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/KMP.java) * [RabinKarp.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter5_3_Substring_Search/RabinKarp.java) ### chapter6_3_Suffix_Arrays * [KWIC.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/KWIC.java) * [LRS.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/LRS.java) * [SuffixArray.java](https://github.com/bighuang624/Algorithms-notes/blob/master/code/chapter6_3_Suffix_Arrays/SuffixArray.java) ================================================ FILE: code/algs4/Alphabet.java ================================================ /****************************************************************************** * Compilation: javac Alphabet.java * Execution: java Alphabet * Dependencies: StdOut.java * * A data type for alphabets, for use with string-processing code * that must convert between an alphabet of size R and the integers * 0 through R-1. * * Warning: supports only the basic multilingual plane (BMP), i.e, * Unicode characters between U+0000 and U+FFFF. * ******************************************************************************/ package algs4; public class Alphabet { /** * The binary alphabet { 0, 1 }. */ public static final Alphabet BINARY = new Alphabet("01"); /** * The octal alphabet { 0, 1, 2, 3, 4, 5, 6, 7 }. */ public static final Alphabet OCTAL = new Alphabet("01234567"); /** * The decimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }. */ public static final Alphabet DECIMAL = new Alphabet("0123456789"); /** * The hexadecimal alphabet { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F }. */ public static final Alphabet HEXADECIMAL = new Alphabet("0123456789ABCDEF"); /** * The DNA alphabet { A, C, T, G }. */ public static final Alphabet DNA = new Alphabet("ACGT"); /** * The lowercase alphabet { a, b, c, ..., z }. */ public static final Alphabet LOWERCASE = new Alphabet("abcdefghijklmnopqrstuvwxyz"); /** * The uppercase alphabet { A, B, C, ..., Z }. */ public static final Alphabet UPPERCASE = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); /** * The protein alphabet { A, C, D, E, F, G, H, I, K, L, M, N, P, Q, R, S, T, V, W, Y }. */ public static final Alphabet PROTEIN = new Alphabet("ACDEFGHIKLMNPQRSTVWY"); /** * The base-64 alphabet (64 characters). */ public static final Alphabet BASE64 = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); /** * The ASCII alphabet (0-127). */ public static final Alphabet ASCII = new Alphabet(128); /** * The extended ASCII alphabet (0-255). */ public static final Alphabet EXTENDED_ASCII = new Alphabet(256); /** * The Unicode 16 alphabet (0-65,535). */ public static final Alphabet UNICODE16 = new Alphabet(65536); private char[] alphabet; // the characters in the alphabet private int[] inverse; // indices private final int R; // the radix of the alphabet /** * Initializes a new alphabet from the given set of characters. * * @param alpha the set of characters */ public Alphabet(String alpha) { // check that alphabet contains no duplicate chars boolean[] unicode = new boolean[Character.MAX_VALUE]; for (int i = 0; i < alpha.length(); i++) { char c = alpha.charAt(i); if (unicode[c]) throw new IllegalArgumentException("Illegal alphabet: repeated character = '" + c + "'"); unicode[c] = true; } alphabet = alpha.toCharArray(); R = alpha.length(); inverse = new int[Character.MAX_VALUE]; for (int i = 0; i < inverse.length; i++) inverse[i] = -1; // can't use char since R can be as big as 65,536 for (int c = 0; c < R; c++) inverse[alphabet[c]] = c; } /** * Initializes a new alphabet using characters 0 through R-1. * * @param radix the number of characters in the alphabet (the radix R) */ private Alphabet(int radix) { this.R = radix; alphabet = new char[R]; inverse = new int[R]; // can't use char since R can be as big as 65,536 for (int i = 0; i < R; i++) alphabet[i] = (char) i; for (int i = 0; i < R; i++) inverse[i] = i; } /** * Initializes a new alphabet using characters 0 through 255. */ public Alphabet() { this(256); } /** * Returns true if the argument is a character in this alphabet. * * @param c the character * @return {@code true} if {@code c} is a character in this alphabet; * {@code false} otherwise */ public boolean contains(char c) { return inverse[c] != -1; } /** * Returns the number of characters in this alphabet (the radix). * * @return the number of characters in this alphabet * @deprecated Replaced by {@link #radix()}. */ @Deprecated public int R() { return R; } /** * Returns the number of characters in this alphabet (the radix). * * @return the number of characters in this alphabet */ public int radix() { return R; } /** * Returns the binary logarithm of the number of characters in this alphabet. * * @return the binary logarithm (rounded up) of the number of characters in this alphabet */ public int lgR() { int lgR = 0; for (int t = R-1; t >= 1; t /= 2) lgR++; return lgR; } /** * Returns the index corresponding to the argument character. * * @param c the character * @return the index corresponding to the character {@code c} * @throws IllegalArgumentException unless {@code c} is a character in this alphabet */ public int toIndex(char c) { if (c >= inverse.length || inverse[c] == -1) { throw new IllegalArgumentException("Character " + c + " not in alphabet"); } return inverse[c]; } /** * Returns the indices corresponding to the argument characters. * * @param s the characters * @return the indices corresponding to the characters {@code s} * @throws IllegalArgumentException unless every character in {@code s} * is a character in this alphabet */ public int[] toIndices(String s) { char[] source = s.toCharArray(); int[] target = new int[s.length()]; for (int i = 0; i < source.length; i++) target[i] = toIndex(source[i]); return target; } /** * Returns the character corresponding to the argument index. * * @param index the index * @return the character corresponding to the index {@code index} * @throws IllegalArgumentException unless {@code 0 <= index < R} */ public char toChar(int index) { if (index < 0 || index >= R) { throw new IndexOutOfBoundsException("Alphabet index out of bounds"); } return alphabet[index]; } /** * Returns the characters corresponding to the argument indices. * * @param indices the indices * @return the characters corresponding to the indices {@code indices} * @throws IllegalArgumentException unless {@code 0 < indices[i] < R} * for every {@code i} */ public String toChars(int[] indices) { StringBuilder s = new StringBuilder(indices.length); for (int i = 0; i < indices.length; i++) s.append(toChar(indices[i])); return s.toString(); } /** * Unit tests the {@code Alphabet} data type. * * @param args the command-line arguments */ public static void main(String[] args) { int[] encoded1 = Alphabet.BASE64.toIndices("NowIsTheTimeForAllGoodMen"); String decoded1 = Alphabet.BASE64.toChars(encoded1); StdOut.println(decoded1); int[] encoded2 = Alphabet.DNA.toIndices("AACGAACGGTTTACCCCG"); String decoded2 = Alphabet.DNA.toChars(encoded2); StdOut.println(decoded2); int[] encoded3 = Alphabet.DECIMAL.toIndices("01234567890123456789"); String decoded3 = Alphabet.DECIMAL.toChars(encoded3); StdOut.println(decoded3); } } /****************************************************************************** * Copyright 2002-2016, Robert Sedgewick and Kevin Wayne. * * This file is part of algs4.jar, which accompanies the textbook * * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. * http://algs4.cs.princeton.edu * * * algs4.jar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * algs4.jar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with algs4.jar. If not, see http://www.gnu.org/licenses. ******************************************************************************/ ================================================ FILE: code/algs4/Bag.java ================================================ /****************************************************************************** * Compilation: javac Bag.java * Execution: java Bag < input.txt * Dependencies: StdIn.java StdOut.java * * A generic bag or multiset, implemented using a singly-linked list. * * % more tobe.txt * to be or not to - be - - that - - - is * * % java Bag < tobe.txt * size of bag = 14 * is * - * - * - * that * - * - * be * - * to * not * or * be * to * ******************************************************************************/ package algs4; import java.util.Iterator; import java.util.NoSuchElementException; /** * The {@code Bag} class represents a bag (or multiset) of * generic items. It supports insertion and iterating over the * items in arbitrary order. *
* This implementation uses a singly-linked list with a static nested class Node. * See {@link LinkedBag} for the version from the * textbook that uses a non-static nested class. * The add, isEmpty, and size operations * take constant time. Iteration takes time proportional to the number of items. *
* For additional documentation, see Section 1.3 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* The indexOf operations takes logarithmic time in the worst case.
*
* For additional documentation, see Section 1.1 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class BinarySearch {
/**
* This class should not be instantiated.
*/
private BinarySearch() { }
/**
* Returns the index of the specified key in the specified array.
*
* @param a the array of integers, must be sorted in ascending order
* @param key the search key
* @return index of key in array {@code a} if present; {@code -1} otherwise
*/
public static int indexOf(int[] a, int key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
/**
* Returns the index of the specified key in the specified array.
* This function is poorly named because it does not give the rank
* if the array has duplicate keys or if the key is not in the array.
*
* @param key the search key
* @param a the array of integers, must be sorted in ascending order
* @return index of key in array {@code a} if present; {@code -1} otherwise
* @deprecated Replaced by {@link #indexOf(int[], int)}.
*/
@Deprecated
public static int rank(int key, int[] a) {
return indexOf(a, key);
}
/**
* Reads in a sequence of integers from the whitelist file, specified as
* a command-line argument; reads in integers from standard input;
* prints to standard output those integers that do not appear in the file.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (BinarySearch.indexOf(whitelist, key) == -1)
StdOut.println(key);
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/BinaryStdIn.java
================================================
/******************************************************************************
* Compilation: javac BinaryStdIn.java
* Execution: java BinaryStdIn < input > output
* Dependencies: none
*
* Supports reading binary data from standard input.
*
* % java BinaryStdIn < input.jpg > output.jpg
* % diff input.jpg output.jpg
*
******************************************************************************/
package algs4;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.NoSuchElementException;
/**
* Binary standard input. This class provides methods for reading
* in bits from standard input, either one bit at a time (as a {@code boolean}),
* 8 bits at a time (as a {@code byte} or {@code char}),
* 16 bits at a time (as a {@code short}), 32 bits at a time
* (as an {@code int} or {@code float}), or 64 bits at a time (as a
* {@code double} or {@code long}).
*
* All primitive types are assumed to be represented using their
* standard Java representations, in big-endian (most significant
* byte first) order.
*
* The client should not intermix calls to {@code BinaryStdIn} with calls
* to {@code StdIn} or {@code System.in};
* otherwise unexpected behavior will result.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class BinaryStdIn {
private static BufferedInputStream in = new BufferedInputStream(System.in);
private static final int EOF = -1; // end of file
private static int buffer; // one character buffer
private static int n; // number of bits left in buffer
// static initializer
static {
fillBuffer();
}
// don't instantiate
private BinaryStdIn() { }
private static void fillBuffer() {
try {
buffer = in.read();
n = 8;
}
catch (IOException e) {
System.out.println("EOF");
buffer = EOF;
n = -1;
}
}
/**
* Close this input stream and release any associated system resources.
*/
public static void close() {
try {
in.close();
}
catch (IOException ioe) {
throw new IllegalStateException("Could not close BinaryStdIn", ioe);
}
}
/**
* Returns true if standard input is empty.
* @return true if and only if standard input is empty
*/
public static boolean isEmpty() {
return buffer == EOF;
}
/**
* Reads the next bit of data from standard input and return as a boolean.
*
* @return the next bit of data from standard input as a {@code boolean}
* @throws NoSuchElementException if standard input is empty
*/
public static boolean readBoolean() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
n--;
boolean bit = ((buffer >> n) & 1) == 1;
if (n == 0) fillBuffer();
return bit;
}
/**
* Reads the next 8 bits from standard input and return as an 8-bit char.
* Note that {@code char} is a 16-bit type;
* to read the next 16 bits as a char, use {@code readChar(16)}.
*
* @return the next 8 bits of data from standard input as a {@code char}
* @throws NoSuchElementException if there are fewer than 8 bits available on standard input
*/
public static char readChar() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
// special case when aligned byte
if (n == 8) {
int x = buffer;
fillBuffer();
return (char) (x & 0xff);
}
// combine last n bits of current buffer with first 8-n bits of new buffer
int x = buffer;
x <<= (8 - n);
int oldN = n;
fillBuffer();
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
n = oldN;
x |= (buffer >>> n);
return (char) (x & 0xff);
// the above code doesn't quite work for the last character if n = 8
// because buffer will be -1, so there is a special case for aligned byte
}
/**
* Reads the next r bits from standard input and return as an r-bit character.
*
* @param r number of bits to read.
* @return the next r bits of data from standard input as a {@code char}
* @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input
* @throws IllegalArgumentException unless {@code 1 <= r <= 16}
*/
public static char readChar(int r) {
if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value of r = " + r);
// optimize r = 8 case
if (r == 8) return readChar();
char x = 0;
for (int i = 0; i < r; i++) {
x <<= 1;
boolean bit = readBoolean();
if (bit) x |= 1;
}
return x;
}
/**
* Reads the remaining bytes of data from standard input and return as a string.
*
* @return the remaining bytes of data from standard input as a {@code String}
* @throws NoSuchElementException if standard input is empty or if the number of bits
* available on standard input is not a multiple of 8 (byte-aligned)
*/
public static String readString() {
if (isEmpty()) throw new NoSuchElementException("Reading from empty input stream");
StringBuilder sb = new StringBuilder();
while (!isEmpty()) {
char c = readChar();
sb.append(c);
}
return sb.toString();
}
/**
* Reads the next 16 bits from standard input and return as a 16-bit short.
*
* @return the next 16 bits of data from standard input as a {@code short}
* @throws NoSuchElementException if there are fewer than 16 bits available on standard input
*/
public static short readShort() {
short x = 0;
for (int i = 0; i < 2; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next 32 bits from standard input and return as a 32-bit int.
*
* @return the next 32 bits of data from standard input as a {@code int}
* @throws NoSuchElementException if there are fewer than 32 bits available on standard input
*/
public static int readInt() {
int x = 0;
for (int i = 0; i < 4; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next r bits from standard input and return as an r-bit int.
*
* @param r number of bits to read.
* @return the next r bits of data from standard input as a {@code int}
* @throws NoSuchElementException if there are fewer than {@code r} bits available on standard input
* @throws IllegalArgumentException unless {@code 1 <= r <= 32}
*/
public static int readInt(int r) {
if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value of r = " + r);
// optimize r = 32 case
if (r == 32) return readInt();
int x = 0;
for (int i = 0; i < r; i++) {
x <<= 1;
boolean bit = readBoolean();
if (bit) x |= 1;
}
return x;
}
/**
* Reads the next 64 bits from standard input and return as a 64-bit long.
*
* @return the next 64 bits of data from standard input as a {@code long}
* @throws NoSuchElementException if there are fewer than 64 bits available on standard input
*/
public static long readLong() {
long x = 0;
for (int i = 0; i < 8; i++) {
char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
/**
* Reads the next 64 bits from standard input and return as a 64-bit double.
*
* @return the next 64 bits of data from standard input as a {@code double}
* @throws NoSuchElementException if there are fewer than 64 bits available on standard input
*/
public static double readDouble() {
return Double.longBitsToDouble(readLong());
}
/**
* Reads the next 32 bits from standard input and return as a 32-bit float.
*
* @return the next 32 bits of data from standard input as a {@code float}
* @throws NoSuchElementException if there are fewer than 32 bits available on standard input
*/
public static float readFloat() {
return Float.intBitsToFloat(readInt());
}
/**
* Reads the next 8 bits from standard input and return as an 8-bit byte.
*
* @return the next 8 bits of data from standard input as a {@code byte}
* @throws NoSuchElementException if there are fewer than 8 bits available on standard input
*/
public static byte readByte() {
char c = readChar();
return (byte) (c & 0xff);
}
/**
* Test client. Reads in a binary input file from standard input and writes
* it to standard output.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// read one 8-bit char at a time
while (!BinaryStdIn.isEmpty()) {
char c = BinaryStdIn.readChar();
BinaryStdOut.write(c);
}
BinaryStdOut.flush();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/BinaryStdOut.java
================================================
/******************************************************************************
* Compilation: javac BinaryStdOut.java
* Execution: java BinaryStdOut
* Dependencies: none
*
* Write binary data to standard output, either one 1-bit boolean,
* one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float,
* or one 64-bit long at a time.
*
* The bytes written are not aligned.
*
******************************************************************************/
package algs4;
import java.io.BufferedOutputStream;
import java.io.IOException;
/**
* Binary standard output. This class provides methods for converting
* primtive type variables ({@code boolean}, {@code byte}, {@code char},
* {@code int}, {@code long}, {@code float}, and {@code double})
* to sequences of bits and writing them to standard output.
* Uses big-endian (most-significant byte first).
*
* The client must {@code flush()} the output stream when finished writing bits.
*
* The client should not intermixing calls to {@code BinaryStdOut} with calls
* to {@code StdOut} or {@code System.out}; otherwise unexpected behavior
* will result.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class BinaryStdOut {
private static BufferedOutputStream out = new BufferedOutputStream(System.out);
private static int buffer; // 8-bit buffer of bits to write out
private static int n; // number of bits remaining in buffer
// don't instantiate
private BinaryStdOut() { }
/**
* Write the specified bit to standard output.
*/
private static void writeBit(boolean bit) {
// add bit to buffer
buffer <<= 1;
if (bit) buffer |= 1;
// if buffer is full (8 bits), write out as a single byte
n++;
if (n == 8) clearBuffer();
}
/**
* Write the 8-bit byte to standard output.
*/
private static void writeByte(int x) {
assert x >= 0 && x < 256;
// optimized if byte-aligned
if (n == 0) {
try {
out.write(x);
}
catch (IOException e) {
e.printStackTrace();
}
return;
}
// otherwise write one bit at a time
for (int i = 0; i < 8; i++) {
boolean bit = ((x >>> (8 - i - 1)) & 1) == 1;
writeBit(bit);
}
}
// write out any remaining bits in buffer to standard output, padding with 0s
private static void clearBuffer() {
if (n == 0) return;
if (n > 0) buffer <<= (8 - n);
try {
out.write(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
n = 0;
buffer = 0;
}
/**
* Flush standard output, padding 0s if number of bits written so far
* is not a multiple of 8.
*/
public static void flush() {
clearBuffer();
try {
out.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Flush and close standard output. Once standard output is closed, you can no
* longer write bits to it.
*/
public static void close() {
flush();
try {
out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Write the specified bit to standard output.
* @param x the {@code boolean} to write.
*/
public static void write(boolean x) {
writeBit(x);
}
/**
* Write the 8-bit byte to standard output.
* @param x the {@code byte} to write.
*/
public static void write(byte x) {
writeByte(x & 0xff);
}
/**
* Write the 32-bit int to standard output.
* @param x the {@code int} to write.
*/
public static void write(int x) {
writeByte((x >>> 24) & 0xff);
writeByte((x >>> 16) & 0xff);
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Write the r-bit int to standard output.
* @param x the {@code int} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 32.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2r - 1.
*/
public static void write(int x, int r) {
if (r == 32) {
write(x);
return;
}
if (r < 1 || r > 32) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x < 0 || x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Write the 64-bit double to standard output.
* @param x the {@code double} to write.
*/
public static void write(double x) {
write(Double.doubleToRawLongBits(x));
}
/**
* Write the 64-bit long to standard output.
* @param x the {@code long} to write.
*/
public static void write(long x) {
writeByte((int) ((x >>> 56) & 0xff));
writeByte((int) ((x >>> 48) & 0xff));
writeByte((int) ((x >>> 40) & 0xff));
writeByte((int) ((x >>> 32) & 0xff));
writeByte((int) ((x >>> 24) & 0xff));
writeByte((int) ((x >>> 16) & 0xff));
writeByte((int) ((x >>> 8) & 0xff));
writeByte((int) ((x >>> 0) & 0xff));
}
/**
* Write the 32-bit float to standard output.
* @param x the {@code float} to write.
*/
public static void write(float x) {
write(Float.floatToRawIntBits(x));
}
/**
* Write the 16-bit int to standard output.
* @param x the {@code short} to write.
*/
public static void write(short x) {
writeByte((x >>> 8) & 0xff);
writeByte((x >>> 0) & 0xff);
}
/**
* Write the 8-bit char to standard output.
* @param x the {@code char} to write.
* @throws IllegalArgumentException if {@code x} is not betwen 0 and 255.
*/
public static void write(char x) {
if (x < 0 || x >= 256) throw new IllegalArgumentException("Illegal 8-bit char = " + x);
writeByte(x);
}
/**
* Write the r-bit char to standard output.
* @param x the {@code char} to write.
* @param r the number of relevant bits in the char.
* @throws IllegalArgumentException if {@code r} is not between 1 and 16.
* @throws IllegalArgumentException if {@code x} is not between 0 and 2r - 1.
*/
public static void write(char x, int r) {
if (r == 8) {
write(x);
return;
}
if (r < 1 || r > 16) throw new IllegalArgumentException("Illegal value for r = " + r);
if (x >= (1 << r)) throw new IllegalArgumentException("Illegal " + r + "-bit char = " + x);
for (int i = 0; i < r; i++) {
boolean bit = ((x >>> (r - i - 1)) & 1) == 1;
writeBit(bit);
}
}
/**
* Write the string of 8-bit characters to standard output.
* @param s the {@code String} to write.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 255.
*/
public static void write(String s) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i));
}
/**
* Write the String of r-bit characters to standard output.
* @param s the {@code String} to write.
* @param r the number of relevants bits in each character.
* @throws IllegalArgumentException if r is not between 1 and 16.
* @throws IllegalArgumentException if any character in the string is not
* between 0 and 2r - 1.
*/
public static void write(String s, int r) {
for (int i = 0; i < s.length(); i++)
write(s.charAt(i), r);
}
/**
* Test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
// write n integers to binary standard output
for (int i = 0; i < m; i++) {
BinaryStdOut.write(i);
}
BinaryStdOut.flush();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Counter.java
================================================
/******************************************************************************
* Compilation: javac Counter.java
* Execution: java Counter n trials
* Dependencies: StdRandom.java StdOut.java
*
* A mutable data type for an integer counter.
*
* The test clients create n counters and performs trials increment
* operations on random counters.
*
* java Counter 6 600000
* 100140 counter0
* 100273 counter1
* 99848 counter2
* 100129 counter3
* 99973 counter4
* 99637 counter5
*
******************************************************************************/
package algs4;
/**
* The {@code Counter} class is a mutable data type to encapsulate a counter.
*
* For additional documentation,
* see Section 1.2 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Counter implements Comparable
// * This implementation uses depth-first search.
// * The constructor takes time proportional to V + E
// * (in the worst case),
// * where V is the number of vertices and E is the number of edges.
// * Afterwards, the preorder, postorder, and reverse postorder
// * operation takes take time proportional to V.
// *
// * For additional documentation,
// * see Section 4.2 of
// * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
// *
// * @author Robert Sedgewick
// * @author Kevin Wayne
// */
//public class DepthFirstOrder {
// private boolean[] marked; // marked[v] = has v been marked in dfs?
// private int[] pre; // pre[v] = preorder number of v
// private int[] post; // post[v] = postorder number of v
// private Queue
* For additional documentation, see Section 3.1 of
* Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class Draw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
/**
* The color black.
*/
public static final Color BLACK = Color.BLACK;
/**
* The color blue.
*/
public static final Color BLUE = Color.BLUE;
/**
* The color cyan.
*/
public static final Color CYAN = Color.CYAN;
/**
* The color dark gray.
*/
public static final Color DARK_GRAY = Color.DARK_GRAY;
/**
* The color gray.
*/
public static final Color GRAY = Color.GRAY;
/**
* The color green.
*/
public static final Color GREEN = Color.GREEN;
/**
* The color light gray.
*/
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
/**
* The color magenta.
*/
public static final Color MAGENTA = Color.MAGENTA;
/**
* The color orange.
*/
public static final Color ORANGE = Color.ORANGE;
/**
* The color pink.
*/
public static final Color PINK = Color.PINK;
/**
* The color red.
*/
public static final Color RED = Color.RED;
/**
* The color white.
*/
public static final Color WHITE = Color.WHITE;
/**
* The color yellow.
*/
public static final Color YELLOW = Color.YELLOW;
/**
* Shade of blue used in Introduction to Programming in Java.
* It is Pantone 300U. The RGB values are approximately (9, 90, 166).
*/
public static final Color BOOK_BLUE = new Color(9, 90, 166);
/**
* Shade of light blue used in Introduction to Programming in Java.
* The RGB values are approximately (103, 198, 243).
*/
public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);
/**
* Shade of red used in Algorithms, 4th edition.
* It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
*/
public static final Color BOOK_RED = new Color(150, 35, 31);
// default colors
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// boundary of drawing canvas, 0% border
private static final double BORDER = 0.0;
private static final double DEFAULT_XMIN = 0.0;
private static final double DEFAULT_XMAX = 1.0;
private static final double DEFAULT_YMIN = 0.0;
private static final double DEFAULT_YMAX = 1.0;
// default canvas size is SIZE-by-SIZE
private static final int DEFAULT_SIZE = 512;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16);
// current pen color
private Color penColor;
// canvas size
private int width = DEFAULT_SIZE;
private int height = DEFAULT_SIZE;
// current pen radius
private double penRadius;
// show we draw immediately or wait until next show?
private boolean defer = false;
private double xmin, ymin, xmax, ymax;
// name of window
private String name = "Draw";
// for synchronization
private final Object mouseLock = new Object();
private final Object keyLock = new Object();
// current font
private Font font;
// the JLabel for drawing
private JLabel draw;
// double buffered graphics
private BufferedImage offscreenImage, onscreenImage;
private Graphics2D offscreen, onscreen;
// the frame for drawing to the screen
private JFrame frame = new JFrame();
// mouse state
private boolean mousePressed = false;
private double mouseX = 0;
private double mouseY = 0;
// keyboard state
private final LinkedList
* This method takes as an argument the keycode (corresponding to a physical key).
* It can handle action keys (such as F1 and arrow keys) and modifier keys
* (such as shift and control).
* See {@link KeyEvent} for a description of key codes.
*
* @param keycode the keycode to check
* @return {@code true} if {@code keycode} is currently being pressed;
* {@code false} otherwise
*/
public boolean isKeyPressed(int keycode) {
synchronized (keyLock) {
return keysDown.contains(keycode);
}
}
/**
* This method cannot be called directly.
*/
@Override
public void keyTyped(KeyEvent e) {
synchronized (keyLock) {
keysTyped.addFirst(e.getKeyChar());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyTyped(e.getKeyChar());
}
/**
* This method cannot be called directly.
*/
@Override
public void keyPressed(KeyEvent e) {
synchronized (keyLock) {
keysDown.add(e.getKeyCode());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyPressed(e.getKeyCode());
}
/**
* This method cannot be called directly.
*/
@Override
public void keyReleased(KeyEvent e) {
synchronized (keyLock) {
keysDown.remove(e.getKeyCode());
}
// notify all listeners
for (DrawListener listener : listeners)
listener.keyPressed(e.getKeyCode());
}
/**
* Test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// create one drawing window
Draw draw1 = new Draw("Test client 1");
draw1.square(.2, .8, .1);
draw1.filledSquare(.8, .8, .2);
draw1.circle(.8, .2, .2);
draw1.setPenColor(Draw.MAGENTA);
draw1.setPenRadius(.02);
draw1.arc(.8, .2, .1, 200, 45);
// create another one
Draw draw2 = new Draw("Test client 2");
draw2.setCanvasSize(900, 200);
// draw a blue diamond
draw2.setPenRadius();
draw2.setPenColor(Draw.BLUE);
double[] x = { .1, .2, .3, .2 };
double[] y = { .2, .3, .2, .1 };
draw2.filledPolygon(x, y);
// text
draw2.setPenColor(Draw.BLACK);
draw2.text(0.2, 0.5, "bdfdfdfdlack text");
draw2.setPenColor(Draw.WHITE);
draw2.text(0.8, 0.8, "white text");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/DrawListener.java
================================================
/******************************************************************************
* Compilation: javac DrawListener.java
* Execution: none
* Dependencies: none
*
* Interface that accompanies Draw.java.
******************************************************************************/
package algs4;
public interface DrawListener {
/**
* Invoked when the mouse has been pressed.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mousePressed(double x, double y);
/**
* Invoked when the mouse has been dragged.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mouseDragged(double x, double y);
/**
* Invoked when the mouse has been released.
*
* @param x the x-coordinate of the mouse
* @param y the y-coordinate of the mouse
*/
void mouseReleased(double x, double y);
/**
* Invoked when a key has been typed.
*
* @param c the character typed
*/
void keyTyped(char c);
/**
* Invoked when a key has been pressed.
*
* @param keycode the key combination pressed
*/
void keyPressed(int keycode);
/**
* Invoked when a key has been released.
*
* @param keycode the key combination released
*/
void keyReleased(int keycode);
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Heap.java
================================================
/******************************************************************************
* Compilation: javac Heap.java
* Execution: java Heap < input.txt
* Dependencies: StdOut.java StdIn.java
* Data files: http://algs4.cs.princeton.edu/24pq/tiny.txt
* http://algs4.cs.princeton.edu/24pq/words3.txt
*
* Sorts a sequence of strings from standard input using heapsort.
*
* % more tiny.txt
* S O R T E X A M P L E
*
* % java Heap < tiny.txt
* A E E L M O P R S T X [ one string per line ]
*
* % more words3.txt
* bed bug dad yes zoo ... all bad yet
*
* % java Heap < words3.txt
* all bad bed bug dad ... yes yet zoo [ one string per line ]
*
******************************************************************************/
package algs4;
/**
* The {@code Heap} class provides a static methods for heapsorting
* an array.
*
* For additional documentation, see Section 2.4 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Heap {
// This class should not be instantiated.
private Heap() { }
/**
* Rearranges the array in ascending order, using the natural order.
* @param pq the array to be sorted
*/
public static void sort(Comparable[] pq) {
int n = pq.length;
for (int k = n/2; k >= 1; k--)
sink(pq, k, n);
while (n > 1) {
exch(pq, 1, n--);
sink(pq, 1, n);
}
}
/***************************************************************************
* Helper functions to restore the heap invariant.
***************************************************************************/
private static void sink(Comparable[] pq, int k, int n) {
while (2*k <= n) {
int j = 2*k;
if (j < n && less(pq, j, j+1)) j++;
if (!less(pq, k, j)) break;
exch(pq, k, j);
k = j;
}
}
/***************************************************************************
* Helper functions for comparisons and swaps.
* Indices are "off-by-one" to support 1-based indexing.
***************************************************************************/
private static boolean less(Comparable[] pq, int i, int j) {
return pq[i-1].compareTo(pq[j-1]) < 0;
}
private static void exch(Object[] pq, int i, int j) {
Object swap = pq[i-1];
pq[i-1] = pq[j-1];
pq[j-1] = swap;
}
// is v < w ?
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
/***************************************************************************
* Check if array is sorted - useful for debugging.
***************************************************************************/
private static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i-1])) return false;
return true;
}
// print array to standard output
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
StdOut.println(a[i]);
}
}
/**
* Reads in a sequence of strings from standard input; heapsorts them;
* and prints them to standard output in ascending order.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
String[] a = StdIn.readAllStrings();
Heap.sort(a);
show(a);
assert isSorted(a);
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/HexDump.java
================================================
/******************************************************************************
* Compilation: javac HexDump.java
* Execution: java HexDump < file
* Dependencies: BinaryStdIn.java StdOut.java
* Data file: http://algs4.cs.princeton.edu/55compression/abra.txt
*
* Reads in a binary file and writes out the bytes in hex, 16 per line.
*
* % more abra.txt
* ABRACADABRA!
*
* % java HexDump 16 < abra.txt
* 41 42 52 41 43 41 44 41 42 52 41 21
* 96 bits
*
*
* Remark
* --------------------------
* - Similar to the Unix utilities od (octal dump) or hexdump (hexadecimal dump).
*
* % od -t x1 < abra.txt
* 0000000 41 42 52 41 43 41 44 41 42 52 41 21
* 0000014
*
******************************************************************************/
package algs4;
/**
* The {@code HexDump} class provides a client for displaying the contents
* of a binary file in hexadecimal.
*
* For additional documentation,
* see Section 5.5 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* See also {@link BinaryDump} and {@link PictureDump}.
* For more full-featured versions, see the Unix utilities
* {@code od} (octal dump) and {@code hexdump} (hexadecimal dump).
*
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class HexDump {
// Do not instantiate.
private HexDump() { }
/**
* Reads in a sequence of bytes from standard input and writes
* them to standard output using hexademical notation, k hex digits
* per line, where k is given as a command-line integer (defaults
* to 16 if no integer is specified); also writes the number
* of bits.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int bytesPerLine = 16;
if (args.length == 1) {
bytesPerLine = Integer.parseInt(args[0]);
}
int i;
for (i = 0; !BinaryStdIn.isEmpty(); i++) {
if (bytesPerLine == 0) {
BinaryStdIn.readChar();
continue;
}
if (i == 0) StdOut.printf("");
else if (i % bytesPerLine == 0) StdOut.printf("\n", i);
else StdOut.print(" ");
char c = BinaryStdIn.readChar();
StdOut.printf("%02x", c & 0xff);
}
if (bytesPerLine != 0) StdOut.println();
StdOut.println((i*8) + " bits");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/In.java
================================================
/******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/
package algs4;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.Socket;
// import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* Input. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
*
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
*
* For additional documentation, see
* Section 3.1 of
* Computer Science: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
*
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see
* Scanner.java (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In {
///// begin: section (1 of 2) of code duplicated from In to StdIn.
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile("");
// used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A");
//// end: section (1 of 2) of code duplicated from In to StdIn.
private Scanner scanner;
/**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
/**
* Initializes an input stream from a socket.
*
* @param socket the socket
* @throws IllegalArgumentException if cannot open {@code socket}
* @throws IllegalArgumentException if {@code socket} is {@code null}
*/
public In(Socket socket) {
if (socket == null) throw new IllegalArgumentException("socket argument is null");
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + socket, ioe);
}
}
/**
* Initializes an input stream from a URL.
*
* @param url the URL
* @throws IllegalArgumentException if cannot open {@code url}
* @throws IllegalArgumentException if {@code url} is {@code null}
*/
public In(URL url) {
if (url == null) throw new IllegalArgumentException("url argument is null");
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + url, ioe);
}
}
/**
* Initializes an input stream from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot open {@code file}
* @throws IllegalArgumentException if {@code file} is {@code null}
*/
public In(File file) {
if (file == null) throw new IllegalArgumentException("file argument is null");
try {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + file, ioe);
}
}
/**
* Initializes an input stream from a filename or web page name.
*
* @param name the filename or web page name
* @throws IllegalArgumentException if cannot open {@code name} as
* a file or URL
* @throws IllegalArgumentException if {@code name} is {@code null}
*/
public In(String name) {
if (name == null) throw new IllegalArgumentException("argument is null");
try {
// first try to read file from local file system
File file = new File(name);
if (file.exists()) {
// for consistency with StdIn, wrap with BufferedInputStream instead of use
// file as argument to Scanner
FileInputStream fis = new FileInputStream(file);
scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
}
// next try for files included in jar
URL url = getClass().getResource(name);
// or URL from web
if (url == null) {
url = new URL(name);
}
URLConnection site = url.openConnection();
// in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76");
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + name, ioe);
}
}
/**
* Initializes an input stream from a given {@link Scanner} source; use with
* {@code new Scanner(String)} to read from a string.
*
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
* @throws IllegalArgumentException if {@code scanner} is {@code null}
*/
public In(Scanner scanner) {
if (scanner == null) throw new IllegalArgumentException("scanner argument is null");
this.scanner = scanner;
}
/**
* Returns true if this input stream exists.
*
* @return {@code true} if this input stream exists; {@code false} otherwise
*/
public boolean exists() {
return scanner != null;
}
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static".
/**
* Returns true if input stream is empty (except possibly whitespace).
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if this input stream is empty (except possibly whitespace);
* {@code false} otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if this input stream has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if this input stream has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if this input stream has more input (including whitespace);
* {@code false} otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; {@code null} if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character in this input stream.
*
* @return the next character in this input stream
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of this input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token from this input stream and returns it as a {@code String}.
*
* @return the next {@code String} in this input stream
*/
public String readString() {
return scanner.next();
}
/**
* Reads the next token from this input stream, parses it as a {@code int},
* and returns the {@code int}.
*
* @return the next {@code int} in this input stream
*/
public int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from this input stream, parses it as a {@code double},
* and returns the {@code double}.
*
* @return the next {@code double} in this input stream
*/
public double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from this input stream, parses it as a {@code float},
* and returns the {@code float}.
*
* @return the next {@code float} in this input stream
*/
public float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from this input stream, parses it as a {@code long},
* and returns the {@code long}.
*
* @return the next {@code long} in this input stream
*/
public long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from this input stream, parses it as a {@code short},
* and returns the {@code short}.
*
* @return the next {@code short} in this input stream
*/
public short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from this input stream, parses it as a {@code byte},
* and returns the {@code byte}.
*
* To read binary data, use {@link BinaryIn}.
*
* @return the next {@code byte} in this input stream
*/
public byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from this input stream, parses it as a {@code boolean}
* (interpreting either {@code "true"} or {@code "1"} as {@code true},
* and either {@code "false"} or {@code "0"} as {@code false}).
*
* @return the next {@code boolean} in this input stream
*/
public boolean readBoolean() {
String s = readString();
if ("true".equalsIgnoreCase(s)) return true;
if ("false".equalsIgnoreCase(s)) return false;
if ("1".equals(s)) return true;
if ("0".equals(s)) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList
* This implementation uses a binary heap along with an array to associate
* keys with integers in the given range.
* The insert, delete-the-minimum, delete,
* change-key, decrease-key, and increase-key
* operations take logarithmic time.
* The is-empty, size, min-index, min-key,
* and key-of operations take constant time.
* Construction takes time proportional to the specified capacity.
*
* For additional documentation, see Section 2.4 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* For additional documentation,
* see Section 1.2 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Interval1D {
/**
* Compares two intervals by min endpoint.
*/
public static final Comparator
* For additional documentation,
* see Section 1.2 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Interval2D {
private final Interval1D x;
private final Interval1D y;
/**
* Initializes a two-dimensional interval.
* @param x the one-dimensional interval of x-coordinates
* @param y the one-dimensional interval of y-coordinates
*/
public Interval2D(Interval1D x, Interval1D y) {
this.x = x;
this.y = y;
}
/**
* Does this two-dimensional interval intersect that two-dimensional interval?
* @param that the other two-dimensional interval
* @return true if this two-dimensional interval intersects
* that two-dimensional interval; false otherwise
*/
public boolean intersects(Interval2D that) {
if (!this.x.intersects(that.x)) return false;
if (!this.y.intersects(that.y)) return false;
return true;
}
/**
* Does this two-dimensional interval contain the point p?
* @param p the two-dimensional point
* @return true if this two-dimensional interval contains the point p; false otherwise
*/
public boolean contains(Point2D p) {
return x.contains(p.x()) && y.contains(p.y());
}
/**
* Returns the area of this two-dimensional interval.
* @return the area of this two-dimensional interval
*/
public double area() {
return x.length() * y.length();
}
/**
* Returns a string representation of this two-dimensional interval.
* @return a string representation of this two-dimensional interval
* in the form [xmin, xmax] x [ymin, ymax]
*/
public String toString() {
return x + " x " + y;
}
/**
* Does this interval equal the other interval?
* @param other the other interval
* @return true if this interval equals the other interval; false otherwise
*/
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Interval2D that = (Interval2D) other;
return this.x.equals(that.x) && this.y.equals(that.y);
}
/**
* Returns an integer hash code for this interval.
* @return an integer hash code for this interval
*/
public int hashCode() {
int hash1 = x.hashCode();
int hash2 = y.hashCode();
return 31*hash1 + hash2;
}
/**
* Draws this two-dimensional interval to standard draw.
*/
public void draw() {
double xc = (x.min() + x.max()) / 2.0;
double yc = (y.min() + y.max()) / 2.0;
StdDraw.rectangle(xc, yc, x.length() / 2.0, y.length() / 2.0);
}
/**
* Unit tests the {@code Interval2D} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
double xmin = Double.parseDouble(args[0]);
double xmax = Double.parseDouble(args[1]);
double ymin = Double.parseDouble(args[2]);
double ymax = Double.parseDouble(args[3]);
int trials = Integer.parseInt(args[4]);
Interval1D xInterval = new Interval1D(xmin, xmax);
Interval1D yInterval = new Interval1D(ymin, ymax);
Interval2D box = new Interval2D(xInterval, yInterval);
box.draw();
Counter counter = new Counter("hits");
for (int t = 0; t < trials; t++) {
double x = StdRandom.uniform(0.0, 1.0);
double y = StdRandom.uniform(0.0, 1.0);
Point2D point = new Point2D(x, y);
if (box.contains(point)) counter.increment();
else point.draw();
}
StdOut.println(counter);
StdOut.printf("box area = %.2f\n", box.area());
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/MinPQ.java
================================================
/******************************************************************************
* Compilation: javac MinPQ.java
* Execution: java MinPQ < input.txt
* Dependencies: StdIn.java StdOut.java
* Data files: http://algs4.cs.princeton.edu/24pq/tinyPQ.txt
*
* Generic min priority queue implementation with a binary heap.
* Can be used with a comparator instead of the natural order.
*
* % java MinPQ < tinyPQ.txt
* E A E (6 left on pq)
*
* We use a one-based array to simplify parent and child calculations.
*
* Can be optimized by replacing full exchanges with half exchanges
* (ala insertion sort).
*
******************************************************************************/
package algs4;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* The {@code MinPQ} class represents a priority queue of generic keys.
* It supports the usual insert and delete-the-minimum
* operations, along with methods for peeking at the minimum key,
* testing if the priority queue is empty, and iterating through
* the keys.
*
* This implementation uses a binary heap.
* The insert and delete-the-minimum operations take
* logarithmic amortized time.
* The min, size, and is-empty operations take constant time.
* Construction takes time proportional to the specified capacity or the number of
* items used to initialize the data structure.
*
* For additional documentation, see Section 2.4 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* Takes time proportional to the number of keys, using sink-based heap construction.
*
* @param keys the array of keys
*/
public MinPQ(Key[] keys) {
n = keys.length;
pq = (Key[]) new Object[keys.length + 1];
for (int i = 0; i < n; i++)
pq[i+1] = keys[i];
for (int k = n/2; k >= 1; k--)
sink(k);
assert isMinHeap();
}
/**
* Returns true if this priority queue is empty.
*
* @return {@code true} if this priority queue is empty;
* {@code false} otherwise
*/
public boolean isEmpty() {
return n == 0;
}
/**
* Returns the number of keys on this priority queue.
*
* @return the number of keys on this priority queue
*/
public int size() {
return n;
}
/**
* Returns a smallest key on this priority queue.
*
* @return a smallest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key min() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
return pq[1];
}
// helper function to double the size of the heap array
private void resize(int capacity) {
assert capacity > n;
Key[] temp = (Key[]) new Object[capacity];
for (int i = 1; i <= n; i++) {
temp[i] = pq[i];
}
pq = temp;
}
/**
* Adds a new key to this priority queue.
*
* @param x the key to add to this priority queue
*/
public void insert(Key x) {
// double size of array if necessary
if (n == pq.length - 1) resize(2 * pq.length);
// add x, and percolate it up to maintain heap invariant
pq[++n] = x;
swim(n);
assert isMinHeap();
}
/**
* Removes and returns a smallest key on this priority queue.
*
* @return a smallest key on this priority queue
* @throws NoSuchElementException if this priority queue is empty
*/
public Key delMin() {
if (isEmpty()) throw new NoSuchElementException("Priority queue underflow");
exch(1, n);
Key min = pq[n--];
sink(1);
pq[n+1] = null; // avoid loitering and help with garbage collection
if ((n > 0) && (n == (pq.length - 1) / 4)) resize(pq.length / 2);
assert isMinHeap();
return min;
}
/***************************************************************************
* Helper functions to restore the heap invariant.
***************************************************************************/
private void swim(int k) {
while (k > 1 && greater(k/2, k)) {
exch(k, k/2);
k = k/2;
}
}
private void sink(int k) {
while (2*k <= n) {
int j = 2*k;
if (j < n && greater(j, j+1)) j++;
if (!greater(k, j)) break;
exch(k, j);
k = j;
}
}
/***************************************************************************
* Helper functions for compares and swaps.
***************************************************************************/
private boolean greater(int i, int j) {
if (comparator == null) {
return ((Comparable
* The iterator doesn't implement {@code remove()} since it's optional.
*
* @return an iterator that iterates over the keys in ascending order
*/
public Iterator
* For additional documentation, see
* Section 3.1 of
* Computer Science: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Out {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with In
private static final Locale LOCALE = Locale.US;
private PrintWriter out;
/**
* Initializes an output stream from a {@link OutputStream}.
*
* @param os the {@code OutputStream}
*/
public Out(OutputStream os) {
try {
OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);
out = new PrintWriter(osw, true);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initializes an output stream from standard output.
*/
public Out() {
this(System.out);
}
/**
* Initializes an output stream from a socket.
*
* @param socket the socket
*/
public Out(Socket socket) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);
out = new PrintWriter(osw, true);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initializes an output stream from a file.
*
* @param filename the name of the file
*/
public Out(String filename) {
try {
OutputStream os = new FileOutputStream(filename);
OutputStreamWriter osw = new OutputStreamWriter(os, CHARSET_NAME);
out = new PrintWriter(osw, true);
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* Closes the output stream.
*/
public void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to this output stream and then terminates the line.
*
* @param x the boolean to print
*/
public void println(boolean x) {
out.println(x);
}
/**
* Prints a character to this output stream and then terminates the line.
*
* @param x the character to print
*/
public void println(char x) {
out.println(x);
}
/**
* Prints a double to this output stream and then terminates the line.
*
* @param x the double to print
*/
public void println(double x) {
out.println(x);
}
/**
* Prints a float to this output stream and then terminates the line.
*
* @param x the float to print
*/
public void println(float x) {
out.println(x);
}
/**
* Prints an integer to this output stream and then terminates the line.
*
* @param x the integer to print
*/
public void println(int x) {
out.println(x);
}
/**
* Prints a long to this output stream and then terminates the line.
*
* @param x the long to print
*/
public void println(long x) {
out.println(x);
}
/**
* Prints a byte to this output stream and then terminates the line.
*
* To write binary data, see {@link BinaryOut}.
*
* @param x the byte to print
*/
public void println(byte x) {
out.println(x);
}
/**
* Flushes this output stream.
*/
public void print() {
out.flush();
}
/**
* Prints an object to this output stream and flushes this output stream.
*
* @param x the object to print
*/
public void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to this output stream and flushes this output stream.
*
* @param x the boolean to print
*/
public void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to this output stream and flushes this output stream.
*
* @param x the character to print
*/
public void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to this output stream and flushes this output stream.
*
* @param x the double to print
*/
public void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to this output stream and flushes this output stream.
*
* @param x the float to print
*/
public void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to this output stream and flushes this output stream.
*
* @param x the integer to print
*/
public void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to this output stream and flushes this output stream.
*
* @param x the long integer to print
*/
public void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to this output stream and flushes this output stream.
*
* @param x the byte to print
*/
public void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to this output stream, using the specified format
* string and arguments, and then flushes this output stream.
*
* @param format the format string
* @param args the arguments accompanying the format string
*/
public void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to this output stream, using the specified
* locale, format string, and arguments, and then flushes this output stream.
*
* @param locale the locale
* @param format the format string
* @param args the arguments accompanying the format string
*/
public void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* A test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Out out;
// write to stdout
out = new Out();
out.println("Test 1");
out.close();
// write to a file
out = new Out("test.txt");
out.println("Test 2");
out.close();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Particle.java
================================================
/******************************************************************************
* Compilation: javac Particle.java
* Execution: none
* Dependencies: StdDraw.java
*
* A particle moving in the unit box with a given position, velocity,
* radius, and mass.
*
******************************************************************************/
package algs4;
import java.awt.Color;
/**
* The {@code Particle} class represents a particle moving in the unit box,
* with a given position, velocity, radius, and mass. Methods are provided
* for moving the particle and for predicting and resolvling elastic
* collisions with vertical walls, horizontal walls, and other particles.
* This data type is mutable because the position and velocity change.
*
* For additional documentation,
* see Section 6.1 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class Particle {
private static final double INFINITY = Double.POSITIVE_INFINITY;
private double rx, ry; // position
private double vx, vy; // velocity
private int count; // number of collisions so far
private final double radius; // radius
private final double mass; // mass
private final Color color; // color
/**
* Initializes a particle with the specified position, velocity, radius, mass, and color.
*
* @param rx x-coordinate of position
* @param ry y-coordinate of position
* @param vx x-coordinate of velocity
* @param vy y-coordinate of velocity
* @param radius the radius
* @param mass the mass
* @param color the color
*/
public Particle(double rx, double ry, double vx, double vy, double radius, double mass, Color color) {
this.vx = vx;
this.vy = vy;
this.rx = rx;
this.ry = ry;
this.radius = radius;
this.mass = mass;
this.color = color;
}
/**
* Initializes a particle with a random position and velocity.
* The position is uniform in the unit box; the velocity in
* either direciton is chosen uniformly at random.
*/
public Particle() {
rx = StdRandom.uniform(0.0, 1.0);
ry = StdRandom.uniform(0.0, 1.0);
vx = StdRandom.uniform(-0.005, 0.005);
vy = StdRandom.uniform(-0.005, 0.005);
radius = 0.01;
mass = 0.5;
color = Color.BLACK;
}
/**
* Moves this particle in a straight line (based on its velocity)
* for the specified amount of time.
*
* @param dt the amount of time
*/
public void move(double dt) {
rx += vx * dt;
ry += vy * dt;
}
/**
* Draws this particle to standard draw.
*/
public void draw() {
StdDraw.setPenColor(color);
StdDraw.filledCircle(rx, ry, radius);
}
/**
* Returns the number of collisions involving this particle with
* vertical walls, horizontal walls, or other particles.
* This is equal to the number of calls to {@link #bounceOff},
* {@link #bounceOffVerticalWall}, and
* {@link #bounceOffHorizontalWall}.
*
* @return the number of collisions involving this particle with
* vertical walls, horizontal walls, or other particles
*/
public int count() {
return count;
}
/**
* Returns the amount of time for this particle to collide with the specified
* particle, assuming no interening collisions.
*
* @param that the other particle
* @return the amount of time for this particle to collide with the specified
* particle, assuming no interening collisions;
* {@code Double.POSITIVE_INFINITY} if the particles will not collide
*/
public double timeToHit(Particle that) {
if (this == that) return INFINITY;
double dx = that.rx - this.rx;
double dy = that.ry - this.ry;
double dvx = that.vx - this.vx;
double dvy = that.vy - this.vy;
double dvdr = dx*dvx + dy*dvy;
if (dvdr > 0) return INFINITY;
double dvdv = dvx*dvx + dvy*dvy;
double drdr = dx*dx + dy*dy;
double sigma = this.radius + that.radius;
double d = (dvdr*dvdr) - dvdv * (drdr - sigma*sigma);
// if (drdr < sigma*sigma) StdOut.println("overlapping particles");
if (d < 0) return INFINITY;
return -(dvdr + Math.sqrt(d)) / dvdv;
}
/**
* Returns the amount of time for this particle to collide with a vertical
* wall, assuming no interening collisions.
*
* @return the amount of time for this particle to collide with a vertical wall,
* assuming no interening collisions;
* {@code Double.POSITIVE_INFINITY} if the particle will not collide
* with a vertical wall
*/
public double timeToHitVerticalWall() {
if (vx > 0) return (1.0 - rx - radius) / vx;
else if (vx < 0) return (radius - rx) / vx;
else return INFINITY;
}
/**
* Returns the amount of time for this particle to collide with a horizontal
* wall, assuming no interening collisions.
*
* @return the amount of time for this particle to collide with a horizontal wall,
* assuming no interening collisions;
* {@code Double.POSITIVE_INFINITY} if the particle will not collide
* with a horizontal wall
*/
public double timeToHitHorizontalWall() {
if (vy > 0) return (1.0 - ry - radius) / vy;
else if (vy < 0) return (radius - ry) / vy;
else return INFINITY;
}
/**
* Updates the velocities of this particle and the specified particle according
* to the laws of elastic collision. Assumes that the particles are colliding
* at this instant.
*
* @param that the other particle
*/
public void bounceOff(Particle that) {
double dx = that.rx - this.rx;
double dy = that.ry - this.ry;
double dvx = that.vx - this.vx;
double dvy = that.vy - this.vy;
double dvdr = dx*dvx + dy*dvy; // dv dot dr
double dist = this.radius + that.radius; // distance between particle centers at collison
// magnitude of normal force
double magnitude = 2 * this.mass * that.mass * dvdr / ((this.mass + that.mass) * dist);
// normal force, and in x and y directions
double fx = magnitude * dx / dist;
double fy = magnitude * dy / dist;
// update velocities according to normal force
this.vx += fx / this.mass;
this.vy += fy / this.mass;
that.vx -= fx / that.mass;
that.vy -= fy / that.mass;
// update collision counts
this.count++;
that.count++;
}
/**
* Updates the velocity of this particle upon collision with a vertical
* wall (by reflecting the velocity in the x-direction).
* Assumes that the particle is colliding with a vertical wall at this instant.
*/
public void bounceOffVerticalWall() {
vx = -vx;
count++;
}
/**
* Updates the velocity of this particle upon collision with a horizontal
* wall (by reflecting the velocity in the y-direction).
* Assumes that the particle is colliding with a horizontal wall at this instant.
*/
public void bounceOffHorizontalWall() {
vy = -vy;
count++;
}
/**
* Returns the kinetic energy of this particle.
* The kinetic energy is given by the formula 1/2 m v2,
* where m is the mass of this particle and v is its velocity.
*
* @return the kinetic energy of this particle
*/
public double kineticEnergy() {
return 0.5 * mass * (vx*vx + vy*vy);
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Picture.java
================================================
/******************************************************************************
* Compilation: javac Picture.java
* Execution: java Picture imagename
* Dependencies: none
*
* Data type for manipulating individual pixels of an image. The original
* image can be read from a file in jpg, gif, or png format, or the
* user can create a blank image of a given size. Includes methods for
* displaying the image in a window on the screen or saving to a file.
*
* % java Picture mandrill.jpg
*
* Remarks
* -------
* - pixel (x, y) is column x and row y, where (0, 0) is upper left
*
* - see also GrayPicture.java for a grayscale version
*
******************************************************************************/
package algs4;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
/**
* This class provides methods for manipulating individual pixels of
* an image. The original image can be read from a {@code .jpg}, {@code .gif},
* or {@code .png} file or the user can create a blank image of a given size.
* This class includes methods for displaying the image in a window on
* the screen or saving it to a file.
*
* Pixel (col, row) is column col and row row.
* By default, the origin (0, 0) is the pixel in the top-left corner,
* which is a common convention in image processing.
* The method {@code setOriginLowerLeft()} change the origin to the lower left.
*
* For additional documentation, see
* Section 3.1 of
* Computer Science: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class Picture implements ActionListener {
private BufferedImage image; // the rasterized image
private JFrame frame; // on-screen view
private String filename; // name of file
private boolean isOriginUpperLeft = true; // location of origin
private final int width, height; // width and height
/**
* Initializes a blank {@code width}-by-{@code height} picture, with {@code width} columns
* and {@code height} rows, where each pixel is black.
*
* @param width the width of the picture
* @param height the height of the picture
* @throws IllegalArgumentException if {@code width} is negative
* @throws IllegalArgumentException if {@code height} is negative
*/
public Picture(int width, int height) {
if (width < 0) throw new IllegalArgumentException("width must be nonnegative");
if (height < 0) throw new IllegalArgumentException("height must be nonnegative");
this.width = width;
this.height = height;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// set to TYPE_INT_ARGB to support transparency
filename = width + "-by-" + height;
}
/**
* Initializes a new picture that is a deep copy of the argument picture.
*
* @param picture the picture to copy
*/
public Picture(Picture picture) {
width = picture.width();
height = picture.height();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
filename = picture.filename;
for (int col = 0; col < width(); col++)
for (int row = 0; row < height(); row++)
image.setRGB(col, row, picture.get(col, row).getRGB());
}
/**
* Initializes a picture by reading from a file or URL.
*
* @param filename the name of the file (.png, .gif, or .jpg) or URL.
* @throws IllegalArgumentException if cannot read image
*/
public Picture(String filename) {
this.filename = filename;
try {
// try to read from file in working directory
File file = new File(filename);
if (file.isFile()) {
image = ImageIO.read(file);
}
// now try to read from file in same directory as this .class file
else {
URL url = getClass().getResource(filename);
if (url == null) {
url = new URL(filename);
}
image = ImageIO.read(url);
}
if (image == null) {
throw new IllegalArgumentException("could not read image file: " + filename);
}
width = image.getWidth(null);
height = image.getHeight(null);
}
catch (IOException ioe) {
throw new IllegalArgumentException("could not open image file: " + filename, ioe);
}
}
/**
* Initializes a picture by reading in a .png, .gif, or .jpg from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot read image
*/
public Picture(File file) {
try {
image = ImageIO.read(file);
}
catch (IOException ioe) {
throw new IllegalArgumentException("could not open file: " + file, ioe);
}
if (image == null) {
throw new IllegalArgumentException("could not read file: " + file);
}
width = image.getWidth(null);
height = image.getHeight(null);
filename = file.getName();
}
/**
* Returns a JLabel containing this picture, for embedding in a JPanel,
* JFrame or other GUI widget.
*
* @return the {@code JLabel}
*/
public JLabel getJLabel() {
if (image == null) return null; // no image available
ImageIcon icon = new ImageIcon(image);
return new JLabel(icon);
}
/**
* Sets the origin to be the upper left pixel. This is the default.
*/
public void setOriginUpperLeft() {
isOriginUpperLeft = true;
}
/**
* Sets the origin to be the lower left pixel.
*/
public void setOriginLowerLeft() {
isOriginUpperLeft = false;
}
/**
* Displays the picture in a window on the screen.
*/
public void show() {
// create the GUI for viewing the image if needed
if (frame == null) {
frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Save... ");
menuItem1.addActionListener(this);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
frame.setJMenuBar(menuBar);
frame.setContentPane(getJLabel());
// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle(filename);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
// draw
frame.repaint();
}
/**
* Returns the height of the picture.
*
* @return the height of the picture (in pixels)
*/
public int height() {
return height;
}
/**
* Returns the width of the picture.
*
* @return the width of the picture (in pixels)
*/
public int width() {
return width;
}
private void validateRow(int row) {
if (row < 0 || row >= height())
throw new IndexOutOfBoundsException("row must be between 0 and " + (height() - 1) + ": " + row);
}
private void validateCol(int col) {
if (col < 0 || col >= width())
throw new IndexOutOfBoundsException("col must be between 0 and " + (width() - 1) + ": " + col);
}
/**
* Returns the color of pixel ({@code col}, {@code row}).
*
* @param col the column index
* @param row the row index
* @return the color of pixel ({@code col}, {@code row})
* @throws IndexOutOfBoundsException unless both {@code 0 <= col < width} and {@code 0 <= row < height}
*/
public Color get(int col, int row) {
validateCol(col);
validateRow(row);
if (isOriginUpperLeft) return new Color(image.getRGB(col, row));
else return new Color(image.getRGB(col, height - row - 1));
}
/**
* Sets the color of pixel ({@code col}, {@code row}) to given color.
*
* @param col the column index
* @param row the row index
* @param color the color
* @throws IndexOutOfBoundsException unless both {@code 0 <= col < width} and {@code 0 <= row < height}
* @throws IllegalArgumentException if {@code color} is {@code null}
*/
public void set(int col, int row, Color color) {
validateCol(col);
validateRow(row);
if (color == null) throw new IllegalArgumentException("color argument is null");
if (isOriginUpperLeft) image.setRGB(col, row, color.getRGB());
else image.setRGB(col, height - row - 1, color.getRGB());
}
/**
* Returns true if this picture is equal to the argument picture.
*
* @param other the other picture
* @return {@code true} if this picture is the same dimension as {@code other}
* and if all pixels have the same color; {@code false} otherwise
*/
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Picture that = (Picture) other;
if (this.width() != that.width()) return false;
if (this.height() != that.height()) return false;
for (int col = 0; col < width(); col++)
for (int row = 0; row < height(); row++)
if (!this.get(col, row).equals(that.get(col, row))) return false;
return true;
}
/**
* This operation is not supported because pictures are mutable.
*
* @return does not return a value
* @throws UnsupportedOperationException if called
*/
public int hashCode() {
throw new UnsupportedOperationException("hashCode() is not supported because pictures are mutable");
}
/**
* Saves the picture to a file in a standard image format.
* The filetype must be .png or .jpg.
*
* @param name the name of the file
*/
public void save(String name) {
save(new File(name));
}
/**
* Saves the picture to a file in a PNG or JPEG image format.
*
* @param file the file
*/
public void save(File file) {
filename = file.getName();
if (frame != null) frame.setTitle(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
if ("jpg".equalsIgnoreCase(suffix) || "png".equalsIgnoreCase(suffix)) {
try {
ImageIO.write(image, suffix, file);
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("Error: filename must end in .jpg or .png");
}
}
/**
* Opens a save dialog box when the user selects "Save As" from the menu.
*/
@Override
public void actionPerformed(ActionEvent e) {
FileDialog chooser = new FileDialog(frame,
"Use a .png or .jpg extension", FileDialog.SAVE);
chooser.setVisible(true);
if (chooser.getFile() != null) {
save(chooser.getDirectory() + File.separator + chooser.getFile());
}
}
/**
* Unit tests this {@code Picture} data type.
* Reads a picture specified by the command-line argument,
* and shows it in a window on the screen.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
Picture picture = new Picture(args[0]);
System.out.printf("%d-by-%d\n", picture.width(), picture.height());
picture.show();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/PictureDump.java
================================================
/******************************************************************************
* Compilation: javac PictureDump.java
* Execution: java PictureDump width height < file
* Dependencies: BinaryStdIn.java Picture.java
* Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt
*
* Reads in a binary file and writes out the bits as w-by-h picture,
* with the 1 bits in black and the 0 bits in white.
*
* % more abra.txt
* ABRACADABRA!
*
* % java PictureDump 16 6 < abra.txt
*
******************************************************************************/
package algs4;
import java.awt.Color;
/**
* The {@code PictureDump} class provides a client for displaying the contents
* of a binary file as a black-and-white picture.
*
* For additional documentation,
* see Section 5.5 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* See also {@link BinaryDump} and {@link HexDump}.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class PictureDump {
// Do not instantiate.
private PictureDump() { }
/**
* Reads in a sequence of bytes from standard input and draws
* them to standard drawing output as a width-by-height picture,
* using black for 1 and white for 0 (and red for any leftover
* pixels).
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
Picture picture = new Picture(width, height);
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if (!BinaryStdIn.isEmpty()) {
boolean bit = BinaryStdIn.readBoolean();
if (bit) picture.set(col, row, Color.BLACK);
else picture.set(col, row, Color.WHITE);
}
else {
picture.set(col, row, Color.RED);
}
}
}
picture.show();
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/Point2D.java
================================================
/******************************************************************************
* Compilation: javac Point2D.java
* Execution: java Point2D x0 y0 N
* Dependencies: StdDraw.java StdRandom.java
*
* Immutable point data type for points in the plane.
*
******************************************************************************/
package algs4;
import java.util.Arrays;
import java.util.Comparator;
/**
* The {@code Point} class is an immutable data type to encapsulate a
* two-dimensional point with real-value coordinates.
*
* Note: in order to deal with the difference behavior of double and
* Double with respect to -0.0 and +0.0, the Point2D constructor converts
* any coordinates that are -0.0 to +0.0.
*
* For additional documentation,
* see Section 1.2 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class Point2D implements Comparable
* This implementation uses a singly-linked list with a static nested class for
* linked-list nodes. See {@link LinkedQueue} for the version from the
* textbook that uses a non-static nested class.
* The enqueue, dequeue, peek, size, and is-empty
* operations all take constant time in the worst case.
*
* For additional documentation, see Section 1.3 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* Even though this implementation include the method {@code equals()}, it
* does not support the method {@code hashCode()} because sets are mutable.
*
* This implementation uses a balanced binary search tree. It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* The add, contains, delete, minimum,
* maximum, ceiling, and floor methods take
* logarithmic time in the worst case.
* The size, and is-empty operations take constant time.
* Construction takes constant time.
*
* This implementation uses a balanced binary search tree. It requires that
* For additional documentation, see
* Section 3.5 of
* Algorithms in Java, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* Note that this method declares two empty sets to be equal
* even if they are parameterized by different generic types.
* This is consistent with the behavior of {@code equals()}
* within Java's Collections framework.
*
* @param other the other set
* @return {@code true} if this set equals {@code other};
* {@code false} otherwise
*/
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
SET that = (SET) other;
return this.set.equals(that.set);
}
/**
* This operation is not supported because sets are mutable.
*
* @return does not return a value
* @throws UnsupportedOperationException if called
*/
@Override
public int hashCode() {
throw new UnsupportedOperationException("hashCode() is not supported because sets are mutable");
}
/**
* Returns a string representation of this set.
*
* @return a string representation of this set, enclosed in curly braces,
* with adjacent keys separated by a comma and a space
*/
@Override
public String toString() {
String s = set.toString();
return "{ " + s.substring(1, s.length() - 1) + " }";
}
/**
* Unit tests the {@code SET} data type.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
SET
* This implementation uses a balanced binary search tree. It requires that
* the key type implements the {@code Comparable} interface and calls the
* {@code compareTo()} and method to compare two keys. It does not call either
* {@code equals()} or {@code hashCode()}.
* The put, contains, remove, minimum,
* maximum, ceiling, and floor operations each take
* logarithmic time in the worst case.
* The size, and is-empty operations take constant time.
* Construction takes constant time.
*
* For additional documentation, see Section 3.5 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* To iterate over all of the keys in the symbol table named {@code st},
* use the foreach notation: {@code for (Key key : st.keys())}.
*
* @return all keys in this symbol table
*/
public Iterable
* This method is provided for backward compatibility with the version from
* Introduction to Programming in Java: An Interdisciplinary Approach.
*
* @return an iterator to all of the keys in this symbol table
* @deprecated Replaced by {@link #keys()}.
*/
@Deprecated
public Iterator
* This implementation uses a singly-linked list with a static nested class for
* linked-list nodes. See {@link LinkedStack} for the version from the
* textbook that uses a non-static nested class.
* The push, pop, peek, size, and is-empty
* operations all take constant time in the worst case.
*
* For additional documentation,
* see Section 1.3 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @param
* Getting started.
* To use standard drawing, you must have {@code StdDraw.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* StdDraw.java
* and put a copy in your working directory.
*
* Now, type the following short program into your editor:
*
* Points and lines.
* You can draw points and line segments with the following methods:
*
* The x- and y-coordinates must be in the drawing area
* (between 0 and 1 and by default) or the points and lines will not be visible.
*
* Squares, circles, rectangles, and ellipses.
* You can draw squares, circles, rectangles, and ellipses using
* the following methods:
*
* All of these methods take as arguments the location and size of the shape.
* The location is always specified by the x- and y-coordinates
* of its center.
* The size of a circle is specified by its radius and the size of an ellipse is
* specified by the lengths of its semi-major and semi-minor axes.
* The size of a square or rectangle is specified by its half-width or half-height.
* The convention for drawing squares and rectangles is parallel to those for
* drawing circles and ellipses, but may be unexpected to the uninitiated.
*
* The methods above trace outlines of the given shapes. The following methods
* draw filled versions:
*
* Circular arcs.
* You can draw circular arcs with the following method:
*
* The arc is from the circle centered at (x, y) of the specified radius.
* The arc extends from angle1 to angle2. By convention, the angles are
* polar (counterclockwise angle from the x-axis)
* and represented in degrees. For example, {@code StdDraw.arc(0.0, 0.0, 1.0, 0, 90)}
* draws the arc of the unit circle from 3 o'clock (0 degrees) to 12 o'clock (90 degrees).
*
* Polygons.
* You can draw polygons with the following methods:
*
* The points in the polygon are ({@code x[i]}, {@code y[i]}).
* For example, the following code fragment draws a filled diamond
* with vertices (0.1, 0.2), (0.2, 0.3), (0.3, 0.2), and (0.2, 0.1):
*
* Pen size.
* The pen is circular, so that when you set the pen radius to r
* and draw a point, you get a circle of radius r. Also, lines are
* of thickness 2r and have rounded ends. The default pen radius
* is 0.005 and is not affected by coordinate scaling. This default pen
* radius is about 1/200 the width of the default canvas, so that if
* you draw 100 points equally spaced along a horizontal or vertical line,
* you will be able to see individual circles, but if you draw 200 such
* points, the result will look like a line.
*
* For example, {@code StdDraw.setPenRadius(0.025)} makes
* the thickness of the lines and the size of the points to be five times
* the 0.005 default.
* To draw points with the minimum possible radius (one pixel on typical
* displays), set the pen radius to 0.0.
*
* Pen color.
* All geometric shapes (such as points, lines, and circles) are drawn using
* the current pen color. By default, it is black.
* You can change the pen color with the following methods:
*
* The first method allows you to specify colors using the RGB color system.
* This color picker
* is a convenient way to find a desired color.
* The second method allows you to specify colors using the
* {@link Color} data type that is discussed in Chapter 3. Until then,
* you can use this method with one of these predefined colors in standard drawing:
* {@link #BLACK}, {@link #BLUE}, {@link #CYAN}, {@link #DARK_GRAY}, {@link #GRAY},
* {@link #GREEN}, {@link #LIGHT_GRAY}, {@link #MAGENTA}, {@link #ORANGE},
* {@link #PINK}, {@link #RED}, {@link #WHITE}, and {@link #YELLOW}.
* For example, {@code StdDraw.setPenColor(StdDraw.MAGENTA)} sets the
* pen color to magenta.
*
* Canvas size.
* By default, all drawing takes places in a 512-by-512 canvas.
* The canvas does not include the window title or window border.
* You can change the size of the canvas with the following method:
*
* This sets the canvas size to be width-by-height pixels.
* It also erases the current drawing and resets the coordinate system,
* pen radius, pen color, and font back to their default values.
* Ordinarly, this method is called once, at the very beginning of a program.
* For example, {@code StdDraw.setCanvasSize(800, 800)}
* sets the canvas size to be 800-by-800 pixels.
*
* Canvas scale and coordinate system.
* By default, all drawing takes places in the unit square, with (0, 0) at
* lower left and (1, 1) at upper right. You can change the default
* coordinate system with the following methods:
*
* The arguments are the coordinates of the minimum and maximum
* x- or y-coordinates that will appear in the canvas.
* For example, if you wish to use the default coordinate system but
* leave a small margin, you can call {@code StdDraw.setScale(-.05, 1.05)}.
*
* These methods change the coordinate system for subsequent drawing
* commands; they do not affect previous drawings.
* These methods do not change the canvas size; so, if the x-
* and y-scales are different, squares will become rectangles
* and circles will become ellipsoidal.
*
* Text.
* You can use the following methods to annotate your drawings with text:
*
* The first two methods write the specified text in the current font,
* centered at (x, y).
* The second method allows you to rotate the text.
* The last two methods either left- or right-align the text at (x, y).
*
* The default font is a Sans Serif font with point size 16.
* You can use the following method to change the font:
*
* You use the {@link Font} data type to specify the font. This allows you to
* choose the face, size, and style of the font. For example, the following
* code fragment sets the font to Arial Bold, 60 point.
*
* Images.
* You can use the following methods to add images to your drawings:
*
* These methods draw the specified image, centered at (x, y).
* The supported image formats are JPEG, PNG, and GIF.
* The image will display at its native size, independent of the coordinate system.
* Optionally, you can rotate the image a specified number of degrees counterclockwise
* or rescale it to fit snugly inside a width-by-height bounding box.
*
* Saving to a file.
* You save your image to a file using the File → Save menu option.
* You can also save a file programatically using the following method:
*
* The supported image formats are JPEG and PNG. The filename must have either the
* extension .jpg or .png.
* We recommend using PNG for drawing that consist solely of geometric shapes and JPEG
* for drawings that contains pictures.
*
* Clearing the canvas.
* To clear the entire drawing canvas, you can use the following methods:
*
* The first method clears the canvas to white; the second method
* allows you to specify a color of your choice. For example,
* {@code StdDraw.clear(StdDraw.LIGHT_GRAY)} clears the canvas to a shade
* of gray.
*
* Computer animations and double buffering.
* Double buffering is one of the most powerful features of standard drawing,
* enabling computer animations.
* The following methods control the way in which objects are drawn:
*
* By default, double buffering is disabled, which means that as soon as you
* call a drawing
* method—such as {@code point()} or {@code line()}—the
* results appear on the screen.
*
* When double buffering is enabled by calling {@link #enableDoubleBuffering()},
* all drawing takes place on the offscreen canvas. The offscreen canvas
* is not displayed. Only when you call
* {@link #show()} does your drawing get copied from the offscreen canvas to
* the onscreen canvas, where it is displayed in the standard drawing window. You
* can think of double buffering as collecting all of the lines, points, shapes,
* and text that you tell it to draw, and then drawing them all
* simultaneously, upon request.
*
* The most important use of double buffering is to produce computer
* animations, creating the illusion of motion by rapidly
* displaying static drawings. To produce an animation, repeat
* the following four steps:
*
* The {@link #clear()}, {@link #show()}, and {@link #pause(int dt)} methods
* support the first, third, and fourth of these steps, respectively.
*
* For example, this code fragment animates two balls moving in a circle.
*
* Keyboard and mouse inputs.
* Standard drawing has very basic support for keyboard and mouse input.
* It is much less powerful than most user interface libraries provide, but also much simpler.
* You can use the following methods to intercept mouse events:
*
* The first method tells you whether a mouse button is currently being pressed.
* The last two methods tells you the x- and y-coordinates of the mouse's
* current position, using the same coordinate system as the canvas (the unit square, by default).
* You should use these methods in an animation loop that waits a short while before trying
* to poll the mouse for its current state.
* You can use the following methods to intercept keyboard events:
*
* If the user types lots of keys, they will be saved in a list until you process them.
* The first method tells you whether the user has typed a key (that your program has
* not yet processed).
* The second method returns the next key that the user typed (that your program has
* not yet processed) and removes it from the list of saved keystrokes.
* The third method tells you whether a key is currently being pressed.
*
* Accessing control parameters.
* You can use the following methods to access the current pen color, pen radius,
* and font:
*
* These methods are useful when you want to temporarily change a
* control parameter and reset it back to its original value.
*
* Corner cases.
* To avoid clutter, the API doesn't explicitly refer to arguments that are
* null, infinity, or NaN.
*
* Performance tricks.
* Standard drawing is capable of drawing large amounts of data.
* Here are a few tricks and tips:
*
* Known bugs and issues.
*
* Reference.
* For additional documentation,
* see Section 1.5 of
* Introduction to Programming in Java: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdDraw implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
/**
* The color black.
*/
public static final Color BLACK = Color.BLACK;
/**
* The color blue.
*/
public static final Color BLUE = Color.BLUE;
/**
* The color cyan.
*/
public static final Color CYAN = Color.CYAN;
/**
* The color dark gray.
*/
public static final Color DARK_GRAY = Color.DARK_GRAY;
/**
* The color gray.
*/
public static final Color GRAY = Color.GRAY;
/**
* The color green.
*/
public static final Color GREEN = Color.GREEN;
/**
* The color light gray.
*/
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
/**
* The color magenta.
*/
public static final Color MAGENTA = Color.MAGENTA;
/**
* The color orange.
*/
public static final Color ORANGE = Color.ORANGE;
/**
* The color pink.
*/
public static final Color PINK = Color.PINK;
/**
* The color red.
*/
public static final Color RED = Color.RED;
/**
* The color white.
*/
public static final Color WHITE = Color.WHITE;
/**
* The color yellow.
*/
public static final Color YELLOW = Color.YELLOW;
/**
* Shade of blue used in Introduction to Programming in Java.
* It is Pantone 300U. The RGB values are approximately (9, 90, 166).
*/
public static final Color BOOK_BLUE = new Color(9, 90, 166);
/**
* Shade of light blue used in Introduction to Programming in Java.
* The RGB values are approximately (103, 198, 243).
*/
public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243);
/**
* Shade of red used in Algorithms, 4th edition.
* It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
*/
public static final Color BOOK_RED = new Color(150, 35, 31);
// default colors
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// current pen color
private static Color penColor;
// default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE
private static final int DEFAULT_SIZE = 512;
private static int width = DEFAULT_SIZE;
private static int height = DEFAULT_SIZE;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// current pen radius
private static double penRadius;
// show we draw immediately or wait until next show?
private static boolean defer = false;
// boundary of drawing canvas, 0% border
// private static final double BORDER = 0.05;
private static final double BORDER = 0.00;
private static final double DEFAULT_XMIN = 0.0;
private static final double DEFAULT_XMAX = 1.0;
private static final double DEFAULT_YMIN = 0.0;
private static final double DEFAULT_YMAX = 1.0;
private static double xmin, ymin, xmax, ymax;
// for synchronization
private static Object mouseLock = new Object();
private static Object keyLock = new Object();
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16);
// current font
private static Font font;
// double buffered graphics
private static BufferedImage offscreenImage, onscreenImage;
private static Graphics2D offscreen, onscreen;
// singleton for callbacks: avoids generation of extra .class files
private static StdDraw std = new StdDraw();
// the frame for drawing to the screen
private static JFrame frame;
// mouse state
private static boolean mousePressed = false;
private static double mouseX = 0;
private static double mouseY = 0;
// queue of typed key characters
private static LinkedList
* The predefined pen colors are
* {@code StdDraw.BLACK}, {@code StdDraw.BLUE}, {@code StdDraw.CYAN},
* {@code StdDraw.DARK_GRAY}, {@code StdDraw.GRAY}, {@code StdDraw.GREEN},
* {@code StdDraw.LIGHT_GRAY}, {@code StdDraw.MAGENTA}, {@code StdDraw.ORANGE},
* {@code StdDraw.PINK}, {@code StdDraw.RED}, {@code StdDraw.WHITE}, and
* {@code StdDraw.YELLOW}.
*
* @param color the color to make the pen
*/
public static void setPenColor(Color color) {
if (color == null) throw new NullPointerException();
penColor = color;
offscreen.setColor(penColor);
}
/**
* Sets the pen color to the specified RGB color.
*
* @param red the amount of red (between 0 and 255)
* @param green the amount of green (between 0 and 255)
* @param blue the amount of blue (between 0 and 255)
* @throws IllegalArgumentException if {@code red}, {@code green},
* or {@code blue} is outside its prescribed range
*/
public static void setPenColor(int red, int green, int blue) {
if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255");
if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of green must be between 0 and 255");
if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of blue must be between 0 and 255");
setPenColor(new Color(red, green, blue));
}
/**
* Returns the current font.
*
* @return the current font
*/
public static Font getFont() {
return font;
}
/**
* Sets the font to the default font (sans serif, 16 point).
*/
public static void setFont() {
setFont(DEFAULT_FONT);
}
/**
* Sets the font to the specified value.
*
* @param font the font
*/
public static void setFont(Font font) {
if (font == null) throw new NullPointerException();
StdDraw.font = font;
}
/***************************************************************************
* Drawing geometric shapes.
***************************************************************************/
/**
* Draws a line segment between (x0, y0) and
* (x1, y1).
*
* @param x0 the x-coordinate of one endpoint
* @param y0 the y-coordinate of one endpoint
* @param x1 the x-coordinate of the other endpoint
* @param y1 the y-coordinate of the other endpoint
*/
public static void line(double x0, double y0, double x1, double y1) {
offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));
draw();
}
/**
* Draws one pixel at (x, y).
* This method is private because pixels depend on the display.
* To achieve the same effect, set the pen radius to 0 and call {@code point()}.
*
* @param x the x-coordinate of the pixel
* @param y the y-coordinate of the pixel
*/
private static void pixel(double x, double y) {
offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
}
/**
* Draws a point centered at (x, y).
* The point is a filled circle whose radius is equal to the pen radius.
* To draw a single-pixel point, first set the pen radius to 0.
*
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
*/
public static void point(double x, double y) {
double xs = scaleX(x);
double ys = scaleY(y);
double r = penRadius;
float scaledPenRadius = (float) (r * DEFAULT_SIZE);
// double ws = factorX(2*r);
// double hs = factorY(2*r);
// if (ws <= 1 && hs <= 1) pixel(x, y);
if (scaledPenRadius <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - scaledPenRadius/2, ys - scaledPenRadius/2,
scaledPenRadius, scaledPenRadius));
draw();
}
/**
* Draws a circle of the specified radius, centered at (x, y).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param radius the radius of the circle
* @throws IllegalArgumentException if {@code radius} is negative
*/
public static void circle(double x, double y, double radius) {
if (!(radius >= 0)) throw new IllegalArgumentException("radius must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*radius);
double hs = factorY(2*radius);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled circle of the specified radius, centered at (x, y).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param radius the radius of the circle
* @throws IllegalArgumentException if {@code radius} is negative
*/
public static void filledCircle(double x, double y, double radius) {
if (!(radius >= 0)) throw new IllegalArgumentException("radius must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*radius);
double hs = factorY(2*radius);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws an ellipse with the specified semimajor and semiminor axes,
* centered at (x, y).
*
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either {@code semiMajorAxis}
* or {@code semiMinorAxis} is negative
*/
public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (!(semiMajorAxis >= 0)) throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
if (!(semiMinorAxis >= 0)) throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws an ellipse with the specified semimajor and semiminor axes,
* centered at (x, y).
*
* @param x the x-coordinate of the center of the ellipse
* @param y the y-coordinate of the center of the ellipse
* @param semiMajorAxis is the semimajor axis of the ellipse
* @param semiMinorAxis is the semiminor axis of the ellipse
* @throws IllegalArgumentException if either {@code semiMajorAxis}
* or {@code semiMinorAxis} is negative
*/
public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) {
if (!(semiMajorAxis >= 0)) throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative");
if (!(semiMinorAxis >= 0)) throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*semiMajorAxis);
double hs = factorY(2*semiMinorAxis);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a circular arc of the specified radius,
* centered at (x, y), from angle1 to angle2 (in degrees).
*
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param radius the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws IllegalArgumentException if {@code radius} is negative
*/
public static void arc(double x, double y, double radius, double angle1, double angle2) {
if (radius < 0) throw new IllegalArgumentException("arc radius must be nonnegative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*radius);
double hs = factorY(2*radius);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));
draw();
}
/**
* Draws a square of side length 2r, centered at (x, y).
*
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param halfLength one half the length of any side of the square
* @throws IllegalArgumentException if {@code halfLength} is negative
*/
public static void square(double x, double y, double halfLength) {
if (!(halfLength >= 0)) throw new IllegalArgumentException("half length must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfLength);
double hs = factorY(2*halfLength);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled square of the specified size, centered at (x, y).
*
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param halfLength one half the length of any side of the square
* @throws IllegalArgumentException if {@code halfLength} is negative
*/
public static void filledSquare(double x, double y, double halfLength) {
if (!(halfLength >= 0)) throw new IllegalArgumentException("half length must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfLength);
double hs = factorY(2*halfLength);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a rectangle of the specified size, centered at (x, y).
*
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth one half the width of the rectangle
* @param halfHeight one half the height of the rectangle
* @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative
*/
public static void rectangle(double x, double y, double halfWidth, double halfHeight) {
if (!(halfWidth >= 0)) throw new IllegalArgumentException("half width must be nonnegative");
if (!(halfHeight >= 0)) throw new IllegalArgumentException("half height must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a filled rectangle of the specified size, centered at (x, y).
*
* @param x the x-coordinate of the center of the rectangle
* @param y the y-coordinate of the center of the rectangle
* @param halfWidth one half the width of the rectangle
* @param halfHeight one half the height of the rectangle
* @throws IllegalArgumentException if either {@code halfWidth} or {@code halfHeight} is negative
*/
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) {
if (!(halfWidth >= 0)) throw new IllegalArgumentException("half width must be nonnegative");
if (!(halfHeight >= 0)) throw new IllegalArgumentException("half height must be nonnegative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*halfWidth);
double hs = factorY(2*halfHeight);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
draw();
}
/**
* Draws a polygon with the vertices
* (x0, y0),
* (x1, y1), ...,
* (xn−1, yn−1).
*
* @param x an array of all the x-coordinates of the polygon
* @param y an array of all the y-coordinates of the polygon
* @throws IllegalArgumentException unless {@code x[]} and {@code y[]}
* are of the same length
*/
public static void polygon(double[] x, double[] y) {
if (x == null) throw new NullPointerException();
if (y == null) throw new NullPointerException();
int n1 = x.length;
int n2 = y.length;
if (n1 != n2) throw new IllegalArgumentException("arrays must be of the same length");
int n = n1;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < n; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.draw(path);
draw();
}
/**
* Draws a polygon with the vertices
* (x0, y0),
* (x1, y1), ...,
* (xn−1, yn−1).
*
* @param x an array of all the x-coordinates of the polygon
* @param y an array of all the y-coordinates of the polygon
* @throws IllegalArgumentException unless {@code x[]} and {@code y[]}
* are of the same length
*/
public static void filledPolygon(double[] x, double[] y) {
if (x == null) throw new NullPointerException();
if (y == null) throw new NullPointerException();
int n1 = x.length;
int n2 = y.length;
if (n1 != n2) throw new IllegalArgumentException("arrays must be of the same length");
int n = n1;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < n; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.fill(path);
draw();
}
/***************************************************************************
* Drawing images.
***************************************************************************/
// get an image from the given filename
private static Image getImage(String filename) {
if (filename == null) throw new NullPointerException();
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
}
catch (Exception e) {
/* not a url */
}
}
// in case file is inside a .jar (classpath relative to StdDraw)
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = StdDraw.class.getResource(filename);
if (url != null)
icon = new ImageIcon(url);
}
// in case file is inside a .jar (classpath relative to root of jar)
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = StdDraw.class.getResource("/" + filename);
if (url == null) throw new IllegalArgumentException("image " + filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
}
/***************************************************************************
* [Summer 2016] Should we update to use ImageIO instead of ImageIcon()?
* Seems to have some issues loading images on some systems
* and slows things down on other systems.
* especially if you don't call ImageIO.setUseCache(false)
* One advantage is that it returns a BufferedImage.
***************************************************************************/
/*
private static BufferedImage getImage(String filename) {
if (filename == null) throw new NullPointerException();
// from a file or URL
try {
URL url = new URL(filename);
BufferedImage image = ImageIO.read(url);
return image;
}
catch (IOException e) {
// ignore
}
// in case file is inside a .jar (classpath relative to StdDraw)
try {
URL url = StdDraw.class.getResource(filename);
BufferedImage image = ImageIO.read(url);
return image;
}
catch (IOException e) {
// ignore
}
// in case file is inside a .jar (classpath relative to root of jar)
try {
URL url = StdDraw.class.getResource("/" + filename);
BufferedImage image = ImageIO.read(url);
return image;
}
catch (IOException e) {
// ignore
}
throw new IllegalArgumentException("image " + filename + " not found");
}
*/
/**
* Draws the specified image centered at (x, y).
* The supported image formats are JPEG, PNG, and GIF.
* As an optimization, the picture is cached, so there is no performance
* penalty for redrawing the same image multiple times (e.g., in an animation).
* However, if you change the picture file after drawing it, subsequent
* calls will draw the original picture.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @throws IllegalArgumentException if the image filename is invalid
*/
public static void picture(double x, double y, String filename) {
// BufferedImage image = getImage(filename);
Image image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
// int ws = image.getWidth(); // can call only if image is a BufferedImage
// int hs = image.getHeight();
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
draw();
}
/**
* Draws the specified image centered at (x, y),
* rotated given number of degrees.
* The supported image formats are JPEG, PNG, and GIF.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if the image filename is invalid
*/
public static void picture(double x, double y, String filename, double degrees) {
// BufferedImage image = getImage(filename);
Image image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
// int ws = image.getWidth(); // can call only if image is a BufferedImage
// int hs = image.getHeight();
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
draw();
}
/**
* Draws the specified image centered at (x, y),
* rescaled to the specified bounding box.
* The supported image formats are JPEG, PNG, and GIF.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param scaledWidth the width of the scaled image (in screen coordinates)
* @param scaledHeight the height of the scaled image (in screen coordinates)
* @throws IllegalArgumentException if either {@code scaledWidth}
* or {@code scaledHeight} is negative
* @throws IllegalArgumentException if the image filename is invalid
*/
public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight) {
Image image = getImage(filename);
if (scaledWidth < 0) throw new IllegalArgumentException("width is negative: " + scaledWidth);
if (scaledHeight < 0) throw new IllegalArgumentException("height is negative: " + scaledHeight);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(scaledWidth);
double hs = factorY(scaledHeight);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
else {
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
}
draw();
}
/**
* Draws the specified image centered at (x, y), rotated
* given number of degrees, and rescaled to the specified bounding box.
* The supported image formats are JPEG, PNG, and GIF.
*
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param filename the name of the image/picture, e.g., "ball.gif"
* @param scaledWidth the width of the scaled image (in screen coordinates)
* @param scaledHeight the height of the scaled image (in screen coordinates)
* @param degrees is the number of degrees to rotate counterclockwise
* @throws IllegalArgumentException if either {@code scaledWidth}
* or {@code scaledHeight} is negative
* @throws IllegalArgumentException if the image filename is invalid
*/
public static void picture(double x, double y, String filename, double scaledWidth, double scaledHeight, double degrees) {
if (scaledWidth < 0) throw new IllegalArgumentException("width is negative: " + scaledWidth);
if (scaledHeight < 0) throw new IllegalArgumentException("height is negative: " + scaledHeight);
Image image = getImage(filename);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(scaledWidth);
double hs = factorY(scaledHeight);
if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + filename + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
draw();
}
/***************************************************************************
* Drawing text.
***************************************************************************/
/**
* Write the given text string in the current font, centered at (x, y).
*
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param text the text to write
*/
public static void text(double x, double y, String text) {
if (text == null) throw new NullPointerException();
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int ws = metrics.stringWidth(text);
int hs = metrics.getDescent();
offscreen.drawString(text, (float) (xs - ws/2.0), (float) (ys + hs));
draw();
}
/**
* Write the given text string in the current font, centered at (x, y) and
* rotated by the specified number of degrees.
* @param x the center x-coordinate of the text
* @param y the center y-coordinate of the text
* @param text the text to write
* @param degrees is the number of degrees to rotate counterclockwise
*/
public static void text(double x, double y, String text, double degrees) {
if (text == null) throw new NullPointerException();
double xs = scaleX(x);
double ys = scaleY(y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
text(x, y, text);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
}
/**
* Write the given text string in the current font, left-aligned at (x, y).
* @param x the x-coordinate of the text
* @param y the y-coordinate of the text
* @param text the text
*/
public static void textLeft(double x, double y, String text) {
if (text == null) throw new NullPointerException();
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int hs = metrics.getDescent();
offscreen.drawString(text, (float) xs, (float) (ys + hs));
draw();
}
/**
* Write the given text string in the current font, right-aligned at (x, y).
*
* @param x the x-coordinate of the text
* @param y the y-coordinate of the text
* @param text the text to write
*/
public static void textRight(double x, double y, String text) {
if (text == null) throw new NullPointerException();
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int ws = metrics.stringWidth(text);
int hs = metrics.getDescent();
offscreen.drawString(text, (float) (xs - ws), (float) (ys + hs));
draw();
}
/**
* Copies the offscreen buffer to the onscreen buffer, pauses for t milliseconds
* and enables double buffering.
* @param t number of milliseconds
* @deprecated replaced by {@link #enableDoubleBuffering}, {@link #show()}, and {@link #pause}
*/
@Deprecated
public static void show(int t) {
// sleep until the next time we're allowed to draw
long millis = System.currentTimeMillis();
if (millis < nextDraw) {
try {
Thread.sleep(nextDraw - millis);
}
catch (InterruptedException e) {
System.out.println("Error sleeping");
}
millis = nextDraw;
}
show();
enableDoubleBuffering();
// when are we allowed to draw again
nextDraw = millis + t;
}
/**
* Pause for t milliseconds. This method is intended to support computer animations.
* @param t number of milliseconds
*/
public static void pause(int t) {
// sleep until the next time we're allowed to draw
long millis = System.currentTimeMillis();
if (millis < nextDraw) {
try {
Thread.sleep(nextDraw - millis);
}
catch (InterruptedException e) {
System.out.println("Error sleeping");
}
millis = nextDraw;
}
// when are we allowed to draw again
nextDraw = millis + t;
}
/**
* Copies offscreen buffer to onscreen buffer. There is no reason to call
* this method unless double buffering is enabled.
*/
public static void show() {
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
}
// draw onscreen if defer is false
private static void draw() {
if (!defer) show();
}
/**
* Enable double buffering. All subsequent calls to
* drawing methods such as {@code line()}, {@code circle()},
* and {@code square()} will be deffered until the next call
* to show(). Useful for animations.
*/
public static void enableDoubleBuffering() {
defer = true;
}
/**
* Disable double buffering. All subsequent calls to
* drawing methods such as {@code line()}, {@code circle()},
* and {@code square()} will be displayed on screen when called.
* This is the default.
*/
public static void disableDoubleBuffering() {
defer = false;
}
/***************************************************************************
* Save drawing to a file.
***************************************************************************/
/**
* Saves the drawing to using the specified filename.
* The supported image formats are JPEG and PNG;
* the filename suffix must be {@code .jpg} or {@code .png}.
*
* @param filename the name of the file with one of the required suffixes
*/
public static void save(String filename) {
if (filename == null) throw new NullPointerException();
File file = new File(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if (suffix.toLowerCase().equals("png")) {
try {
ImageIO.write(onscreenImage, suffix, file);
}
catch (IOException e) {
e.printStackTrace();
}
}
// need to change from ARGB to RGB for JPEG
// reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
else if (suffix.toLowerCase().equals("jpg")) {
WritableRaster raster = onscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
try {
ImageIO.write(rgbBuffer, suffix, file);
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
/**
* This method cannot be called directly.
*/
@Override
public void actionPerformed(ActionEvent e) {
FileDialog chooser = new FileDialog(StdDraw.frame, "Use a .png or .jpg extension", FileDialog.SAVE);
chooser.setVisible(true);
String filename = chooser.getFile();
if (filename != null) {
StdDraw.save(chooser.getDirectory() + File.separator + chooser.getFile());
}
}
/***************************************************************************
* Mouse interactions.
***************************************************************************/
/**
* Returns true if the mouse is being pressed.
*
* @return {@code true} if the mouse is being pressed; {@code false} otherwise
*/
public static boolean mousePressed() {
synchronized (mouseLock) {
return mousePressed;
}
}
/**
* Returns the x-coordinate of the mouse.
*
* @return the x-coordinate of the mouse
*/
public static double mouseX() {
synchronized (mouseLock) {
return mouseX;
}
}
/**
* Returns the y-coordinate of the mouse.
*
* @return y-coordinate of the mouse
*/
public static double mouseY() {
synchronized (mouseLock) {
return mouseY;
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseClicked(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
@Override
public void mouseEntered(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
@Override
public void mouseExited(MouseEvent e) { }
/**
* This method cannot be called directly.
*/
@Override
public void mousePressed(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
mousePressed = true;
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseReleased(MouseEvent e) {
synchronized (mouseLock) {
mousePressed = false;
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseDragged(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
}
}
/**
* This method cannot be called directly.
*/
@Override
public void mouseMoved(MouseEvent e) {
synchronized (mouseLock) {
mouseX = StdDraw.userX(e.getX());
mouseY = StdDraw.userY(e.getY());
}
}
/***************************************************************************
* Keyboard interactions.
***************************************************************************/
/**
* Returns true if the user has typed a key (that has not yet been processed).
*
* @return {@code true} if the user has typed a key (that has not yet been processed
* by {@link #nextKeyTyped()}; {@code false} otherwise
*/
public static boolean hasNextKeyTyped() {
synchronized (keyLock) {
return !keysTyped.isEmpty();
}
}
/**
* Returns the next key that was typed by the user (that your program has not already processed).
* This method should be preceded by a call to {@link #hasNextKeyTyped()} to ensure
* that there is a next key to process.
* This method returns a Unicode character corresponding to the key
* typed (such as {@code 'a'} or {@code 'A'}).
* It cannot identify action keys (such as F1 and arrow keys)
* or modifier keys (such as control).
*
* @return the next key typed by the user (that your program has not already processed).
* @throws NoSuchElementException if there is no remaining key
*/
public static char nextKeyTyped() {
synchronized (keyLock) {
if (keysTyped.isEmpty()) {
throw new NoSuchElementException("your program has already processed all keystrokes");
}
return keysTyped.removeLast();
}
}
/**
* Returns true if the given key is being pressed.
*
* This method takes the keycode (corresponding to a physical key)
* as an argument. It can handle action keys
* (such as F1 and arrow keys) and modifier keys (such as shift and control).
* See {@link KeyEvent} for a description of key codes.
*
* @param keycode the key to check if it is being pressed
* @return {@code true} if {@code keycode} is currently being pressed;
* {@code false} otherwise
*/
public static boolean isKeyPressed(int keycode) {
synchronized (keyLock) {
return keysDown.contains(keycode);
}
}
/**
* This method cannot be called directly.
*/
@Override
public void keyTyped(KeyEvent e) {
synchronized (keyLock) {
keysTyped.addFirst(e.getKeyChar());
}
}
/**
* This method cannot be called directly.
*/
@Override
public void keyPressed(KeyEvent e) {
synchronized (keyLock) {
keysDown.add(e.getKeyCode());
}
}
/**
* This method cannot be called directly.
*/
@Override
public void keyReleased(KeyEvent e) {
synchronized (keyLock) {
keysDown.remove(e.getKeyCode());
}
}
/**
* Test client.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
StdDraw.square(.2, .8, .1);
StdDraw.filledSquare(.8, .8, .2);
StdDraw.circle(.8, .2, .2);
StdDraw.setPenColor(StdDraw.BOOK_RED);
StdDraw.setPenRadius(.02);
StdDraw.arc(.8, .2, .1, 200, 45);
// draw a blue diamond
StdDraw.setPenRadius();
StdDraw.setPenColor(StdDraw.BOOK_BLUE);
double[] x = { .1, .2, .3, .2 };
double[] y = { .2, .3, .2, .1 };
StdDraw.filledPolygon(x, y);
// text
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(0.2, 0.5, "black text");
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.text(0.8, 0.8, "white text");
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/StdIn.java
================================================
/******************************************************************************
* Compilation: javac StdIn.java
* Execution: java StdIn (interactive test of basic functionality)
* Dependencies: none
*
* Reads in data of various types from standard input.
*
******************************************************************************/
package algs4;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* The {@code StdIn} class provides static methods for reading strings
* and numbers from standard input.
* These functions fall into one of four categories:
*
* Generally, it is best not to mix functions from the different
* categories in the same program.
*
* Reading tokens from standard input one at a time,
* and converting to numbers and strings.
* You can use the following methods to read numbers, strings, and booleans
* from standard input:
*
* Each method skips over any input that is whitespace. Then, it reads
* the next token and attempts to convert it into a value of the specified
* type. If it succeeds, it returns that value; otherwise, it
* throws a {@link InputMismatchException}.
*
* Whitespace includes spaces, tabs, and newlines; the full definition
* is inherited from {@link Character#isWhitespace(char)}.
* A token is a maximal sequence of non-whitespace characters.
* The precise rules for describing which tokens can be converted to
* integers and floating-point numbers are inherited from
* Scanner,
* using the locale {@link Locale#US}; the rules
* for floating-point numbers are slightly different
* from those in {@link Double#valueOf(String)},
* but unlikely to be of concern to most programmers.
*
* Reading characters from standard input, one at a time.
* You can use the following two methods to read characters from standard input:
*
* The first method returns true if standard input has more input (including whitespace).
* The second method reads and returns the next character of input on standard
* input (possibly a whitespace character).
*
* As an example, the following code fragment reads characters from standard input,
* one character at a time, and prints it to standard output.
*
* Reading lines from standard input, one at a time.
* You can use the following two methods to read lines from standard input:
*
* The first method returns true if standard input has more input (including whitespace).
* The second method reads and returns the remaining portion of
* the next line of input on standard input (possibly whitespace),
* discarding the trailing line separator.
*
* A line separator is defined to be one of the following strings:
* {@code \n} (Linux), {@code \r} (old Macintosh),
* {@code \r\n} (Windows),
* {@code \u2028}, {@code \u2029}, or {@code \u0085}.
*
* As an example, the following code fragment reads text from standard input,
* one line at a time, and prints it to standard output.
*
* Reading a sequence of values of the same type from standard input.
* You can use the following methods to read a sequence numbers, strings,
* or booleans (all of the same type) from standard input:
*
* The first three methods read of all of remaining token on standard input
* and dconverts the tokens to values of
* the specified type, as in the corresponding
* {@code readDouble}, {@code readInt}, and {@code readString()} methods.
* The {@code readAllLines()} method reads all remaining lines on standard
* input and returns them as an array of strings.
* The {@code readAll()} method reads all remaining input on standard
* input and returns it as a string.
*
* As an example, the following code fragment reads all of the remaining
* tokens from standard input and returns them as an array of strings.
*
* Differences with Scanner.
* {@code StdIn} and {@link Scanner} are both designed to parse
* tokens and convert them to primitive types and strings.
* Some of the main differences are summarized below:
*
* Historical note: {@code StdIn} preceded {@code Scanner}; when
* {@code Scanner} was introduced, this class was reimplemented to use {@code Scanner}.
*
* Using standard input.
* Standard input is fundamental operating system abstraction, on Mac OS X,
* Windows, and Linux.
* The methods in {@code StdIn} are blocking, which means that they
* will wait until you enter input on standard input.
* If your program has a loop that repeats until standard input is empty,
* you must signal that the input is finished.
* To do so, depending on your operating system and IDE,
* use either {@code
* Known bugs.
* Java's UTF-8 encoding does not recognize the optional
* byte-order mask.
* If the input begins with the optional byte-order mask, {@code StdIn}
* will have an extra character {@code \uFEFF} at the beginning.
*
* Reference.
* For additional documentation,
* see Section 1.5 of
* Introduction to Programming in Java: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdIn {
/*** begin: section (1 of 2) of code duplicated from In to StdIn. */
// assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US;
// the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+");
// makes whitespace significant
private static final Pattern EMPTY_PATTERN = Pattern.compile("");
// used to read the entire input
private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A");
/*** end: section (1 of 2) of code duplicated from In to StdIn. */
private static Scanner scanner;
// it doesn't make sense to instantiate this class
private StdIn() { }
//// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static"
/**
* Returns true if standard input is empty (except possibly for whitespace).
* Use this method to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return {@code true} if standard input is empty (except possibly
* for whitespace); {@code false} otherwise
*/
public static boolean isEmpty() {
return !scanner.hasNext();
}
/**
* Returns true if standard input has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return {@code true} if standard input is empty;
* {@code false} otherwise
*/
public static boolean hasNextLine() {
return scanner.hasNextLine();
}
/**
* Returns true if standard input has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return {@code true} if standard input has more input (including whitespace);
* {@code false} otherwise
*/
public static boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
}
/**
* Reads and returns the next line, excluding the line separator if present.
*
* @return the next line, excluding the line separator if present;
* {@code null} if no such line
*/
public static String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
}
/**
* Reads and returns the next character.
*
* @return the next character
* @throws NoSuchElementException if standard input is empty
*/
public static char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
}
/**
* Reads and returns the remainder of the input, as a string.
*
* @return the remainder of the input, as a string
* @throws NoSuchElementException if standard input is empty
*/
public static String readAll() {
if (!scanner.hasNextLine())
return "";
String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
}
/**
* Reads the next token and returns the {@code String}.
*
* @return the next {@code String}
* @throws NoSuchElementException if standard input is empty
*/
public static String readString() {
return scanner.next();
}
/**
* Reads the next token from standard input, parses it as an integer, and returns the integer.
*
* @return the next integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as an {@code int}
*/
public static int readInt() {
return scanner.nextInt();
}
/**
* Reads the next token from standard input, parses it as a double, and returns the double.
*
* @return the next double on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code double}
*/
public static double readDouble() {
return scanner.nextDouble();
}
/**
* Reads the next token from standard input, parses it as a float, and returns the float.
*
* @return the next float on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code float}
*/
public static float readFloat() {
return scanner.nextFloat();
}
/**
* Reads the next token from standard input, parses it as a long integer, and returns the long integer.
*
* @return the next long integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code long}
*/
public static long readLong() {
return scanner.nextLong();
}
/**
* Reads the next token from standard input, parses it as a short integer, and returns the short integer.
*
* @return the next short integer on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code short}
*/
public static short readShort() {
return scanner.nextShort();
}
/**
* Reads the next token from standard input, parses it as a byte, and returns the byte.
*
* @return the next byte on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code byte}
*/
public static byte readByte() {
return scanner.nextByte();
}
/**
* Reads the next token from standard input, parses it as a boolean,
* and returns the boolean.
*
* @return the next boolean on standard input
* @throws NoSuchElementException if standard input is empty
* @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}:
* {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false,
* ignoring case
*/
public static boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
}
/**
* Reads all remaining tokens from standard input and returns them as an array of strings.
*
* @return all remaining tokens on standard input, as an array of strings
*/
public static String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// because trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
// don't include first token if it is leading whitespace
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length - 1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
}
/**
* Reads all remaining lines from standard input and returns them as an array of strings.
* @return all remaining lines on standard input, as an array of strings
*/
public static String[] readAllLines() {
ArrayList
* Getting started.
* To use this class, you must have {@code StdOut.class} in your
* Java classpath. If you used our autoinstaller, you should be all set.
* Otherwise, download
* StdOut.java
* and put a copy in your working directory.
*
* Here is an example program that uses {@code StdOut}:
*
* Differences with System.out.
* The behavior of {@code StdOut} is similar to that of {@link System#out},
* but there are a few subtle differences:
*
* Reference.
* For additional documentation,
* see Section 1.5 of
* Introduction to Programming in Java: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdOut {
// force Unicode UTF-8 encoding; otherwise it's system dependent
private static final String CHARSET_NAME = "UTF-8";
// assume language = English, country = US for consistency with StdIn
private static final Locale LOCALE = Locale.US;
// send output here
private static PrintWriter out;
// this is called before invoking any methods
static {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true);
}
catch (UnsupportedEncodingException e) {
System.out.println(e);
}
}
// don't instantiate
private StdOut() { }
/**
* Closes standard output.
*/
public static void close() {
out.close();
}
/**
* Terminates the current line by printing the line-separator string.
*/
public static void println() {
out.println();
}
/**
* Prints an object to this output stream and then terminates the line.
*
* @param x the object to print
*/
public static void println(Object x) {
out.println(x);
}
/**
* Prints a boolean to standard output and then terminates the line.
*
* @param x the boolean to print
*/
public static void println(boolean x) {
out.println(x);
}
/**
* Prints a character to standard output and then terminates the line.
*
* @param x the character to print
*/
public static void println(char x) {
out.println(x);
}
/**
* Prints a double to standard output and then terminates the line.
*
* @param x the double to print
*/
public static void println(double x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(float x) {
out.println(x);
}
/**
* Prints an integer to standard output and then terminates the line.
*
* @param x the integer to print
*/
public static void println(int x) {
out.println(x);
}
/**
* Prints a long to standard output and then terminates the line.
*
* @param x the long to print
*/
public static void println(long x) {
out.println(x);
}
/**
* Prints a short integer to standard output and then terminates the line.
*
* @param x the short to print
*/
public static void println(short x) {
out.println(x);
}
/**
* Prints a byte to standard output and then terminates the line.
*
* To write binary data, see {@link BinaryStdOut}.
*
* @param x the byte to print
*/
public static void println(byte x) {
out.println(x);
}
/**
* Flushes standard output.
*/
public static void print() {
out.flush();
}
/**
* Prints an object to standard output and flushes standard output.
*
* @param x the object to print
*/
public static void print(Object x) {
out.print(x);
out.flush();
}
/**
* Prints a boolean to standard output and flushes standard output.
*
* @param x the boolean to print
*/
public static void print(boolean x) {
out.print(x);
out.flush();
}
/**
* Prints a character to standard output and flushes standard output.
*
* @param x the character to print
*/
public static void print(char x) {
out.print(x);
out.flush();
}
/**
* Prints a double to standard output and flushes standard output.
*
* @param x the double to print
*/
public static void print(double x) {
out.print(x);
out.flush();
}
/**
* Prints a float to standard output and flushes standard output.
*
* @param x the float to print
*/
public static void print(float x) {
out.print(x);
out.flush();
}
/**
* Prints an integer to standard output and flushes standard output.
*
* @param x the integer to print
*/
public static void print(int x) {
out.print(x);
out.flush();
}
/**
* Prints a long integer to standard output and flushes standard output.
*
* @param x the long integer to print
*/
public static void print(long x) {
out.print(x);
out.flush();
}
/**
* Prints a short integer to standard output and flushes standard output.
*
* @param x the short integer to print
*/
public static void print(short x) {
out.print(x);
out.flush();
}
/**
* Prints a byte to standard output and flushes standard output.
*
* @param x the byte to print
*/
public static void print(byte x) {
out.print(x);
out.flush();
}
/**
* Prints a formatted string to standard output, using the specified format
* string and arguments, and then flushes standard output.
*
*
* @param format the format string
* @param args the arguments accompanying the format string
*/
public static void printf(String format, Object... args) {
out.printf(LOCALE, format, args);
out.flush();
}
/**
* Prints a formatted string to standard output, using the locale and
* the specified format string and arguments; then flushes standard output.
*
* @param locale the locale
* @param format the format string
* @param args the arguments accompanying the format string
*/
public static void printf(Locale locale, String format, Object... args) {
out.printf(locale, format, args);
out.flush();
}
/**
* Unit tests some of the methods in {@code StdOut}.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
// write to stdout
StdOut.println("Test");
StdOut.println(17);
StdOut.println(true);
StdOut.printf("%.6f\n", 1.0/7.0);
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/algs4/StdRandom.java
================================================
/******************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
* Dependencies: StdOut.java
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
******************************************************************************/
package algs4;
import java.util.Random;
/**
* The {@code StdRandom} class provides static methods for generating
* random number from various discrete and continuous distributions,
* including Bernoulli, uniform, Gaussian, exponential, pareto,
* Poisson, and Cauchy. It also provides method for shuffling an
* array or subarray.
*
* For additional documentation,
* see Section 2.2 of
* Introduction to Programming in Java: An Interdisciplinary Approach
* by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// don't instantiate
private StdRandom() { }
/**
* Sets the seed of the pseudorandom number generator.
* This method enables you to produce the same sequence of "random"
* number for each execution of the program.
* Ordinarily, you should call this method at most once per program.
*
* @param s the seed
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Returns the seed of the pseudorandom number generator.
*
* @return the seed
*/
public static long getSeed() {
return seed;
}
/**
* Returns a random real number uniformly in [0, 1).
*
* @return a random real number uniformly in [0, 1)
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Returns a random integer uniformly in [0, n).
*
* @param n number of possible integers
* @return a random integer uniformly between 0 (inclusive) and {@code N} (exclusive)
* @throws IllegalArgumentException if {@code n <= 0}
*/
public static int uniform(int n) {
if (n <= 0) throw new IllegalArgumentException("Parameter N must be positive");
return random.nextInt(n);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Returns a random real number uniformly in [0, 1).
*
* @return a random real number uniformly in [0, 1)
* @deprecated Replaced by {@link #uniform()}.
*/
@Deprecated
public static double random() {
return uniform();
}
/**
* Returns a random integer uniformly in [a, b).
*
* @param a the left endpoint
* @param b the right endpoint
* @return a random integer uniformly in [a, b)
* @throws IllegalArgumentException if {@code b <= a}
* @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE}
*/
public static int uniform(int a, int b) {
if (b <= a) throw new IllegalArgumentException("Invalid range");
if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException("Invalid range");
return a + uniform(b - a);
}
/**
* Returns a random real number uniformly in [a, b).
*
* @param a the left endpoint
* @param b the right endpoint
* @return a random real number uniformly in [a, b)
* @throws IllegalArgumentException unless {@code a < b}
*/
public static double uniform(double a, double b) {
if (!(a < b)) throw new IllegalArgumentException("Invalid range");
return a + uniform() * (b-a);
}
/**
* Returns a random boolean from a Bernoulli distribution with success
* probability p.
*
* @param p the probability of returning {@code true}
* @return {@code true} with probability {@code p} and
* {@code false} with probability {@code p}
* @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0}
*/
public static boolean bernoulli(double p) {
if (!(p >= 0.0 && p <= 1.0))
throw new IllegalArgumentException("Probability must be between 0.0 and 1.0");
return uniform() < p;
}
/**
* Returns a random boolean from a Bernoulli distribution with success
* probability 1/2.
*
* @return {@code true} with probability 1/2 and
* {@code false} with probability 1/2
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Returns a random real number from a standard Gaussian distribution.
*
* @return a random real number from a standard Gaussian distribution
* (mean 0 and standard deviation 1).
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Returns a random real number from a Gaussian distribution with mean μ
* and standard deviation σ.
*
* @param mu the mean
* @param sigma the standard deviation
* @return a real number distributed according to the Gaussian distribution
* with mean {@code mu} and standard deviation {@code sigma}
*/
public static double gaussian(double mu, double sigma) {
return mu + sigma * gaussian();
}
/**
* Returns a random integer from a geometric distribution with success
* probability p.
*
* @param p the parameter of the geometric distribution
* @return a random integer from a geometric distribution with success
* probability {@code p}; or {@code Integer.MAX_VALUE} if
* {@code p} is (nearly) equal to {@code 1.0}.
* @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0}
*/
public static int geometric(double p) {
if (!(p >= 0.0 && p <= 1.0))
throw new IllegalArgumentException("Probability must be between 0.0 and 1.0");
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Returns a random integer from a Poisson distribution with mean λ.
*
* @param lambda the mean of the Poisson distribution
* @return a random integer from a Poisson distribution with mean {@code lambda}
* @throws IllegalArgumentException unless {@code lambda > 0.0} and not infinite
*/
public static int poisson(double lambda) {
if (!(lambda > 0.0))
throw new IllegalArgumentException("Parameter lambda must be positive");
if (Double.isInfinite(lambda))
throw new IllegalArgumentException("Parameter lambda must not be infinite");
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double expLambda = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= expLambda);
return k-1;
}
/**
* Returns a random real number from the standard Pareto distribution.
*
* @return a random real number from the standard Pareto distribution
*/
public static double pareto() {
return pareto(1.0);
}
/**
* Returns a random real number from a Pareto distribution with
* shape parameter α.
*
* @param alpha shape parameter
* @return a random real number from a Pareto distribution with shape
* parameter {@code alpha}
* @throws IllegalArgumentException unless {@code alpha > 0.0}
*/
public static double pareto(double alpha) {
if (!(alpha > 0.0))
throw new IllegalArgumentException("Shape parameter alpha must be positive");
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Returns a random real number from the Cauchy distribution.
*
* @return a random real number from the Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Returns a random integer from the specified discrete distribution.
*
* @param probabilities the probability of occurrence of each integer
* @return a random integer from a discrete distribution:
* {@code i} with probability {@code probabilities[i]}
* @throws NullPointerException if {@code probabilities} is {@code null}
* @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to {@code 1.0}
* @throws IllegalArgumentException unless {@code probabilities[i] >= 0.0} for each index {@code i}
*/
public static int discrete(double[] probabilities) {
if (probabilities == null) throw new NullPointerException("argument array is null");
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < probabilities.length; i++) {
if (!(probabilities[i] >= 0.0))
throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + probabilities[i]);
sum += probabilities[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum);
// the for loop may not return a value when both r is (nearly) 1.0 and when the
// cumulative sum is less than 1.0 (as a result of floating-point roundoff error)
while (true) {
double r = uniform();
sum = 0.0;
for (int i = 0; i < probabilities.length; i++) {
sum = sum + probabilities[i];
if (sum > r) return i;
}
}
}
/**
* Returns a random integer from the specified discrete distribution.
*
* @param frequencies the frequency of occurrence of each integer
* @return a random integer from a discrete distribution:
* {@code i} with probability proportional to {@code frequencies[i]}
* @throws NullPointerException if {@code frequencies} is {@code null}
* @throws IllegalArgumentException if all array entries are {@code 0}
* @throws IllegalArgumentException if {@code frequencies[i]} is negative for any index {@code i}
* @throws IllegalArgumentException if sum of frequencies exceeds {@code Integer.MAX_VALUE} (231 - 1)
*/
public static int discrete(int[] frequencies) {
if (frequencies == null) throw new NullPointerException("argument array is null");
long sum = 0;
for (int i = 0; i < frequencies.length; i++) {
if (frequencies[i] < 0)
throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + frequencies[i]);
sum += frequencies[i];
}
if (sum == 0)
throw new IllegalArgumentException("at least one array entry must be positive");
if (sum >= Integer.MAX_VALUE)
throw new IllegalArgumentException("sum of frequencies overflows an int");
// pick index i with probabilitity proportional to frequency
double r = uniform((int) sum);
sum = 0;
for (int i = 0; i < frequencies.length; i++) {
sum += frequencies[i];
if (sum > r) return i;
}
// can't reach here
assert false;
return -1;
}
/**
* Returns a random real number from an exponential distribution
* with rate λ.
*
* @param lambda the rate of the exponential distribution
* @return a random real number from an exponential distribution with
* rate {@code lambda}
* @throws IllegalArgumentException unless {@code lambda > 0.0}
*/
public static double exp(double lambda) {
if (!(lambda > 0.0))
throw new IllegalArgumentException("Rate lambda must be positive");
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearranges the elements of the specified array in uniformly random order.
*
* @param a the array to shuffle
* @throws NullPointerException if {@code a} is {@code null}
*/
public static void shuffle(Object[] a) {
if (a == null) throw new NullPointerException("argument array is null");
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + uniform(n-i); // between i and n-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearranges the elements of the specified array in uniformly random order.
*
* @param a the array to shuffle
* @throws NullPointerException if {@code a} is {@code null}
*/
public static void shuffle(double[] a) {
if (a == null) throw new NullPointerException("argument array is null");
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + uniform(n-i); // between i and n-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearranges the elements of the specified array in uniformly random order.
*
* @param a the array to shuffle
* @throws NullPointerException if {@code a} is {@code null}
*/
public static void shuffle(int[] a) {
if (a == null) throw new NullPointerException("argument array is null");
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + uniform(n-i); // between i and n-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearranges the elements of the specified subarray in uniformly random order.
*
* @param a the array to shuffle
* @param lo the left endpoint (inclusive)
* @param hi the right endpoint (inclusive)
* @throws NullPointerException if {@code a} is {@code null}
* @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}
*
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (a == null) throw new NullPointerException("argument array is null");
if (lo < 0 || lo > hi || hi >= a.length) {
throw new IndexOutOfBoundsException("Illegal subarray range");
}
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearranges the elements of the specified subarray in uniformly random order.
*
* @param a the array to shuffle
* @param lo the left endpoint (inclusive)
* @param hi the right endpoint (inclusive)
* @throws NullPointerException if {@code a} is {@code null}
* @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}
*/
public static void shuffle(double[] a, int lo, int hi) {
if (a == null) throw new NullPointerException("argument array is null");
if (lo < 0 || lo > hi || hi >= a.length) {
throw new IndexOutOfBoundsException("Illegal subarray range");
}
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearranges the elements of the specified subarray in uniformly random order.
*
* @param a the array to shuffle
* @param lo the left endpoint (inclusive)
* @param hi the right endpoint (inclusive)
* @throws NullPointerException if {@code a} is {@code null}
* @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)}
*/
public static void shuffle(int[] a, int lo, int hi) {
if (a == null) throw new NullPointerException("argument array is null");
if (lo < 0 || lo > hi || hi >= a.length) {
throw new IndexOutOfBoundsException("Illegal subarray range");
}
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Unit test.
*
* @param args the command-line arguments
*/
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] probabilities = { 0.5, 0.3, 0.1, 0.1 };
int[] frequencies = { 5, 3, 1, 1 };
String[] a = "A B C D E F G".split(" ");
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < n; i++) {
StdOut.printf("%2d ", uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b ", bernoulli(0.5));
StdOut.printf("%7.5f ", gaussian(9.0, 0.2));
StdOut.printf("%1d ", discrete(probabilities));
StdOut.printf("%1d ", discrete(frequencies));
StdRandom.shuffle(a);
for (String s : a)
StdOut.print(s);
StdOut.println();
}
}
}
/******************************************************************************
* Copyright 2002-2016, Robert Sedgewick and Kevin Wayne.
*
* This file is part of algs4.jar, which accompanies the textbook
*
* Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
* Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
* http://algs4.cs.princeton.edu
*
*
* algs4.jar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* algs4.jar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with algs4.jar. If not, see http://www.gnu.org/licenses.
******************************************************************************/
================================================
FILE: code/chapter1_1_Programming_Model/BinarySearch.java
================================================
package chapter1_1_Programming_Model;
import java.util.Arrays;
import algs4.*;
/**
* 二分查找
* @author huang
*/
public class BinarySearch {
public static int rank(int key, int[] a) {
// 数组必须有序
int lo = 0;
int hi = a.length - 1;
while(lo <= hi) {
int mid = lo + (hi - lo) / 2;
if(key < a[mid])
hi = mid - 1;
else if(key > a[mid])
lo = mid + 1;
else
return mid;
}
return -1;
}
public static void main(String[] args) {
int[] whitelist = In.readInts(args[0]);
Arrays.sort(whitelist);
while(!StdIn.isEmpty()){
int key = StdIn.readInt();
if(rank(key, whitelist) < 0)
StdOut.println(key);
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/BouncingBall.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdDraw;
public class BouncingBall {
public static void main(String[] args) {
// set the scale of the coordinate system
StdDraw.setXscale(-1.0, 1.0);
StdDraw.setYscale(-1.0, 1.0);
StdDraw.enableDoubleBuffering();
// initial values
double rx = .480, ry = .860; // position
double vx = .015, vy = .023; // velocity
double radius = .05; // radius
// main animation loop
while(true) {
// bounce off wall according to law of elastic collision
if(Math.abs(rx + vx) > 1.0 - radius)
vx = -vx;
if(Math.abs(ry + vy) > 1.0 - radius)
vy = -vy;
// update position
rx = rx + vx;
ry = ry + vy;
// clear the background
StdDraw.setPenColor(StdDraw.GRAY);
StdDraw.filledSquare(0, 0, 1.0);
// draw ball on the screen
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.filledCircle(rx, ry, radius);
// display and pause for 20 ms
StdDraw.show();
StdDraw.pause(20);
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex1.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex1 {
public static void main(String[] args) {
StdOut.println((0 + 15) / 2);
StdOut.println(2.0e-6 * 100000000.1);
StdOut.println(true && false || true && true);
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex10.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex10 {
public static void main(String[] args) {
int[] a = new int[10];
for(int i = 0; i < 10; i++)
a[i] = i*i;
for(int i = 9; i >= 0; i--)
StdOut.printf("%d ", a[i]);
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex11.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
import algs4.StdRandom;
public class Ex11 {
public static void main(String[] args) {
boolean[][] arr = new boolean[7][6];
for(int i = 0; i < 7; i++) {
for(int j = 0; j < 6; j++) {
double num = StdRandom.uniform();
if(num > 0.5)
arr[i][j] = true;
else
arr[i][j] = false;
}
}
printBoolArr(arr);
}
public static void printBoolArr (boolean[][] arr) {
StdOut.print(' ');
for (int i = 0; i < arr[0].length; i++) {
StdOut.print(i);
}
StdOut.println();
for (int i = 0; i < arr.length; i++) {
StdOut.print(i);
for (int j = 0; j < arr[i].length; j++) {
StdOut.print(arr[i][j] ? '*' : ' ');
}
StdOut.println();
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex13.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
import algs4.StdRandom;
public class Ex13 {
public static void main(String[] args) {
int M = 3, N = 4;
int[][] arr = new int[M][N];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr[0].length; j++)
arr[i][j] = StdRandom.uniform(20);
StdOut.println("oldArr: ");
printArr(arr);
StdOut.println("newArr: ");
printArr(arrReverse(arr));
}
public static int[][] arrReverse(int[][] arr) {
int[][] newArr = new int[arr[0].length][arr.length];
for(int i = 0; i < newArr.length; i++)
for(int j = 0; j < newArr[0].length; j++)
newArr[i][j] = arr[j][i];
return newArr;
}
public static void printArr(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[0].length; j++) {
StdOut.printf("%d ",arr[i][j]);
}
StdOut.println();
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex14.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex14 {
public static void main(String[] args) {
StdOut.print(lg(8));
}
public static int lg(int N) {
int i = 0;
while(n2(i) <= N)
i++;
return i-1;
}
public static int n2(int n) {
int result = 1;
for(int i = 0; i < n; i++)
result *= 2;
return result;
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex15.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex15 {
public static void main(String[] args) {
int[] arr = {0, 1, 1, 1};
int[] timesArr = histogram(arr, 2);
for(int j = 0; j < timesArr.length; j++) {
StdOut.printf("%d ", timesArr[j]);
}
}
public static int[] histogram(int[] a, int M) {
int[] arr = new int[M];
for(int i = 0; i < M; i++){
int times = 0;
for(int j = 0; j < a.length; j++){
if(a[j] == i)
times++;
}
arr[i] = times;
}
return arr;
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex19.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex19 {
static final int M = 100;
static long[] arr = new long[M];
public static long F(int N) {
if(N == 0)
arr[N] = 0;
else if(N == 1)
arr[N] = 1;
else
arr[N] = arr[N - 1] + arr[N - 2];
return arr[N];
}
public static void main(String[] args) {
for(int N = 0; N < M; N++)
StdOut.println(N + " " + F(N));
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex2.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex2 {
public static void main(String[] args) {
StdOut.println((1 + 2.236) / 2);
StdOut.println(1 + 2 + 3 + 4.0);
StdOut.println(4.1 >= 4);
StdOut.println(1 + 2 + "3");
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex20.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex20 {
public static void main(String[] args) {
StdOut.print(ln10(9));
}
public static double ln10(int N) {
if(N == 1)
return Math.log10(1);
return Math.log10(N) + ln10(N - 1);
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex3.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdIn;
import algs4.StdOut;
public class Ex3 {
public static void main(String[] args) {
int a = StdIn.readInt();
int b = StdIn.readInt();
int c = StdIn.readInt();
if(a == b && a == c) {
StdOut.println("equal");
} else {
StdOut.println("not equal");
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex30.java
================================================
package chapter1_1_Programming_Model;
import algs4.StdOut;
public class Ex30 {
public static void main(String[] args) {
int N = 10;
boolean[][] arr = new boolean [N][N];
setArrBoolean(arr);
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length; j++) {
StdOut.printf("%b ", arr[i][j]);
}
StdOut.println();
}
}
public static void setArrBoolean(boolean[][] arr) {
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length; j++) {
arr[i][j] = true;
for(int k = 2; k <= i; k++) {
if((i % k == 0) && (j % k == 0)) {
arr[i][j] = false;
}
}
}
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex31.java
================================================
package chapter1_1_Programming_Model;
import java.awt.Color;
import algs4.StdDraw;
import algs4.StdRandom;
public class Ex31 {
static class Point {
double x, y;
public Point(double x, double y) {
super();
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
double p = Double.parseDouble(args[1]);
if(p < 0 || p > 1) {
System.out.println("p is not valid!");
return;
}
Point[] points = new Point[N];
double angle = 360.0 / N;
StdDraw.circle(.5, .5, .5);
StdDraw.setPenRadius(.05);
for(int i = 0; i < N; i++) {
points[i] = new Point(.5 + .5 * Math.cos(angle * i * Math.PI / 180),
.5 + .5 * Math.sin(angle * i * Math.PI / 180));
StdDraw.point(points[i].x, points[i].y);
}
StdDraw.setPenRadius(.01);
StdDraw.setPenColor(Color.GRAY);
for(int i = 0; i < N - 1; i++) {
for(int j = i + 1; j < N; j++) {
if(StdRandom.bernoulli(p)) {
StdDraw.line(points[i].x, points[i].y, points[j].x, points[j].y);
}
}
}
}
}
================================================
FILE: code/chapter1_1_Programming_Model/Ex32.java
================================================
package chapter1_1_Programming_Model;
import java.util.ArrayList;
import java.util.Scanner;
import algs4.StdDraw;
public class Ex32 {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
ArrayList
* public class TestStdDraw {
* public static void main(String[] args) {
* StdDraw.setPenRadius(0.05);
* StdDraw.setPenColor(StdDraw.BLUE);
* StdDraw.point(0.5, 0.5);
* StdDraw.setPenColor(StdDraw.MAGENTA);
* StdDraw.line(0.2, 0.2, 0.8, 0.2);
* }
* }
*
* If you compile and execute the program, you should see a window
* appear with a thick magenta line and a blue point.
* This program illustrates the two main types of methods in standard
* drawing—methods that draw geometric shapes and methods that
* control drawing parameters.
* The methods {@code StdDraw.line()} and {@code StdDraw.point()}
* draw lines and points; the methods {@code StdDraw.setPenRadius()}
* and {@code StdDraw.setPenColor()} control the line thickness and color.
*
*
*
*
*
*
*
*
*
*
*
* double[] x = { 0.1, 0.2, 0.3, 0.2 };
* double[] y = { 0.2, 0.3, 0.2, 0.1 };
* StdDraw.filledPolygon(x, y);
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* Font font = new Font("Arial", Font.BOLD, 60);
* StdDraw.setFont(font);
* StdDraw.text(0.5, 0.5, "Hello, World");
*
*
*
*
*
*
*
*
*
*
*
*
* StdDraw.setScale(-2, +2);
* StdDraw.enableDoubleBuffering();
*
* for (double t = 0.0; true; t += 0.02) {
* double x = Math.sin(t);
* double y = Math.cos(t);
* StdDraw.clear();
* StdDraw.filledCircle(x, y, 0.05);
* StdDraw.filledCircle(-x, -y, 0.05);
* StdDraw.show();
* StdDraw.pause(20);
* }
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
* while (StdIn.hasNextChar()) {
* char c = StdIn.readChar();
* StdOut.print(c);
* }
*
*
*
*
* while (StdIn.hasNextLine()) {
* String line = StdIn.readLine();
* StdOut.println(line);
* }
*
*
*
*
* String[] words = StdIn.readAllStrings();
*
*
*
*
* public class TestStdOut {
* public static void main(String[] args) {
* int a = 17;
* int b = 23;
* int sum = a + b;
* StdOut.println("Hello, World");
* StdOut.printf("%d + %d = %d\n", a, b, sum);
* }
* }
*
*
*
*