├── .gitignore ├── pom.xml ├── src └── main │ └── java │ └── edu │ └── princeton │ └── cs │ └── algs4 │ ├── DrawListener.java │ ├── Average.java │ ├── Cat.java │ ├── DeDup.java │ ├── GREP.java │ ├── DoublingTest.java │ ├── RandomSeq.java │ ├── Whitelist.java │ ├── PictureDump.java │ ├── DoublingRatio.java │ ├── Count.java │ ├── BinaryDump.java │ ├── WhiteFilter.java │ ├── BlackFilter.java │ ├── TopM.java │ ├── FileIndex.java │ ├── HexDump.java │ ├── StaticSETofInts.java │ ├── Multiway.java │ ├── Genome.java │ ├── Stopwatch.java │ ├── DirectedEdge.java │ ├── Arbitrage.java │ ├── StopwatchCPU.java │ ├── LookupIndex.java │ ├── LongestRepeatedSubstring.java │ ├── LookupCSV.java │ ├── FrequencyCounter.java │ ├── Heap.java │ ├── CPM.java │ ├── RunLength.java │ ├── KWIK.java │ ├── Counter.java │ ├── BinarySearch.java │ ├── ThreeSum.java │ ├── ResizingArrayBag.java │ ├── Edge.java │ ├── InsertionX.java │ ├── MergeBU.java │ ├── Knuth.java │ ├── Quick3way.java │ ├── Accumulator.java │ ├── DepthFirstSearch.java │ ├── LongestCommonSubstring.java │ ├── Shell.java │ ├── LinkedBag.java │ └── LZW.java ├── README.md └── README-MAVEN.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # OS generated files 2 | .DS_Store 3 | Thumbs.db 4 | *~ 5 | # Thumbnails 6 | ._* 7 | 8 | ### Java ### 9 | *.class 10 | 11 | # Package Files # 12 | *.jar 13 | *.war 14 | *.ear 15 | 16 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 17 | hs_err_pid* 18 | 19 | # Gradle Files 20 | .gradle 21 | .m2 22 | 23 | # Build output directies 24 | build/ 25 | /target 26 | 27 | ### Eclipse project file ### 28 | .metadata 29 | .classpath 30 | .project 31 | .settings/ 32 | bin/ 33 | tmp/ 34 | *.tmp 35 | *.bak 36 | *.swp 37 | *~.nib 38 | .loadpath 39 | .launch 40 | .cproject 41 | 42 | 43 | # IntelliJ project files 44 | *.iml 45 | *.iws 46 | *.ipr 47 | .idea 48 | out 49 | test-output 50 | 51 | .idea_modules/ 52 | 53 | # JIRA plugin 54 | atlassian-ide-plugin.xml 55 | 56 | # files intended to be ignored 57 | *IGNORE 58 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | edu.princeton.cs 5 | algs4 6 | jar 7 | 1.0.0.0 8 | algs4 9 | 10 | 11 | GNU GENERAL PUBLIC LICENSE 12 | http://www.gnu.org/licenses/gpl-3.0.en.html 13 | 14 | 15 | 16 | 17 | kevin 18 | Kevin Wayne 19 | wayne@CS.Princeton.EDU 20 | https://www.cs.princeton.edu/~wayne/contact/ 21 | Princeton University 22 | https://www.cs.princeton.edu 23 | 24 | author 25 | developer 26 | 27 | UTC/GMT -4:00 hours 28 | 29 | https://www.cs.princeton.edu/~wayne/contact/KevinWayne.jpg 30 | 31 | 32 | 33 | robert 34 | Robert Sedgewick 35 | 36 | author 37 | 38 | 39 | 40 | 41 | github.com 42 | https://github.com/kevin-wayne/algs4/issues 43 | 44 | 45 | 46 | main-build 47 | 48 | true 49 | 50 | 51 | UTF-8 52 | 1.8 53 | 54 | 55 | 56 | 57 | org.apache.maven.plugins 58 | maven-compiler-plugin 59 | 3.3 60 | 61 | ${java.version} 62 | ${java.version} 63 | 64 | 65 | 66 | org.apache.maven.plugins 67 | maven-source-plugin 68 | 3.0.1 69 | 70 | 71 | attach-sources 72 | 73 | jar 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DrawListener.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DrawListener.java 3 | * Execution: none 4 | * Dependencies: none 5 | * 6 | * Interface that accompanies Draw.java. 7 | ******************************************************************************/ 8 | 9 | package edu.princeton.cs.algs4; 10 | 11 | public interface DrawListener { 12 | 13 | /** 14 | * Invoked when the mouse has been pressed. 15 | * 16 | * @param x the x-coordinate of the mouse 17 | * @param y the y-coordinate of the mouse 18 | */ 19 | void mousePressed(double x, double y); 20 | 21 | /** 22 | * Invoked when the mouse has been dragged. 23 | * 24 | * @param x the x-coordinate of the mouse 25 | * @param y the y-coordinate of the mouse 26 | */ 27 | void mouseDragged(double x, double y); 28 | 29 | /** 30 | * Invoked when the mouse has been released. 31 | * 32 | * @param x the x-coordinate of the mouse 33 | * @param y the y-coordinate of the mouse 34 | */ 35 | void mouseReleased(double x, double y); 36 | 37 | /** 38 | * Invoked when a key has been typed. 39 | * 40 | * @param c the character typed 41 | */ 42 | void keyTyped(char c); 43 | 44 | /** 45 | * Invoked when a key has been pressed. 46 | * 47 | * @param keycode the key combination pressed 48 | */ 49 | void keyPressed(int keycode); 50 | 51 | /** 52 | * Invoked when a key has been released. 53 | * 54 | * @param keycode the key combination released 55 | */ 56 | void keyReleased(int keycode); 57 | } 58 | 59 | /****************************************************************************** 60 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 61 | * 62 | * This file is part of algs4.jar, which accompanies the textbook 63 | * 64 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 65 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 66 | * http://algs4.cs.princeton.edu 67 | * 68 | * 69 | * algs4.jar is free software: you can redistribute it and/or modify 70 | * it under the terms of the GNU General Public License as published by 71 | * the Free Software Foundation, either version 3 of the License, or 72 | * (at your option) any later version. 73 | * 74 | * algs4.jar is distributed in the hope that it will be useful, 75 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 76 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 77 | * GNU General Public License for more details. 78 | * 79 | * You should have received a copy of the GNU General Public License 80 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 81 | ******************************************************************************/ 82 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Average.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Average.java 3 | * Execution: java Average < data.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * Reads in a sequence of real numbers, and computes their average. 7 | * 8 | * % java Average 9 | * 10.0 5.0 6.0 10 | * 3.0 7.0 32.0 11 | * [Ctrl-d] 12 | * Average is 10.5 13 | * 14 | * Note [Ctrl-d] signifies the end of file on Unix. 15 | * On windows use [Ctrl-z]. 16 | * 17 | ******************************************************************************/ 18 | 19 | package edu.princeton.cs.algs4; 20 | 21 | /** 22 | * The {@code Average} class provides a client for reading in a sequence 23 | * of real numbers and printing out their average. 24 | *

25 | * For additional documentation, see Section 1.1 of 26 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class Average { 32 | 33 | // this class should not be instantiated 34 | private Average() { } 35 | 36 | /** 37 | * Reads in a sequence of real numbers from standard input and prints 38 | * out their average to standard output. 39 | * 40 | * @param args the command-line arguments 41 | */ 42 | public static void main(String[] args) { 43 | int count = 0; // number input values 44 | double sum = 0.0; // sum of input values 45 | 46 | // read data and compute statistics 47 | while (!StdIn.isEmpty()) { 48 | double value = StdIn.readDouble(); 49 | sum += value; 50 | count++; 51 | } 52 | 53 | // compute the average 54 | double average = sum / count; 55 | 56 | // print results 57 | StdOut.println("Average is " + average); 58 | } 59 | } 60 | 61 | /****************************************************************************** 62 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 63 | * 64 | * This file is part of algs4.jar, which accompanies the textbook 65 | * 66 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 67 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 68 | * http://algs4.cs.princeton.edu 69 | * 70 | * 71 | * algs4.jar is free software: you can redistribute it and/or modify 72 | * it under the terms of the GNU General Public License as published by 73 | * the Free Software Foundation, either version 3 of the License, or 74 | * (at your option) any later version. 75 | * 76 | * algs4.jar is distributed in the hope that it will be useful, 77 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 78 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 79 | * GNU General Public License for more details. 80 | * 81 | * You should have received a copy of the GNU General Public License 82 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 83 | ******************************************************************************/ 84 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Cat.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Cat.java 3 | * Execution: java Cat input0.txt input1.txt ... output.txt 4 | * Dependencies: In.java Out.java 5 | * Data files: https://algs4.cs.princeton.edu/11model/in1.txt 6 | * https://algs4.cs.princeton.edu/11model/in2.txt 7 | * 8 | * Reads in text files specified as the first command-line 9 | * arguments, concatenates them, and writes the result to 10 | * filename specified as the last command-line arguments. 11 | * 12 | * % more in1.txt 13 | * This is 14 | * 15 | * % more in2.txt 16 | * a tiny 17 | * test. 18 | * 19 | * % java Cat in1.txt in2.txt out.txt 20 | * 21 | * % more out.txt 22 | * This is 23 | * a tiny 24 | * test. 25 | * 26 | ******************************************************************************/ 27 | 28 | package edu.princeton.cs.algs4; 29 | 30 | /** 31 | * The {@code Cat} class provides a client for concatenating the results 32 | * of several text files. 33 | *

34 | * For additional documentation, see Section 1.1 of 35 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 36 | * 37 | * @author Robert Sedgewick 38 | * @author Kevin Wayne 39 | */ 40 | public class Cat { 41 | 42 | // this class should not be instantiated 43 | private Cat() { } 44 | 45 | /** 46 | * Reads in a sequence of text files specified as the first command-line 47 | * arguments, concatenates them, and writes the results to the file 48 | * specified as the last command-line argument. 49 | * 50 | * @param args the command-line arguments 51 | */ 52 | public static void main(String[] args) { 53 | Out out = new Out(args[args.length - 1]); 54 | for (int i = 0; i < args.length - 1; i++) { 55 | In in = new In(args[i]); 56 | String s = in.readAll(); 57 | out.println(s); 58 | in.close(); 59 | } 60 | out.close(); 61 | } 62 | 63 | } 64 | 65 | /****************************************************************************** 66 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 67 | * 68 | * This file is part of algs4.jar, which accompanies the textbook 69 | * 70 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 71 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 72 | * http://algs4.cs.princeton.edu 73 | * 74 | * 75 | * algs4.jar is free software: you can redistribute it and/or modify 76 | * it under the terms of the GNU General Public License as published by 77 | * the Free Software Foundation, either version 3 of the License, or 78 | * (at your option) any later version. 79 | * 80 | * algs4.jar is distributed in the hope that it will be useful, 81 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 82 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 83 | * GNU General Public License for more details. 84 | * 85 | * You should have received a copy of the GNU General Public License 86 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 87 | ******************************************************************************/ 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | 3 | Algorithms 4/e textbook 4 | This public repository 5 | contains the Java source code 6 | for the algorithms and clients in the textbook 7 | Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 8 | This is the official version—it is actively maintained and updated by the authors. 9 | The programs are organized in the package edu.princeton.cs.algs4. 10 | If you need only the class files (and not the source code), you can use 11 | algs4.jar instead. 12 | 13 |
14 | 15 | ## Design goals 16 | 17 | Our original goal was to cover the 50 algorithms that every programmer should know. 18 | We use the word programmer to refer to anyone engaged in trying to accomplish 19 | something with the help of a computer, including scientists, engineers, and applications 20 | developers, not to mention college students in science, engineering, and computer science. 21 | The code is optimized for clarity, portability, and efficiency. While some of our 22 | implementations are as fast as (or faster than) their counterparts in java.util, 23 | our main goal is to express the core algorithmic ideas in an elegant and simple manner. 24 | While we embrace some advanced Java features (such as generics and iterators), 25 | we avoid those that interfere with the exposition (such as inheritance and concurrency). 26 | 27 | ## Build managers 28 | 29 | This repository is intended for use with either the Maven 30 | or Gradle build managers. 31 | It can be run from either the command line or integrated into 32 | Eclipse, NetBeans, and IntelliJ. 33 | You can also access it via Bintray. 34 | 35 | ## Coursera Algorithms, Part I and II students 36 | 37 | Feel free to use this public repository to develop solutions to the programming assignments. 38 | However, please do not store solutions to programming assignments in public repositories. 39 | 40 | 41 | ## Copyright 42 | 43 | Copyright © 2000–2019 by Robert Sedgewick and Kevin Wayne. 44 | 45 | ## License 46 | 47 | This code is released under GPLv3. 48 | 49 | ## Contribute to this repository 50 | 51 | This wishlist.txt 52 | contains a list of algorithms and data structures that we would 53 | like to add to the repository. Indeed, several of the algorithms and 54 | data structures in this repository were contributed by others. If interested, please 55 | follow the same style as the code in the repository and thoroughly test your 56 | code before contacting us. 57 | 58 | ## Support for other programming languages 59 | 60 | Some of the code in this repository has been translated to other languages: 61 |

65 | 66 | 67 | ## Credits 68 | 69 | Thanks to Peter Korgan for Maven and Gradle support. 70 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DeDup.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DeDup.java 3 | * Execution: java DeDup < input.txt 4 | * Dependencies: SET StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * 7 | * Read in a list of words from standard input and print out 8 | * each word, removing any duplicates. 9 | * 10 | * % more tinyTale.txt 11 | * it was the best of times it was the worst of times 12 | * it was the age of wisdom it was the age of foolishness 13 | * it was the epoch of belief it was the epoch of incredulity 14 | * it was the season of light it was the season of darkness 15 | * it was the spring of hope it was the winter of despair 16 | * 17 | * % java DeDup < tinyTale.txt 18 | * it 19 | * was 20 | * the 21 | * best 22 | * of 23 | * times 24 | * worst 25 | * age 26 | * wisdom 27 | * ... 28 | * winter 29 | * despair 30 | * 31 | ******************************************************************************/ 32 | 33 | package edu.princeton.cs.algs4; 34 | 35 | /** 36 | * The {@code DeDup} class provides a client for reading in a sequence of 37 | * words from standard input and printing each word, removing any duplicates. 38 | * It is useful as a test client for various symbol table implementations. 39 | *

40 | * For additional documentation, see Section 3.5 of 41 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 42 | * 43 | * @author Robert Sedgewick 44 | * @author Kevin Wayne 45 | */ 46 | public class DeDup { 47 | 48 | // Do not instantiate. 49 | private DeDup() { } 50 | 51 | public static void main(String[] args) { 52 | SET set = new SET(); 53 | 54 | // read in strings and add to set 55 | while (!StdIn.isEmpty()) { 56 | String key = StdIn.readString(); 57 | if (!set.contains(key)) { 58 | set.add(key); 59 | StdOut.println(key); 60 | } 61 | } 62 | } 63 | } 64 | 65 | /****************************************************************************** 66 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 67 | * 68 | * This file is part of algs4.jar, which accompanies the textbook 69 | * 70 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 71 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 72 | * http://algs4.cs.princeton.edu 73 | * 74 | * 75 | * algs4.jar is free software: you can redistribute it and/or modify 76 | * it under the terms of the GNU General Public License as published by 77 | * the Free Software Foundation, either version 3 of the License, or 78 | * (at your option) any later version. 79 | * 80 | * algs4.jar is distributed in the hope that it will be useful, 81 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 82 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 83 | * GNU General Public License for more details. 84 | * 85 | * You should have received a copy of the GNU General Public License 86 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 87 | ******************************************************************************/ 88 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/GREP.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac GREP.java 3 | * Execution: java GREP regexp < input.txt 4 | * Dependencies: NFA.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/54regexp/tinyL.txt 6 | * 7 | * This program takes an RE as a command-line argument and prints 8 | * the lines from standard input having some substring that 9 | * is in the language described by the RE. 10 | * 11 | * % more tinyL.txt 12 | * AC 13 | * AD 14 | * AAA 15 | * ABD 16 | * ADD 17 | * BCD 18 | * ABCCBD 19 | * BABAAA 20 | * BABBAAA 21 | * 22 | * % java GREP "(A*B|AC)D" < tinyL.txt 23 | * ABD 24 | * ABCCBD 25 | * 26 | ******************************************************************************/ 27 | 28 | package edu.princeton.cs.algs4; 29 | 30 | /** 31 | * The {@code GREP} class provides a client for reading in a sequence of 32 | * lines from standard input and printing to standard output those lines 33 | * that contain a substring matching a specified regular expression. 34 | *

35 | * For additional documentation, see Section 3.1 of 36 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | public class GREP { 42 | 43 | // do not instantiate 44 | private GREP() { } 45 | 46 | /** 47 | * Interprets the command-line argument as a regular expression 48 | * (supporting closure, binary or, parentheses, and wildcard) 49 | * reads in lines from standard input; writes to standard output 50 | * those lines that contain a substring matching the regular 51 | * expression. 52 | * 53 | * @param args the command-line arguments 54 | */ 55 | public static void main(String[] args) { 56 | String regexp = "(.*" + args[0] + ".*)"; 57 | NFA nfa = new NFA(regexp); 58 | while (StdIn.hasNextLine()) { 59 | String line = StdIn.readLine(); 60 | if (nfa.recognizes(line)) { 61 | StdOut.println(line); 62 | } 63 | } 64 | } 65 | } 66 | 67 | /****************************************************************************** 68 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 69 | * 70 | * This file is part of algs4.jar, which accompanies the textbook 71 | * 72 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 73 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 74 | * http://algs4.cs.princeton.edu 75 | * 76 | * 77 | * algs4.jar is free software: you can redistribute it and/or modify 78 | * it under the terms of the GNU General Public License as published by 79 | * the Free Software Foundation, either version 3 of the License, or 80 | * (at your option) any later version. 81 | * 82 | * algs4.jar is distributed in the hope that it will be useful, 83 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 84 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 85 | * GNU General Public License for more details. 86 | * 87 | * You should have received a copy of the GNU General Public License 88 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 89 | ******************************************************************************/ 90 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DoublingTest.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DoublingTest.java 3 | * Execution: java DoublingTest 4 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 5 | * 6 | * % java DoublingTest 7 | * 250 0.0 8 | * 500 0.0 9 | * 1000 0.1 10 | * 2000 0.6 11 | * 4000 4.5 12 | * 8000 35.7 13 | * ... 14 | * 15 | ******************************************************************************/ 16 | 17 | package edu.princeton.cs.algs4; 18 | 19 | /** 20 | * The {@code DoublingTest} class provides a client for measuring 21 | * the running time of a method using a doubling test. 22 | *

23 | * For additional documentation, see Section 1.4 24 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 25 | * 26 | * @author Robert Sedgewick 27 | * @author Kevin Wayne 28 | */ 29 | public class DoublingTest { 30 | private static final int MAXIMUM_INTEGER = 1000000; 31 | 32 | // This class should not be instantiated. 33 | private DoublingTest() { } 34 | 35 | /** 36 | * Returns the amount of time to call {@code ThreeSum.count()} with n 37 | * random 6-digit integers. 38 | * @param n the number of integers 39 | * @return amount of time (in seconds) to call {@code ThreeSum.count()} 40 | * with n random 6-digit integers 41 | */ 42 | public static double timeTrial(int n) { 43 | int[] a = new int[n]; 44 | for (int i = 0; i < n; i++) { 45 | a[i] = StdRandom.uniform(-MAXIMUM_INTEGER, MAXIMUM_INTEGER); 46 | } 47 | Stopwatch timer = new Stopwatch(); 48 | ThreeSum.count(a); 49 | return timer.elapsedTime(); 50 | } 51 | 52 | /** 53 | * Prints table of running times to call {@code ThreeSum.count()} 54 | * for arrays of size 250, 500, 1000, 2000, and so forth. 55 | * 56 | * @param args the command-line arguments 57 | */ 58 | public static void main(String[] args) { 59 | for (int n = 250; true; n += n) { 60 | double time = timeTrial(n); 61 | StdOut.printf("%7d %7.1f\n", n, time); 62 | } 63 | } 64 | } 65 | 66 | /****************************************************************************** 67 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 68 | * 69 | * This file is part of algs4.jar, which accompanies the textbook 70 | * 71 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 72 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 73 | * http://algs4.cs.princeton.edu 74 | * 75 | * 76 | * algs4.jar is free software: you can redistribute it and/or modify 77 | * it under the terms of the GNU General Public License as published by 78 | * the Free Software Foundation, either version 3 of the License, or 79 | * (at your option) any later version. 80 | * 81 | * algs4.jar is distributed in the hope that it will be useful, 82 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 83 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 84 | * GNU General Public License for more details. 85 | * 86 | * You should have received a copy of the GNU General Public License 87 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 88 | ******************************************************************************/ 89 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/RandomSeq.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac RandomSeq.java 3 | * Execution: java RandomSeq n lo hi 4 | * Dependencies: StdOut.java 5 | * 6 | * Prints N numbers between lo and hi. 7 | * 8 | * % java RandomSeq 5 100.0 200.0 9 | * 123.43 10 | * 153.13 11 | * 144.38 12 | * 155.18 13 | * 104.02 14 | * 15 | ******************************************************************************/ 16 | 17 | package edu.princeton.cs.algs4; 18 | 19 | /** 20 | * The {@code RandomSeq} class is a client that prints out a pseudorandom 21 | * sequence of real numbers in a given range. 22 | *

23 | * For additional documentation, see Section 1.1 of 24 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 25 | * 26 | * @author Robert Sedgewick 27 | * @author Kevin Wayne 28 | */ 29 | public class RandomSeq { 30 | 31 | // this class should not be instantiated 32 | private RandomSeq() { } 33 | 34 | 35 | /** 36 | * Reads in two command-line arguments lo and hi and prints n uniformly 37 | * random real numbers in [lo, hi) to standard output. 38 | * 39 | * @param args the command-line arguments 40 | */ 41 | public static void main(String[] args) { 42 | 43 | // command-line arguments 44 | int n = Integer.parseInt(args[0]); 45 | 46 | // for backward compatibility with Intro to Programming in Java version of RandomSeq 47 | if (args.length == 1) { 48 | // generate and print n numbers between 0.0 and 1.0 49 | for (int i = 0; i < n; i++) { 50 | double x = StdRandom.uniform(); 51 | StdOut.println(x); 52 | } 53 | } 54 | 55 | else if (args.length == 3) { 56 | double lo = Double.parseDouble(args[1]); 57 | double hi = Double.parseDouble(args[2]); 58 | 59 | // generate and print n numbers between lo and hi 60 | for (int i = 0; i < n; i++) { 61 | double x = StdRandom.uniform(lo, hi); 62 | StdOut.printf("%.2f\n", x); 63 | } 64 | } 65 | 66 | else { 67 | throw new IllegalArgumentException("Invalid number of arguments"); 68 | } 69 | } 70 | } 71 | 72 | /****************************************************************************** 73 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 74 | * 75 | * This file is part of algs4.jar, which accompanies the textbook 76 | * 77 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 78 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 79 | * http://algs4.cs.princeton.edu 80 | * 81 | * 82 | * algs4.jar is free software: you can redistribute it and/or modify 83 | * it under the terms of the GNU General Public License as published by 84 | * the Free Software Foundation, either version 3 of the License, or 85 | * (at your option) any later version. 86 | * 87 | * algs4.jar is distributed in the hope that it will be useful, 88 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 89 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 90 | * GNU General Public License for more details. 91 | * 92 | * You should have received a copy of the GNU General Public License 93 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 94 | ******************************************************************************/ 95 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Whitelist.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Whitelist.java 3 | * Execution: java Whitelist whitelist.txt < data.txt 4 | * Dependencies: StaticSetOfInts.java In.java StdOut.java 5 | * 6 | * Data files: https://algs4.cs.princeton.edu/11model/tinyW.txt 7 | * https://algs4.cs.princeton.edu/11model/tinyT.txt 8 | * https://algs4.cs.princeton.edu/11model/largeW.txt 9 | * https://algs4.cs.princeton.edu/11model/largeT.txt 10 | * 11 | * Whitelist filter. 12 | * 13 | * 14 | * % java Whitelist tinyW.txt < tinyT.txt 15 | * 50 16 | * 99 17 | * 13 18 | * 19 | * % java Whitelist largeW.txt < largeT.txt | more 20 | * 499569 21 | * 984875 22 | * 295754 23 | * 207807 24 | * 140925 25 | * 161828 26 | * [367,966 total values] 27 | * 28 | ******************************************************************************/ 29 | 30 | package edu.princeton.cs.algs4; 31 | 32 | /** 33 | * The {@code Whitelist} class provides a client for reading in 34 | * a set of integers from a file; reading in a sequence of integers 35 | * from standard input; and printing to standard output those 36 | * integers not in the whitelist. 37 | *

38 | * For additional documentation, see Section 1.2 of 39 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 40 | * 41 | * @author Robert Sedgewick 42 | * @author Kevin Wayne 43 | */ 44 | public class Whitelist { 45 | 46 | // Do not instantiate. 47 | private Whitelist() { } 48 | 49 | /** 50 | * Reads in a sequence of integers from the whitelist file, specified as 51 | * a command-line argument. Reads in integers from standard input and 52 | * prints to standard output those integers that are not in the file. 53 | * 54 | * @param args the command-line arguments 55 | */ 56 | public static void main(String[] args) { 57 | In in = new In(args[0]); 58 | int[] white = in.readAllInts(); 59 | StaticSETofInts set = new StaticSETofInts(white); 60 | 61 | // Read key, print if not in whitelist. 62 | while (!StdIn.isEmpty()) { 63 | int key = StdIn.readInt(); 64 | if (!set.contains(key)) 65 | StdOut.println(key); 66 | } 67 | } 68 | } 69 | 70 | /****************************************************************************** 71 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 72 | * 73 | * This file is part of algs4.jar, which accompanies the textbook 74 | * 75 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 76 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 77 | * http://algs4.cs.princeton.edu 78 | * 79 | * 80 | * algs4.jar is free software: you can redistribute it and/or modify 81 | * it under the terms of the GNU General Public License as published by 82 | * the Free Software Foundation, either version 3 of the License, or 83 | * (at your option) any later version. 84 | * 85 | * algs4.jar is distributed in the hope that it will be useful, 86 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 87 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 88 | * GNU General Public License for more details. 89 | * 90 | * You should have received a copy of the GNU General Public License 91 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 92 | ******************************************************************************/ 93 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/PictureDump.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac PictureDump.java 3 | * Execution: java PictureDump width height < file 4 | * Dependencies: BinaryStdIn.java Picture.java 5 | * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits as w-by-h picture, 8 | * with the 1 bits in black and the 0 bits in white. 9 | * 10 | * % more abra.txt 11 | * ABRACADABRA! 12 | * 13 | * % java PictureDump 16 6 < abra.txt 14 | * 15 | ******************************************************************************/ 16 | 17 | package edu.princeton.cs.algs4; 18 | 19 | import java.awt.Color; 20 | 21 | 22 | /** 23 | * The {@code PictureDump} class provides a client for displaying the contents 24 | * of a binary file as a black-and-white picture. 25 | *

26 | * For additional documentation, 27 | * see Section 5.5 of 28 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 29 | *

30 | * See also {@link BinaryDump} and {@link HexDump}. 31 | * 32 | * @author Robert Sedgewick 33 | * @author Kevin Wayne 34 | */ 35 | public class PictureDump { 36 | 37 | // Do not instantiate. 38 | private PictureDump() { } 39 | 40 | /** 41 | * Reads in a sequence of bytes from standard input and draws 42 | * them to standard drawing output as a width-by-height picture, 43 | * using black for 1 and white for 0 (and red for any leftover 44 | * pixels). 45 | * 46 | * @param args the command-line arguments 47 | */ 48 | public static void main(String[] args) { 49 | int width = Integer.parseInt(args[0]); 50 | int height = Integer.parseInt(args[1]); 51 | Picture picture = new Picture(width, height); 52 | for (int row = 0; row < height; row++) { 53 | for (int col = 0; col < width; col++) { 54 | if (!BinaryStdIn.isEmpty()) { 55 | boolean bit = BinaryStdIn.readBoolean(); 56 | if (bit) picture.set(col, row, Color.BLACK); 57 | else picture.set(col, row, Color.WHITE); 58 | } 59 | else { 60 | picture.set(col, row, Color.RED); 61 | } 62 | } 63 | } 64 | picture.show(); 65 | } 66 | } 67 | 68 | /****************************************************************************** 69 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 70 | * 71 | * This file is part of algs4.jar, which accompanies the textbook 72 | * 73 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 74 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 75 | * http://algs4.cs.princeton.edu 76 | * 77 | * 78 | * algs4.jar is free software: you can redistribute it and/or modify 79 | * it under the terms of the GNU General Public License as published by 80 | * the Free Software Foundation, either version 3 of the License, or 81 | * (at your option) any later version. 82 | * 83 | * algs4.jar is distributed in the hope that it will be useful, 84 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 85 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 86 | * GNU General Public License for more details. 87 | * 88 | * You should have received a copy of the GNU General Public License 89 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 90 | ******************************************************************************/ 91 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DoublingRatio.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DoublingRatio.java 3 | * Execution: java DoublingRatio 4 | * Dependencies: ThreeSum.java Stopwatch.java StdRandom.java StdOut.java 5 | * 6 | * 7 | * % java DoublingRatio 8 | * 250 0.0 2.7 9 | * 500 0.0 4.8 10 | * 1000 0.1 6.9 11 | * 2000 0.6 7.7 12 | * 4000 4.5 8.0 13 | * 8000 35.7 8.0 14 | * 4000 3.9 6.6 15 | * ... 16 | * 17 | ******************************************************************************/ 18 | 19 | package edu.princeton.cs.algs4; 20 | 21 | /** 22 | * The {@code DoublingRatio} class provides a client for measuring 23 | * the running time of a method using a doubling ratio test. 24 | *

25 | * For additional documentation, see Section 1.4 26 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class DoublingRatio { 32 | private static final int MAXIMUM_INTEGER = 1000000; 33 | 34 | // This class should not be instantiated. 35 | private DoublingRatio() { } 36 | 37 | /** 38 | * Returns the amount of time to call {@code ThreeSum.count()} with n 39 | * random 6-digit integers. 40 | * @param n the number of integers 41 | * @return amount of time (in seconds) to call {@code ThreeSum.count()} 42 | * with n random 6-digit integers 43 | */ 44 | public static double timeTrial(int n) { 45 | int[] a = new int[n]; 46 | for (int i = 0; i < n; i++) { 47 | a[i] = StdRandom.uniform(-MAXIMUM_INTEGER, MAXIMUM_INTEGER); 48 | } 49 | Stopwatch timer = new Stopwatch(); 50 | ThreeSum.count(a); 51 | return timer.elapsedTime(); 52 | } 53 | 54 | /** 55 | * Prints table of running times to call {@code ThreeSum.count()} 56 | * for arrays of size 250, 500, 1000, 2000, and so forth, along 57 | * with ratios of running times between successive array sizes. 58 | * 59 | * @param args the command-line arguments 60 | */ 61 | public static void main(String[] args) { 62 | double prev = timeTrial(125); 63 | for (int n = 250; true; n += n) { 64 | double time = timeTrial(n); 65 | StdOut.printf("%7d %7.1f %5.1f\n", n, time, time/prev); 66 | prev = time; 67 | } 68 | } 69 | } 70 | 71 | 72 | /****************************************************************************** 73 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 74 | * 75 | * This file is part of algs4.jar, which accompanies the textbook 76 | * 77 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 78 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 79 | * http://algs4.cs.princeton.edu 80 | * 81 | * 82 | * algs4.jar is free software: you can redistribute it and/or modify 83 | * it under the terms of the GNU General Public License as published by 84 | * the Free Software Foundation, either version 3 of the License, or 85 | * (at your option) any later version. 86 | * 87 | * algs4.jar is distributed in the hope that it will be useful, 88 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 89 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 90 | * GNU General Public License for more details. 91 | * 92 | * You should have received a copy of the GNU General Public License 93 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 94 | ******************************************************************************/ 95 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Count.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Count.java 3 | * Execution: java Count alpha < input.txt 4 | * Dependencies: Alphabet.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/50strings/abra.txt 6 | * https://algs4.cs.princeton.edu/50strings/pi.txt 7 | * 8 | * Create an alphabet specified on the command line, read in a 9 | * sequence of characters over that alphabet (ignoring characters 10 | * not in the alphabet), computes the frequency of occurrence of 11 | * each character, and print out the results. 12 | * 13 | * % java Count ABCDR < abra.txt 14 | * A 5 15 | * B 2 16 | * C 1 17 | * D 1 18 | * R 2 19 | * 20 | * % java Count 0123456789 < pi.txt 21 | * 0 99959 22 | * 1 99757 23 | * 2 100026 24 | * 3 100230 25 | * 4 100230 26 | * 5 100359 27 | * 6 99548 28 | * 7 99800 29 | * 8 99985 30 | * 9 100106 31 | * 32 | ******************************************************************************/ 33 | 34 | package edu.princeton.cs.algs4; 35 | 36 | 37 | /** 38 | * The {@code Count} class provides an {@link Alphabet} client for reading 39 | * in a piece of text and computing the frequency of occurrence of each 40 | * character over a given alphabet. 41 | *

42 | * For additional documentation, 43 | * see Section 5.5 of 44 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 45 | * 46 | * @author Robert Sedgewick 47 | * @author Kevin Wayne 48 | */ 49 | public class Count { 50 | 51 | // Do not instantiate. 52 | private Count() { } 53 | 54 | /** 55 | * Reads in text from standard input; calculates the frequency of 56 | * occurrence of each character over the alphabet specified as a 57 | * commmand-line argument; and prints the frequencies to standard 58 | * output. 59 | * 60 | * @param args the command-line arguments 61 | */ 62 | public static void main(String[] args) { 63 | Alphabet alphabet = new Alphabet(args[0]); 64 | final int R = alphabet.radix(); 65 | int[] count = new int[R]; 66 | while (StdIn.hasNextChar()) { 67 | char c = StdIn.readChar(); 68 | if (alphabet.contains(c)) 69 | count[alphabet.toIndex(c)]++; 70 | } 71 | for (int c = 0; c < R; c++) 72 | StdOut.println(alphabet.toChar(c) + " " + count[c]); 73 | } 74 | } 75 | 76 | 77 | /****************************************************************************** 78 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 79 | * 80 | * This file is part of algs4.jar, which accompanies the textbook 81 | * 82 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 83 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 84 | * http://algs4.cs.princeton.edu 85 | * 86 | * 87 | * algs4.jar is free software: you can redistribute it and/or modify 88 | * it under the terms of the GNU General Public License as published by 89 | * the Free Software Foundation, either version 3 of the License, or 90 | * (at your option) any later version. 91 | * 92 | * algs4.jar is distributed in the hope that it will be useful, 93 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 94 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 95 | * GNU General Public License for more details. 96 | * 97 | * You should have received a copy of the GNU General Public License 98 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 99 | ******************************************************************************/ 100 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/BinaryDump.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac BinaryDump.java 3 | * Execution: java BinaryDump n < file 4 | * Dependencies: BinaryStdIn.java 5 | * Data file: https://introcs.cs.princeton.edu/stdlib/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bits, n per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java BinaryDump 16 < abra.txt 13 | * 0100000101000010 14 | * 0101001001000001 15 | * 0100001101000001 16 | * 0100010001000001 17 | * 0100001001010010 18 | * 0100000100100001 19 | * 96 bits 20 | * 21 | ******************************************************************************/ 22 | 23 | package edu.princeton.cs.algs4; 24 | 25 | /** 26 | * The {@code BinaryDump} class provides a client for displaying the contents 27 | * of a binary file in binary. 28 | *

29 | * For more full-featured versions, see the Unix utilities 30 | * {@code od} (octal dump) and {@code hexdump} (hexadecimal dump). 31 | *

32 | * For additional documentation, 33 | * see Section 5.5 of 34 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 35 | *

36 | * See also {@link HexDump} and {@link PictureDump}. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | public class BinaryDump { 42 | 43 | // Do not instantiate. 44 | private BinaryDump() { } 45 | 46 | /** 47 | * Reads in a sequence of bytes from standard input and writes 48 | * them to standard output in binary, k bits per line, 49 | * where k is given as a command-line integer (defaults 50 | * to 16 if no integer is specified); also writes the number 51 | * of bits. 52 | * 53 | * @param args the command-line arguments 54 | */ 55 | public static void main(String[] args) { 56 | int bitsPerLine = 16; 57 | if (args.length == 1) { 58 | bitsPerLine = Integer.parseInt(args[0]); 59 | } 60 | 61 | int count; 62 | for (count = 0; !BinaryStdIn.isEmpty(); count++) { 63 | if (bitsPerLine == 0) { 64 | BinaryStdIn.readBoolean(); 65 | continue; 66 | } 67 | else if (count != 0 && count % bitsPerLine == 0) StdOut.println(); 68 | if (BinaryStdIn.readBoolean()) StdOut.print(1); 69 | else StdOut.print(0); 70 | } 71 | if (bitsPerLine != 0) StdOut.println(); 72 | StdOut.println(count + " bits"); 73 | } 74 | } 75 | 76 | /****************************************************************************** 77 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 78 | * 79 | * This file is part of algs4.jar, which accompanies the textbook 80 | * 81 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 82 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 83 | * http://algs4.cs.princeton.edu 84 | * 85 | * 86 | * algs4.jar is free software: you can redistribute it and/or modify 87 | * it under the terms of the GNU General Public License as published by 88 | * the Free Software Foundation, either version 3 of the License, or 89 | * (at your option) any later version. 90 | * 91 | * algs4.jar is distributed in the hope that it will be useful, 92 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 93 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 94 | * GNU General Public License for more details. 95 | * 96 | * You should have received a copy of the GNU General Public License 97 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 98 | ******************************************************************************/ 99 | -------------------------------------------------------------------------------- /README-MAVEN.txt: -------------------------------------------------------------------------------- 1 | This file provides brief instructions on how to add this repository to 2 | a Maven build, from Eclipse, NetBeans, IntelliJ, or the command line. 3 | Specifically, it provides instructions on creating a version of algs4.jar 4 | that you can use as a dependency in your projects. 5 | 6 | These instructions assume that you already have installed Java 7 7 | (JDK 1.7) or above. 8 | 9 | 10 | Using Maven in Eclipse for Java Developers 11 | ------------------------------------------ 12 | If m2e (Maven plugin) is not built into Eclipse, follow these steps to install the plugin: 13 | 14 | * Open Eclipse. 15 | * Go to Help -> Eclipse Marketplace. 16 | * Search for Maven. 17 | * Click "Install" button at "Maven Integration for Eclipse" or "m2e" section. 18 | * Follow the instruction step by step., 19 | 20 | Restart Eclipse after installing m2e. 21 | 22 | Now you can import algs4 as "Maven Project" into Eclipse: 23 | 24 | * Open menu: File-> Import-> Maven-> Existing Maven Projects... 25 | * Choose directory of algs4. 26 | * Confirm import. 27 | 28 | To complete dependencies resolution after import: 29 | * Right click on the project, choose Maven -> Update Project... 30 | * Confirm project update. 31 | 32 | To build project in Eclipse: 33 | Eclipse automatically builds the project every time it saved. 34 | But if you want enforce build, do following: 35 | * Right click on the project in Eclipse. 36 | * Choose Run as... Maven build. 37 | 38 | Maven will put algs4-.jar in the directory /target. 39 | You can use this jar as a dependency in your projects. 40 | 41 | 42 | Using Maven in IntelliJ IDEA 43 | ---------------------------- 44 | 45 | 46 | Using Maven in Netbeans 47 | ----------------------- 48 | 49 | 50 | Using Maven from the Windows Command Prompt 51 | ------------------------------------------- 52 | Download and install Maven by following the instructions at 53 | https://maven.apache.org. 54 | 55 | Locate the installation directory for Maven, e.g., C:\ 56 | 57 | Locate the installation directory for Java, e.g., C:\Program Files\Java\ 58 | 59 | Set the following environment variables: 60 | 61 | set JAVA_HOME=C:\Program Files\Java\ 62 | set PATH=%JAVA_HOME%\bin;%PATH% 63 | set M2_HOME=C:\ 64 | set PATH=%M2_HOME%\bin;%PATH% 65 | 66 | To create the algs4-.jar package and install it in the local 67 | repository for reuse from other projects, change to the directory of 68 | the algs4 repository and run Maven. 69 | 70 | cd 71 | mvn clean install 72 | 73 | Maven will put algs4-.jar in the directory /target. 74 | You can use this jar as a dependency in your projects. 75 | 76 | 77 | 78 | Using Maven from the Linux / Mac OS X bash shell 79 | ------------------------------------------------ 80 | Download and install Maven, either by using your favorite package 81 | manager (such as apt-get) or by following the instructions at 82 | https://maven.apache.org. 83 | 84 | Locate the installation directory for Maven, e.g., /my/maven/ 85 | 86 | Locate the installation directory for Java, e.g., /my/java/ 87 | 88 | Set the following environment variables: 89 | 90 | export JAVA_HOME=/my/java/ 91 | export PATH=$JAVA_HOME/bin:$PATH 92 | export M2_HOME=/my/maven/ 93 | export PATH=$M2_HOME/bin:$PATH 94 | 95 | To create the algs4-.jar package and install it in the local 96 | repository for reuse from other projects, change to the directory of 97 | the algs4 repository and run Maven. 98 | 99 | cd 100 | mvn clean install 101 | 102 | Maven will put algs4-.jar in the directory /target. 103 | You can use this jar as a dependency in your projects. 104 | 105 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/WhiteFilter.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac WhiteFilter.java 3 | * Execution: java WhiteFilter whitelist.txt < input.txt 4 | * Dependencies: SET In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * https://algs4.cs.princeton.edu/35applications/list.txt 7 | * 8 | * Read in a whitelist of words from a file. Then read in a list of 9 | * words from standard input and print out all those words that 10 | * are in the first file. 11 | * 12 | * % more tinyTale.txt 13 | * it was the best of times it was the worst of times 14 | * it was the age of wisdom it was the age of foolishness 15 | * it was the epoch of belief it was the epoch of incredulity 16 | * it was the season of light it was the season of darkness 17 | * it was the spring of hope it was the winter of despair 18 | * 19 | * % more list.txt 20 | * was it the of 21 | * 22 | * % java WhiteFilter list.txt < tinyTale.txt 23 | * it was the of it was the of 24 | * it was the of it was the of 25 | * it was the of it was the of 26 | * it was the of it was the of 27 | * it was the of it was the of 28 | * 29 | ******************************************************************************/ 30 | 31 | package edu.princeton.cs.algs4; 32 | 33 | /** 34 | * The {@code WhiteFilter} class provides a client for reading in a whitelist 35 | * of words from a file; then, reading in a sequence of words from standard input, 36 | * printing out each word that appears in the file. 37 | * It is useful as a test client for various symbol table implementations. 38 | *

39 | * For additional documentation, see Section 3.5 of 40 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public class WhiteFilter { 46 | 47 | // Do not instantiate. 48 | private WhiteFilter() { } 49 | 50 | public static void main(String[] args) { 51 | SET set = new SET(); 52 | 53 | // read in strings and add to set 54 | In in = new In(args[0]); 55 | while (!in.isEmpty()) { 56 | String word = in.readString(); 57 | set.add(word); 58 | } 59 | 60 | // read in string from standard input, printing out all exceptions 61 | while (!StdIn.isEmpty()) { 62 | String word = StdIn.readString(); 63 | if (set.contains(word)) 64 | StdOut.println(word); 65 | } 66 | } 67 | } 68 | 69 | /****************************************************************************** 70 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 71 | * 72 | * This file is part of algs4.jar, which accompanies the textbook 73 | * 74 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 75 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 76 | * http://algs4.cs.princeton.edu 77 | * 78 | * 79 | * algs4.jar is free software: you can redistribute it and/or modify 80 | * it under the terms of the GNU General Public License as published by 81 | * the Free Software Foundation, either version 3 of the License, or 82 | * (at your option) any later version. 83 | * 84 | * algs4.jar is distributed in the hope that it will be useful, 85 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 86 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 87 | * GNU General Public License for more details. 88 | * 89 | * You should have received a copy of the GNU General Public License 90 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 91 | ******************************************************************************/ 92 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/BlackFilter.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac BlackFilter.java 3 | * Execution: java BlackFilter blacklist.txt < input.txt 4 | * Dependencies: SET In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/tinyTale.txt 6 | * https://algs4.cs.princeton.edu/35applications/list.txt 7 | * 8 | * Read in a blacklist of words from a file. Then read in a list of 9 | * words from standard input and print out all those words that 10 | * are not in the first file. 11 | * 12 | * % more tinyTale.txt 13 | * it was the best of times it was the worst of times 14 | * it was the age of wisdom it was the age of foolishness 15 | * it was the epoch of belief it was the epoch of incredulity 16 | * it was the season of light it was the season of darkness 17 | * it was the spring of hope it was the winter of despair 18 | * 19 | * % more list.txt 20 | * was it the of 21 | * 22 | * % java BlackFilter list.txt < tinyTale.txt 23 | * best times worst times 24 | * age wisdom age foolishness 25 | * epoch belief epoch incredulity 26 | * season light season darkness 27 | * spring hope winter despair 28 | * 29 | ******************************************************************************/ 30 | 31 | package edu.princeton.cs.algs4; 32 | 33 | /** 34 | * The {@code BlackFilter} class provides a client for reading in a blacklist 35 | * of words from a file; then, reading in a sequence of words from standard input, 36 | * printing out each word that does not appear in the file. 37 | * It is useful as a test client for various symbol table implementations. 38 | *

39 | * For additional documentation, see Section 3.5 of 40 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public class BlackFilter { 46 | 47 | // Do not instantiate. 48 | private BlackFilter() { } 49 | 50 | public static void main(String[] args) { 51 | SET set = new SET(); 52 | 53 | // read in strings and add to set 54 | In in = new In(args[0]); 55 | while (!in.isEmpty()) { 56 | String word = in.readString(); 57 | set.add(word); 58 | } 59 | 60 | // read in string from standard input, printing out all exceptions 61 | while (!StdIn.isEmpty()) { 62 | String word = StdIn.readString(); 63 | if (!set.contains(word)) 64 | StdOut.println(word); 65 | } 66 | } 67 | } 68 | 69 | /****************************************************************************** 70 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 71 | * 72 | * This file is part of algs4.jar, which accompanies the textbook 73 | * 74 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 75 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 76 | * http://algs4.cs.princeton.edu 77 | * 78 | * 79 | * algs4.jar is free software: you can redistribute it and/or modify 80 | * it under the terms of the GNU General Public License as published by 81 | * the Free Software Foundation, either version 3 of the License, or 82 | * (at your option) any later version. 83 | * 84 | * algs4.jar is distributed in the hope that it will be useful, 85 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 86 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 87 | * GNU General Public License for more details. 88 | * 89 | * You should have received a copy of the GNU General Public License 90 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 91 | ******************************************************************************/ 92 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/TopM.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac TopM.java 3 | * Execution: java TopM m < input.txt 4 | * Dependencies: MinPQ.java Transaction.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/24pq/tinyBatch.txt 6 | * 7 | * Given an integer m from the command line and an input stream where 8 | * each line contains a String and a long value, this MinPQ client 9 | * prints the m lines whose numbers are the highest. 10 | * 11 | * % java TopM 5 < tinyBatch.txt 12 | * Thompson 2/27/2000 4747.08 13 | * vonNeumann 2/12/1994 4732.35 14 | * vonNeumann 1/11/1999 4409.74 15 | * Hoare 8/18/1992 4381.21 16 | * vonNeumann 3/26/2002 4121.85 17 | * 18 | ******************************************************************************/ 19 | 20 | package edu.princeton.cs.algs4; 21 | 22 | /** 23 | * The {@code TopM} class provides a client that reads a sequence of 24 | * transactions from standard input and prints the m largest ones 25 | * to standard output. This implementation uses a {@link MinPQ} of size 26 | * at most m + 1 to identify the M largest transactions 27 | * and a {@link Stack} to output them in the proper order. 28 | *

29 | * For additional documentation, see Section 2.4 30 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 31 | * 32 | * @author Robert Sedgewick 33 | * @author Kevin Wayne 34 | */ 35 | public class TopM { 36 | 37 | // This class should not be instantiated. 38 | private TopM() { } 39 | 40 | /** 41 | * Reads a sequence of transactions from standard input; takes a 42 | * command-line integer m; prints to standard output the m largest 43 | * transactions in descending order. 44 | * 45 | * @param args the command-line arguments 46 | */ 47 | public static void main(String[] args) { 48 | int m = Integer.parseInt(args[0]); 49 | MinPQ pq = new MinPQ(m+1); 50 | 51 | while (StdIn.hasNextLine()) { 52 | // Create an entry from the next line and put on the PQ. 53 | String line = StdIn.readLine(); 54 | Transaction transaction = new Transaction(line); 55 | pq.insert(transaction); 56 | 57 | // remove minimum if m+1 entries on the PQ 58 | if (pq.size() > m) 59 | pq.delMin(); 60 | } // top m entries are on the PQ 61 | 62 | // print entries on PQ in reverse order 63 | Stack stack = new Stack(); 64 | for (Transaction transaction : pq) 65 | stack.push(transaction); 66 | for (Transaction transaction : stack) 67 | StdOut.println(transaction); 68 | } 69 | } 70 | 71 | 72 | /****************************************************************************** 73 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 74 | * 75 | * This file is part of algs4.jar, which accompanies the textbook 76 | * 77 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 78 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 79 | * http://algs4.cs.princeton.edu 80 | * 81 | * 82 | * algs4.jar is free software: you can redistribute it and/or modify 83 | * it under the terms of the GNU General Public License as published by 84 | * the Free Software Foundation, either version 3 of the License, or 85 | * (at your option) any later version. 86 | * 87 | * algs4.jar is distributed in the hope that it will be useful, 88 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 89 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 90 | * GNU General Public License for more details. 91 | * 92 | * You should have received a copy of the GNU General Public License 93 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 94 | ******************************************************************************/ 95 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/FileIndex.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac FileIndex.java 3 | * Execution: java FileIndex file1.txt file2.txt file3.txt ... 4 | * Dependencies: ST.java SET.java In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/ex1.txt 6 | * https://algs4.cs.princeton.edu/35applications/ex2.txt 7 | * https://algs4.cs.princeton.edu/35applications/ex3.txt 8 | * https://algs4.cs.princeton.edu/35applications/ex4.txt 9 | * 10 | * % java FileIndex ex*.txt 11 | * age 12 | * ex3.txt 13 | * ex4.txt 14 | * best 15 | * ex1.txt 16 | * was 17 | * ex1.txt 18 | * ex2.txt 19 | * ex3.txt 20 | * ex4.txt 21 | * 22 | * % java FileIndex *.txt 23 | * 24 | * % java FileIndex *.java 25 | * 26 | ******************************************************************************/ 27 | 28 | package edu.princeton.cs.algs4; 29 | 30 | import java.io.File; 31 | 32 | /** 33 | * The {@code FileIndex} class provides a client for indexing a set of files, 34 | * specified as command-line arguments. It takes queries from standard input 35 | * and prints each file that contains the given query. 36 | *

37 | * For additional documentation, see Section 3.5 of 38 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 39 | * 40 | * @author Robert Sedgewick 41 | * @author Kevin Wayne 42 | */ 43 | public class FileIndex { 44 | 45 | // Do not instantiate. 46 | private FileIndex() { } 47 | 48 | public static void main(String[] args) { 49 | 50 | // key = word, value = set of files containing that word 51 | ST> st = new ST>(); 52 | 53 | // create inverted index of all files 54 | StdOut.println("Indexing files"); 55 | for (String filename : args) { 56 | StdOut.println(" " + filename); 57 | File file = new File(filename); 58 | In in = new In(file); 59 | while (!in.isEmpty()) { 60 | String word = in.readString(); 61 | if (!st.contains(word)) st.put(word, new SET()); 62 | SET set = st.get(word); 63 | set.add(file); 64 | } 65 | } 66 | 67 | 68 | // read queries from standard input, one per line 69 | while (!StdIn.isEmpty()) { 70 | String query = StdIn.readString(); 71 | if (st.contains(query)) { 72 | SET set = st.get(query); 73 | for (File file : set) { 74 | StdOut.println(" " + file.getName()); 75 | } 76 | } 77 | } 78 | 79 | } 80 | 81 | } 82 | 83 | /****************************************************************************** 84 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 85 | * 86 | * This file is part of algs4.jar, which accompanies the textbook 87 | * 88 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 89 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 90 | * http://algs4.cs.princeton.edu 91 | * 92 | * 93 | * algs4.jar is free software: you can redistribute it and/or modify 94 | * it under the terms of the GNU General Public License as published by 95 | * the Free Software Foundation, either version 3 of the License, or 96 | * (at your option) any later version. 97 | * 98 | * algs4.jar is distributed in the hope that it will be useful, 99 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 100 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 101 | * GNU General Public License for more details. 102 | * 103 | * You should have received a copy of the GNU General Public License 104 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 105 | ******************************************************************************/ 106 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/HexDump.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac HexDump.java 3 | * Execution: java HexDump < file 4 | * Dependencies: BinaryStdIn.java StdOut.java 5 | * Data file: https://algs4.cs.princeton.edu/55compression/abra.txt 6 | * 7 | * Reads in a binary file and writes out the bytes in hex, 16 per line. 8 | * 9 | * % more abra.txt 10 | * ABRACADABRA! 11 | * 12 | * % java HexDump 16 < abra.txt 13 | * 41 42 52 41 43 41 44 41 42 52 41 21 14 | * 96 bits 15 | * 16 | * 17 | * Remark 18 | * -------------------------- 19 | * - Similar to the Unix utilities od (octal dump) or hexdump (hexadecimal dump). 20 | * 21 | * % od -t x1 < abra.txt 22 | * 0000000 41 42 52 41 43 41 44 41 42 52 41 21 23 | * 0000014 24 | * 25 | ******************************************************************************/ 26 | 27 | package edu.princeton.cs.algs4; 28 | 29 | /** 30 | * The {@code HexDump} class provides a client for displaying the contents 31 | * of a binary file in hexadecimal. 32 | *

33 | * For additional documentation, 34 | * see Section 5.5 of 35 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 36 | *

37 | * See also {@link BinaryDump} and {@link PictureDump}. 38 | * For more full-featured versions, see the Unix utilities 39 | * {@code od} (octal dump) and {@code hexdump} (hexadecimal dump). 40 | *

41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public class HexDump { 46 | 47 | // Do not instantiate. 48 | private HexDump() { } 49 | 50 | /** 51 | * Reads in a sequence of bytes from standard input and writes 52 | * them to standard output using hexademical notation, k hex digits 53 | * per line, where k is given as a command-line integer (defaults 54 | * to 16 if no integer is specified); also writes the number 55 | * of bits. 56 | * 57 | * @param args the command-line arguments 58 | */ 59 | public static void main(String[] args) { 60 | int bytesPerLine = 16; 61 | if (args.length == 1) { 62 | bytesPerLine = Integer.parseInt(args[0]); 63 | } 64 | 65 | int i; 66 | for (i = 0; !BinaryStdIn.isEmpty(); i++) { 67 | if (bytesPerLine == 0) { 68 | BinaryStdIn.readChar(); 69 | continue; 70 | } 71 | if (i == 0) StdOut.printf(""); 72 | else if (i % bytesPerLine == 0) StdOut.printf("\n", i); 73 | else StdOut.print(" "); 74 | char c = BinaryStdIn.readChar(); 75 | StdOut.printf("%02x", c & 0xff); 76 | } 77 | if (bytesPerLine != 0) StdOut.println(); 78 | StdOut.println((i*8) + " bits"); 79 | } 80 | } 81 | 82 | /****************************************************************************** 83 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 84 | * 85 | * This file is part of algs4.jar, which accompanies the textbook 86 | * 87 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 88 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 89 | * http://algs4.cs.princeton.edu 90 | * 91 | * 92 | * algs4.jar is free software: you can redistribute it and/or modify 93 | * it under the terms of the GNU General Public License as published by 94 | * the Free Software Foundation, either version 3 of the License, or 95 | * (at your option) any later version. 96 | * 97 | * algs4.jar is distributed in the hope that it will be useful, 98 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 99 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 100 | * GNU General Public License for more details. 101 | * 102 | * You should have received a copy of the GNU General Public License 103 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 104 | ******************************************************************************/ 105 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/StaticSETofInts.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac StaticSetOfInts.java 3 | * Execution: none 4 | * Dependencies: StdOut.java 5 | * 6 | * Data type to store a set of integers. 7 | * 8 | ******************************************************************************/ 9 | 10 | package edu.princeton.cs.algs4; 11 | 12 | import java.util.Arrays; 13 | 14 | /** 15 | * The {@code StaticSETofInts} class represents a set of integers. 16 | * It supports searching for a given integer is in the set. It accomplishes 17 | * this by keeping the set of integers in a sorted array and using 18 | * binary search to find the given integer. 19 | *

20 | * The rank and contains operations take 21 | * logarithmic time in the worst case. 22 | *

23 | * For additional documentation, see Section 1.2 of 24 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 25 | * 26 | * @author Robert Sedgewick 27 | * @author Kevin Wayne 28 | */ 29 | public class StaticSETofInts { 30 | private int[] a; 31 | 32 | /** 33 | * Initializes a set of integers specified by the integer array. 34 | * @param keys the array of integers 35 | * @throws IllegalArgumentException if the array contains duplicate integers 36 | */ 37 | public StaticSETofInts(int[] keys) { 38 | 39 | // defensive copy 40 | a = new int[keys.length]; 41 | for (int i = 0; i < keys.length; i++) 42 | a[i] = keys[i]; 43 | 44 | // sort the integers 45 | Arrays.sort(a); 46 | 47 | // check for duplicates 48 | for (int i = 1; i < a.length; i++) 49 | if (a[i] == a[i-1]) 50 | throw new IllegalArgumentException("Argument arrays contains duplicate keys."); 51 | } 52 | 53 | /** 54 | * Is the key in this set of integers? 55 | * @param key the search key 56 | * @return true if the set of integers contains the key; false otherwise 57 | */ 58 | public boolean contains(int key) { 59 | return rank(key) != -1; 60 | } 61 | 62 | /** 63 | * Returns either the index of the search key in the sorted array 64 | * (if the key is in the set) or -1 (if the key is not in the set). 65 | * @param key the search key 66 | * @return the number of keys in this set less than the key (if the key is in the set) 67 | * or -1 (if the key is not in the set). 68 | */ 69 | public int rank(int key) { 70 | int lo = 0; 71 | int hi = a.length - 1; 72 | while (lo <= hi) { 73 | // Key is in a[lo..hi] or not present. 74 | int mid = lo + (hi - lo) / 2; 75 | if (key < a[mid]) hi = mid - 1; 76 | else if (key > a[mid]) lo = mid + 1; 77 | else return mid; 78 | } 79 | return -1; 80 | } 81 | } 82 | 83 | /****************************************************************************** 84 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 85 | * 86 | * This file is part of algs4.jar, which accompanies the textbook 87 | * 88 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 89 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 90 | * http://algs4.cs.princeton.edu 91 | * 92 | * 93 | * algs4.jar is free software: you can redistribute it and/or modify 94 | * it under the terms of the GNU General Public License as published by 95 | * the Free Software Foundation, either version 3 of the License, or 96 | * (at your option) any later version. 97 | * 98 | * algs4.jar is distributed in the hope that it will be useful, 99 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 100 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 101 | * GNU General Public License for more details. 102 | * 103 | * You should have received a copy of the GNU General Public License 104 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 105 | ******************************************************************************/ 106 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Multiway.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Multiway.java 3 | * Execution: java Multiway input1.txt input2.txt input3.txt ... 4 | * Dependencies: IndexMinPQ.java In.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/24pq/m1.txt 6 | * https://algs4.cs.princeton.edu/24pq/m2.txt 7 | * https://algs4.cs.princeton.edu/24pq/m3.txt 8 | * 9 | * Merges together the sorted input stream given as command-line arguments 10 | * into a single sorted output stream on standard output. 11 | * 12 | * % more m1.txt 13 | * A B C F G I I Z 14 | * 15 | * % more m2.txt 16 | * B D H P Q Q 17 | * 18 | * % more m3.txt 19 | * A B E F J N 20 | * 21 | * % java Multiway m1.txt m2.txt m3.txt 22 | * A A B B B C D E F F G H I I J N P Q Q Z 23 | * 24 | ******************************************************************************/ 25 | 26 | package edu.princeton.cs.algs4; 27 | 28 | /** 29 | * The {@code Multiway} class provides a client for reading in several 30 | * sorted text files and merging them together into a single sorted 31 | * text stream. 32 | * This implementation uses a {@link IndexMinPQ} to perform the multiway 33 | * merge. 34 | *

35 | * For additional documentation, see Section 2.4 36 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | 42 | public class Multiway { 43 | 44 | // This class should not be instantiated. 45 | private Multiway() { } 46 | 47 | // merge together the sorted input streams and write the sorted result to standard output 48 | private static void merge(In[] streams) { 49 | int n = streams.length; 50 | IndexMinPQ pq = new IndexMinPQ(n); 51 | for (int i = 0; i < n; i++) 52 | if (!streams[i].isEmpty()) 53 | pq.insert(i, streams[i].readString()); 54 | 55 | // Extract and print min and read next from its stream. 56 | while (!pq.isEmpty()) { 57 | StdOut.print(pq.minKey() + " "); 58 | int i = pq.delMin(); 59 | if (!streams[i].isEmpty()) 60 | pq.insert(i, streams[i].readString()); 61 | } 62 | StdOut.println(); 63 | } 64 | 65 | 66 | /** 67 | * Reads sorted text files specified as command-line arguments; 68 | * merges them together into a sorted output; and writes 69 | * the results to standard output. 70 | * Note: this client does not check that the input files are sorted. 71 | * 72 | * @param args the command-line arguments 73 | */ 74 | public static void main(String[] args) { 75 | int n = args.length; 76 | In[] streams = new In[n]; 77 | for (int i = 0; i < n; i++) 78 | streams[i] = new In(args[i]); 79 | merge(streams); 80 | } 81 | } 82 | 83 | /****************************************************************************** 84 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 85 | * 86 | * This file is part of algs4.jar, which accompanies the textbook 87 | * 88 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 89 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 90 | * http://algs4.cs.princeton.edu 91 | * 92 | * 93 | * algs4.jar is free software: you can redistribute it and/or modify 94 | * it under the terms of the GNU General Public License as published by 95 | * the Free Software Foundation, either version 3 of the License, or 96 | * (at your option) any later version. 97 | * 98 | * algs4.jar is distributed in the hope that it will be useful, 99 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 100 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 101 | * GNU General Public License for more details. 102 | * 103 | * You should have received a copy of the GNU General Public License 104 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 105 | ******************************************************************************/ 106 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Genome.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Genome.java 3 | * Execution: java Genome - < input.txt (compress) 4 | * Execution: java Genome + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * Data files: https://algs4.cs.princeton.edu/55compression/genomeTiny.txt 7 | * 8 | * Compress or expand a genomic sequence using a 2-bit code. 9 | * 10 | * % more genomeTiny.txt 11 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 12 | * 13 | * % java Genome - < genomeTiny.txt | java Genome + 14 | * ATAGATGCATAGCGCATAGCTAGATGTGCTAGC 15 | * 16 | ******************************************************************************/ 17 | 18 | package edu.princeton.cs.algs4; 19 | 20 | /** 21 | * The {@code Genome} class provides static methods for compressing 22 | * and expanding a genomic sequence using a 2-bit code. 23 | *

24 | * For additional documentation, 25 | * see Section 5.5 of 26 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 27 | * 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | public class Genome { 32 | 33 | // Do not instantiate. 34 | private Genome() { } 35 | 36 | /** 37 | * Reads a sequence of 8-bit extended ASCII characters over the alphabet 38 | * { A, C, T, G } from standard input; compresses them using two bits per 39 | * character; and writes the results to standard output. 40 | */ 41 | public static void compress() { 42 | Alphabet DNA = Alphabet.DNA; 43 | String s = BinaryStdIn.readString(); 44 | int n = s.length(); 45 | BinaryStdOut.write(n); 46 | 47 | // Write two-bit code for char. 48 | for (int i = 0; i < n; i++) { 49 | int d = DNA.toIndex(s.charAt(i)); 50 | BinaryStdOut.write(d, 2); 51 | } 52 | BinaryStdOut.close(); 53 | } 54 | 55 | /** 56 | * Reads a binary sequence from standard input; converts each two bits 57 | * to an 8-bit extended ASCII character over the alphabet { A, C, T, G }; 58 | * and writes the results to standard output. 59 | */ 60 | public static void expand() { 61 | Alphabet DNA = Alphabet.DNA; 62 | int n = BinaryStdIn.readInt(); 63 | // Read two bits; write char. 64 | for (int i = 0; i < n; i++) { 65 | char c = BinaryStdIn.readChar(2); 66 | BinaryStdOut.write(DNA.toChar(c), 8); 67 | } 68 | BinaryStdOut.close(); 69 | } 70 | 71 | 72 | /** 73 | * Sample client that calls {@code compress()} if the command-line 74 | * argument is "-" an {@code expand()} if it is "+". 75 | * 76 | * @param args the command-line arguments 77 | */ 78 | public static void main(String[] args) { 79 | if (args[0].equals("-")) compress(); 80 | else if (args[0].equals("+")) expand(); 81 | else throw new IllegalArgumentException("Illegal command line argument"); 82 | } 83 | 84 | } 85 | 86 | /****************************************************************************** 87 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 88 | * 89 | * This file is part of algs4.jar, which accompanies the textbook 90 | * 91 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 92 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 93 | * http://algs4.cs.princeton.edu 94 | * 95 | * 96 | * algs4.jar is free software: you can redistribute it and/or modify 97 | * it under the terms of the GNU General Public License as published by 98 | * the Free Software Foundation, either version 3 of the License, or 99 | * (at your option) any later version. 100 | * 101 | * algs4.jar is distributed in the hope that it will be useful, 102 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 103 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 104 | * GNU General Public License for more details. 105 | * 106 | * You should have received a copy of the GNU General Public License 107 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 108 | ******************************************************************************/ 109 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Stopwatch.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Stopwatch.java 3 | * Execution: java Stopwatch n 4 | * Dependencies: none 5 | * 6 | * A utility class to measure the running time (wall clock) of a program. 7 | * 8 | * % java8 Stopwatch 100000000 9 | * 6.666667e+11 0.5820 seconds 10 | * 6.666667e+11 8.4530 seconds 11 | * 12 | ******************************************************************************/ 13 | 14 | package edu.princeton.cs.algs4; 15 | 16 | /** 17 | * The {@code Stopwatch} data type is for measuring 18 | * the time that elapses between the start and end of a 19 | * programming task (wall-clock time). 20 | * 21 | * See {@link StopwatchCPU} for a version that measures CPU time. 22 | * For additional documentation, 23 | * see Section 1.4 of 24 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 25 | * 26 | * @author Robert Sedgewick 27 | * @author Kevin Wayne 28 | */ 29 | 30 | 31 | public class Stopwatch { 32 | 33 | private final long start; 34 | 35 | /** 36 | * Initializes a new stopwatch. 37 | */ 38 | public Stopwatch() { 39 | start = System.currentTimeMillis(); 40 | } 41 | 42 | 43 | /** 44 | * Returns the elapsed CPU time (in seconds) since the stopwatch was created. 45 | * 46 | * @return elapsed CPU time (in seconds) since the stopwatch was created 47 | */ 48 | public double elapsedTime() { 49 | long now = System.currentTimeMillis(); 50 | return (now - start) / 1000.0; 51 | } 52 | 53 | 54 | /** 55 | * Unit tests the {@code Stopwatch} data type. 56 | * Takes a command-line argument {@code n} and computes the 57 | * sum of the square roots of the first {@code n} positive integers, 58 | * first using {@code Math.sqrt()}, then using {@code Math.pow()}. 59 | * It prints to standard output the sum and the amount of time to 60 | * compute the sum. Note that the discrete sum can be approximated by 61 | * an integral - the sum should be approximately 2/3 * (n^(3/2) - 1). 62 | * 63 | * @param args the command-line arguments 64 | */ 65 | public static void main(String[] args) { 66 | int n = Integer.parseInt(args[0]); 67 | 68 | // sum of square roots of integers from 1 to n using Math.sqrt(x). 69 | Stopwatch timer1 = new Stopwatch(); 70 | double sum1 = 0.0; 71 | for (int i = 1; i <= n; i++) { 72 | sum1 += Math.sqrt(i); 73 | } 74 | double time1 = timer1.elapsedTime(); 75 | StdOut.printf("%e (%.2f seconds)\n", sum1, time1); 76 | 77 | // sum of square roots of integers from 1 to n using Math.pow(x, 0.5). 78 | Stopwatch timer2 = new Stopwatch(); 79 | double sum2 = 0.0; 80 | for (int i = 1; i <= n; i++) { 81 | sum2 += Math.pow(i, 0.5); 82 | } 83 | double time2 = timer2.elapsedTime(); 84 | StdOut.printf("%e (%.2f seconds)\n", sum2, time2); 85 | } 86 | } 87 | 88 | /****************************************************************************** 89 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 90 | * 91 | * This file is part of algs4.jar, which accompanies the textbook 92 | * 93 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 94 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 95 | * http://algs4.cs.princeton.edu 96 | * 97 | * 98 | * algs4.jar is free software: you can redistribute it and/or modify 99 | * it under the terms of the GNU General Public License as published by 100 | * the Free Software Foundation, either version 3 of the License, or 101 | * (at your option) any later version. 102 | * 103 | * algs4.jar is distributed in the hope that it will be useful, 104 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 105 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 106 | * GNU General Public License for more details. 107 | * 108 | * You should have received a copy of the GNU General Public License 109 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 110 | ******************************************************************************/ 111 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DirectedEdge.java 3 | * Execution: java DirectedEdge 4 | * Dependencies: StdOut.java 5 | * 6 | * Immutable weighted directed edge. 7 | * 8 | ******************************************************************************/ 9 | 10 | package edu.princeton.cs.algs4; 11 | /** 12 | * The {@code DirectedEdge} class represents a weighted edge in an 13 | * {@link EdgeWeightedDigraph}. Each edge consists of two integers 14 | * (naming the two vertices) and a real-value weight. The data type 15 | * provides methods for accessing the two endpoints of the directed edge and 16 | * the weight. 17 | *

18 | * For additional documentation, see Section 4.4 of 19 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 20 | * 21 | * @author Robert Sedgewick 22 | * @author Kevin Wayne 23 | */ 24 | 25 | public class DirectedEdge { 26 | private final int v; 27 | private final int w; 28 | private final double weight; 29 | 30 | /** 31 | * Initializes a directed edge from vertex {@code v} to vertex {@code w} with 32 | * the given {@code weight}. 33 | * @param v the tail vertex 34 | * @param w the head vertex 35 | * @param weight the weight of the directed edge 36 | * @throws IllegalArgumentException if either {@code v} or {@code w} 37 | * is a negative integer 38 | * @throws IllegalArgumentException if {@code weight} is {@code NaN} 39 | */ 40 | public DirectedEdge(int v, int w, double weight) { 41 | if (v < 0) throw new IllegalArgumentException("Vertex names must be nonnegative integers"); 42 | if (w < 0) throw new IllegalArgumentException("Vertex names must be nonnegative integers"); 43 | if (Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN"); 44 | this.v = v; 45 | this.w = w; 46 | this.weight = weight; 47 | } 48 | 49 | /** 50 | * Returns the tail vertex of the directed edge. 51 | * @return the tail vertex of the directed edge 52 | */ 53 | public int from() { 54 | return v; 55 | } 56 | 57 | /** 58 | * Returns the head vertex of the directed edge. 59 | * @return the head vertex of the directed edge 60 | */ 61 | public int to() { 62 | return w; 63 | } 64 | 65 | /** 66 | * Returns the weight of the directed edge. 67 | * @return the weight of the directed edge 68 | */ 69 | public double weight() { 70 | return weight; 71 | } 72 | 73 | /** 74 | * Returns a string representation of the directed edge. 75 | * @return a string representation of the directed edge 76 | */ 77 | public String toString() { 78 | return v + "->" + w + " " + String.format("%5.2f", weight); 79 | } 80 | 81 | /** 82 | * Unit tests the {@code DirectedEdge} data type. 83 | * 84 | * @param args the command-line arguments 85 | */ 86 | public static void main(String[] args) { 87 | DirectedEdge e = new DirectedEdge(12, 34, 5.67); 88 | StdOut.println(e); 89 | } 90 | } 91 | 92 | /****************************************************************************** 93 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 94 | * 95 | * This file is part of algs4.jar, which accompanies the textbook 96 | * 97 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 98 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 99 | * http://algs4.cs.princeton.edu 100 | * 101 | * 102 | * algs4.jar is free software: you can redistribute it and/or modify 103 | * it under the terms of the GNU General Public License as published by 104 | * the Free Software Foundation, either version 3 of the License, or 105 | * (at your option) any later version. 106 | * 107 | * algs4.jar is distributed in the hope that it will be useful, 108 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 109 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 110 | * GNU General Public License for more details. 111 | * 112 | * You should have received a copy of the GNU General Public License 113 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 114 | ******************************************************************************/ 115 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Arbitrage.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Arbitrage.java 3 | * Execution: java Arbitrage < input.txt 4 | * Dependencies: EdgeWeightedDigraph.java DirectedEdge.java 5 | * BellmanFordSP.java 6 | * Data file: https://algs4.cs.princeton.edu/44sp/rates.txt 7 | * 8 | * Arbitrage detection. 9 | * 10 | * % more rates.txt 11 | * 5 12 | * USD 1 0.741 0.657 1.061 1.005 13 | * EUR 1.349 1 0.888 1.433 1.366 14 | * GBP 1.521 1.126 1 1.614 1.538 15 | * CHF 0.942 0.698 0.619 1 0.953 16 | * CAD 0.995 0.732 0.650 1.049 1 17 | * 18 | * % java Arbitrage < rates.txt 19 | * 1000.00000 USD = 741.00000 EUR 20 | * 741.00000 EUR = 1012.20600 CAD 21 | * 1012.20600 CAD = 1007.14497 USD 22 | * 23 | ******************************************************************************/ 24 | 25 | package edu.princeton.cs.algs4; 26 | 27 | /** 28 | * The {@code Arbitrage} class provides a client that finds an arbitrage 29 | * opportunity in a currency exchange table by constructing a 30 | * complete-digraph representation of the exchange table and then finding 31 | * a negative cycle in the digraph. 32 | *

33 | * This implementation uses the Bellman-Ford algorithm to find a 34 | * negative cycle in the complete digraph. 35 | * The running time is proportional to V3 in the 36 | * worst case, where V is the number of currencies. 37 | *

38 | * For additional documentation, 39 | * see Section 4.4 of 40 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public class Arbitrage { 46 | 47 | // this class cannot be instantiated 48 | private Arbitrage() { } 49 | 50 | /** 51 | * Reads the currency exchange table from standard input and 52 | * prints an arbitrage opportunity to standard output (if one exists). 53 | * 54 | * @param args the command-line arguments 55 | */ 56 | public static void main(String[] args) { 57 | 58 | // V currencies 59 | int V = StdIn.readInt(); 60 | String[] name = new String[V]; 61 | 62 | // create complete network 63 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(V); 64 | for (int v = 0; v < V; v++) { 65 | name[v] = StdIn.readString(); 66 | for (int w = 0; w < V; w++) { 67 | double rate = StdIn.readDouble(); 68 | DirectedEdge e = new DirectedEdge(v, w, -Math.log(rate)); 69 | G.addEdge(e); 70 | } 71 | } 72 | 73 | // find negative cycle 74 | BellmanFordSP spt = new BellmanFordSP(G, 0); 75 | if (spt.hasNegativeCycle()) { 76 | double stake = 1000.0; 77 | for (DirectedEdge e : spt.negativeCycle()) { 78 | StdOut.printf("%10.5f %s ", stake, name[e.from()]); 79 | stake *= Math.exp(-e.weight()); 80 | StdOut.printf("= %10.5f %s\n", stake, name[e.to()]); 81 | } 82 | } 83 | else { 84 | StdOut.println("No arbitrage opportunity"); 85 | } 86 | } 87 | 88 | } 89 | 90 | /****************************************************************************** 91 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 92 | * 93 | * This file is part of algs4.jar, which accompanies the textbook 94 | * 95 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 96 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 97 | * http://algs4.cs.princeton.edu 98 | * 99 | * 100 | * algs4.jar is free software: you can redistribute it and/or modify 101 | * it under the terms of the GNU General Public License as published by 102 | * the Free Software Foundation, either version 3 of the License, or 103 | * (at your option) any later version. 104 | * 105 | * algs4.jar is distributed in the hope that it will be useful, 106 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 107 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 108 | * GNU General Public License for more details. 109 | * 110 | * You should have received a copy of the GNU General Public License 111 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 112 | ******************************************************************************/ 113 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/StopwatchCPU.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac StopwatchCPU.java 3 | * Execution: java StopwtachCPU n 4 | * Dependencies: none 5 | * 6 | * A version of Stopwatch.java that measures CPU time on a single 7 | * core or processor (instead of wall clock time). 8 | * 9 | * % java8 StopwatchCPU 100000000 10 | * 6.666667e+11 (1.05 seconds) 11 | * 6.666667e+11 (7.50 seconds) 12 | * 13 | ******************************************************************************/ 14 | 15 | package edu.princeton.cs.algs4; 16 | 17 | import java.lang.management.ThreadMXBean; 18 | import java.lang.management.ManagementFactory; 19 | 20 | /** 21 | * The {@code StopwatchCPU} data type is for measuring 22 | * the CPU time used during a programming task. 23 | * 24 | * See {@link Stopwatch} for a version that measures wall-clock time 25 | * (the real time that elapses). 26 | * 27 | * @author Josh Hug 28 | * @author Robert Sedgewick 29 | * @author Kevin Wayne 30 | */ 31 | 32 | public class StopwatchCPU { 33 | private static final double NANOSECONDS_PER_SECOND = 1000000000; 34 | 35 | private final ThreadMXBean threadTimer; 36 | private final long start; 37 | 38 | /** 39 | * Initializes a new stopwatch. 40 | */ 41 | public StopwatchCPU() { 42 | threadTimer = ManagementFactory.getThreadMXBean(); 43 | start = threadTimer.getCurrentThreadCpuTime(); 44 | } 45 | 46 | /** 47 | * Returns the elapsed CPU time (in seconds) since the stopwatch was created. 48 | * 49 | * @return elapsed CPU time (in seconds) since the stopwatch was created 50 | */ 51 | public double elapsedTime() { 52 | long now = threadTimer.getCurrentThreadCpuTime(); 53 | return (now - start) / NANOSECONDS_PER_SECOND; 54 | } 55 | 56 | /** 57 | * Unit tests the {@code StopwatchCPU} data type. 58 | * Takes a command-line argument {@code n} and computes the 59 | * sum of the square roots of the first {@code n} positive integers, 60 | * first using {@code Math.sqrt()}, then using {@code Math.pow()}. 61 | * It prints to standard output the sum and the amount of time to 62 | * compute the sum. Note that the discrete sum can be approximated by 63 | * an integral - the sum should be approximately 2/3 * (n^(3/2) - 1). 64 | * 65 | * @param args the command-line arguments 66 | */ 67 | public static void main(String[] args) { 68 | int n = Integer.parseInt(args[0]); 69 | 70 | // sum of square roots of integers from 1 to n using Math.sqrt(x). 71 | StopwatchCPU timer1 = new StopwatchCPU(); 72 | double sum1 = 0.0; 73 | for (int i = 1; i <= n; i++) { 74 | sum1 += Math.sqrt(i); 75 | } 76 | double time1 = timer1.elapsedTime(); 77 | StdOut.printf("%e (%.2f seconds)\n", sum1, time1); 78 | 79 | // sum of square roots of integers from 1 to n using Math.pow(x, 0.5). 80 | StopwatchCPU timer2 = new StopwatchCPU(); 81 | double sum2 = 0.0; 82 | for (int i = 1; i <= n; i++) { 83 | sum2 += Math.pow(i, 0.5); 84 | } 85 | double time2 = timer2.elapsedTime(); 86 | StdOut.printf("%e (%.2f seconds)\n", sum2, time2); 87 | } 88 | } 89 | 90 | /****************************************************************************** 91 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 92 | * 93 | * This file is part of algs4.jar, which accompanies the textbook 94 | * 95 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 96 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 97 | * http://algs4.cs.princeton.edu 98 | * 99 | * 100 | * algs4.jar is free software: you can redistribute it and/or modify 101 | * it under the terms of the GNU General Public License as published by 102 | * the Free Software Foundation, either version 3 of the License, or 103 | * (at your option) any later version. 104 | * 105 | * algs4.jar is distributed in the hope that it will be useful, 106 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 107 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 108 | * GNU General Public License for more details. 109 | * 110 | * You should have received a copy of the GNU General Public License 111 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 112 | ******************************************************************************/ 113 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LookupIndex.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LookupIndex.java 3 | * Execution: java LookupIndex movies.txt "/" 4 | * Dependencies: ST.java Queue.java In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/aminoI.csv 6 | * https://algs4.cs.princeton.edu/35applications/movies.txt 7 | * 8 | * % java LookupIndex aminoI.csv "," 9 | * Serine 10 | * TCT 11 | * TCA 12 | * TCG 13 | * AGT 14 | * AGC 15 | * TCG 16 | * Serine 17 | * 18 | * % java LookupIndex movies.txt "/" 19 | * Bacon, Kevin 20 | * Animal House (1978) 21 | * Apollo 13 (1995) 22 | * Beauty Shop (2005) 23 | * Diner (1982) 24 | * Few Good Men, A (1992) 25 | * Flatliners (1990) 26 | * Footloose (1984) 27 | * Friday the 13th (1980) 28 | * ... 29 | * Tin Men (1987) 30 | * DeBoy, David 31 | * Blumenfeld, Alan 32 | * ... 33 | * 34 | ******************************************************************************/ 35 | 36 | package edu.princeton.cs.algs4; 37 | 38 | /** 39 | * The {@code LookupIndex} class provides a data-driven client for reading in a 40 | * key-value pairs from a file; then, printing the values corresponding to the 41 | * keys found on standard input. Keys are strings; values are lists of strings. 42 | * The separating delimiter is taken as a command-line argument. This client 43 | * is sometimes known as an inverted index. 44 | *

45 | * For additional documentation, see Section 3.5 of 46 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 47 | * 48 | * @author Robert Sedgewick 49 | * @author Kevin Wayne 50 | */ 51 | public class LookupIndex { 52 | 53 | // Do not instantiate. 54 | private LookupIndex() { } 55 | 56 | public static void main(String[] args) { 57 | String filename = args[0]; 58 | String separator = args[1]; 59 | In in = new In(filename); 60 | 61 | ST> st = new ST>(); 62 | ST> ts = new ST>(); 63 | 64 | while (in.hasNextLine()) { 65 | String line = in.readLine(); 66 | String[] fields = line.split(separator); 67 | String key = fields[0]; 68 | for (int i = 1; i < fields.length; i++) { 69 | String val = fields[i]; 70 | if (!st.contains(key)) st.put(key, new Queue()); 71 | if (!ts.contains(val)) ts.put(val, new Queue()); 72 | st.get(key).enqueue(val); 73 | ts.get(val).enqueue(key); 74 | } 75 | } 76 | 77 | StdOut.println("Done indexing"); 78 | 79 | // read queries from standard input, one per line 80 | while (!StdIn.isEmpty()) { 81 | String query = StdIn.readLine(); 82 | if (st.contains(query)) 83 | for (String vals : st.get(query)) 84 | StdOut.println(" " + vals); 85 | if (ts.contains(query)) 86 | for (String keys : ts.get(query)) 87 | StdOut.println(" " + keys); 88 | } 89 | 90 | } 91 | 92 | } 93 | 94 | /****************************************************************************** 95 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 96 | * 97 | * This file is part of algs4.jar, which accompanies the textbook 98 | * 99 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 100 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 101 | * http://algs4.cs.princeton.edu 102 | * 103 | * 104 | * algs4.jar is free software: you can redistribute it and/or modify 105 | * it under the terms of the GNU General Public License as published by 106 | * the Free Software Foundation, either version 3 of the License, or 107 | * (at your option) any later version. 108 | * 109 | * algs4.jar is distributed in the hope that it will be useful, 110 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 111 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 112 | * GNU General Public License for more details. 113 | * 114 | * You should have received a copy of the GNU General Public License 115 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 116 | ******************************************************************************/ 117 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LongestRepeatedSubstring.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LongestRepeatedSubstring.java 3 | * Execution: java LongestRepeatedSubstring < file.txt 4 | * Dependencies: StdIn.java SuffixArray.java 5 | * Data files: https://algs4.cs.princeton.edu/63suffix/tale.txt 6 | * https://algs4.cs.princeton.edu/63suffix/tinyTale.txt 7 | * https://algs4.cs.princeton.edu/63suffix/mobydick.txt 8 | * 9 | * Reads a text string from stdin, replaces all consecutive blocks of 10 | * whitespace with a single space, and then computes the longest 11 | * repeated substring in that text using a suffix array. 12 | * 13 | * % java LongestRepeatedSubstring < tinyTale.txt 14 | * 'st of times it was the ' 15 | * 16 | * % java LongestRepeatedSubstring < mobydick.txt 17 | * ',- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th' 18 | * 19 | * % java LongestRepeatedSubstring 20 | * aaaaaaaaa 21 | * 'aaaaaaaa' 22 | * 23 | * % java LongestRepeatedSubstring 24 | * abcdefg 25 | * '' 26 | * 27 | ******************************************************************************/ 28 | 29 | package edu.princeton.cs.algs4; 30 | 31 | /** 32 | * The {@code LongestRepeatedSubstring} class provides a {@link SuffixArray} 33 | * client for computing the longest repeated substring of a string that 34 | * appears at least twice. The repeated substrings may overlap (but must 35 | * be distinct). 36 | *

37 | * For additional documentation, 38 | * see Section 6.3 of 39 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 40 | *

41 | * See also {@link LongestCommonSubstring}. 42 | * 43 | * @author Robert Sedgewick 44 | * @author Kevin Wayne 45 | */ 46 | public class LongestRepeatedSubstring { 47 | 48 | // Do not instantiate. 49 | private LongestRepeatedSubstring() { } 50 | 51 | /** 52 | * Returns the longest common string of the two specified strings. 53 | * 54 | * @param s one string 55 | * @param t the other string 56 | * @return the longest common string that appears as a substring 57 | */ 58 | 59 | /** 60 | * Returns the longest repeated substring of the specified string. 61 | * 62 | * @param text the string 63 | * @return the longest repeated substring that appears in {@code text}; 64 | * the empty string if no such string 65 | */ 66 | public static String lrs(String text) { 67 | int n = text.length(); 68 | SuffixArray sa = new SuffixArray(text); 69 | String lrs = ""; 70 | for (int i = 1; i < n; i++) { 71 | int length = sa.lcp(i); 72 | if (length > lrs.length()) { 73 | // lrs = sa.select(i).substring(0, length); 74 | lrs = text.substring(sa.index(i), sa.index(i) + length); 75 | } 76 | } 77 | return lrs; 78 | } 79 | 80 | /** 81 | * Unit tests the {@code lrs()} method. 82 | * 83 | * @param args the command-line arguments 84 | */ 85 | public static void main(String[] args) { 86 | String text = StdIn.readAll().replaceAll("\\s+", " "); 87 | StdOut.println("'" + lrs(text) + "'"); 88 | } 89 | } 90 | 91 | /****************************************************************************** 92 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 93 | * 94 | * This file is part of algs4.jar, which accompanies the textbook 95 | * 96 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 97 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 98 | * http://algs4.cs.princeton.edu 99 | * 100 | * 101 | * algs4.jar is free software: you can redistribute it and/or modify 102 | * it under the terms of the GNU General Public License as published by 103 | * the Free Software Foundation, either version 3 of the License, or 104 | * (at your option) any later version. 105 | * 106 | * algs4.jar is distributed in the hope that it will be useful, 107 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 108 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 109 | * GNU General Public License for more details. 110 | * 111 | * You should have received a copy of the GNU General Public License 112 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 113 | ******************************************************************************/ 114 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LookupCSV.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LookupCSV.java 3 | * Execution: java LookupCSV file.csv keyField valField 4 | * Dependencies: ST.java In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/35applications/DJIA.csv 6 | * https://algs4.cs.princeton.edu/35applications/UPC.csv 7 | * https://algs4.cs.princeton.edu/35applications/amino.csv 8 | * https://algs4.cs.princeton.edu/35applications/elements.csv 9 | * https://algs4.cs.princeton.edu/35applications/ip.csv 10 | * https://algs4.cs.princeton.edu/35applications/morse.csv 11 | * 12 | * Reads in a set of key-value pairs from a two-column CSV file 13 | * specified on the command line; then, reads in keys from standard 14 | * input and prints out corresponding values. 15 | * 16 | * % java LookupCSV amino.csv 0 3 % java LookupCSV ip.csv 0 1 17 | * TTA www.google.com 18 | * Leucine 216.239.41.99 19 | * ABC 20 | * Not found % java LookupCSV ip.csv 1 0 21 | * TCT 216.239.41.99 22 | * Serine www.google.com 23 | * 24 | * % java LookupCSV amino.csv 3 0 % java LookupCSV DJIA.csv 0 1 25 | * Glycine 29-Oct-29 26 | * GGG 252.38 27 | * 20-Oct-87 28 | * 1738.74 29 | * 30 | * 31 | ******************************************************************************/ 32 | 33 | package edu.princeton.cs.algs4; 34 | 35 | /** 36 | * The {@code LookupCSV} class provides a data-driven client for reading in a 37 | * key-value pairs from a file; then, printing the values corresponding to the 38 | * keys found on standard input. Both keys and values are strings. 39 | * The fields to serve as the key and value are taken as command-line arguments. 40 | *

41 | * For additional documentation, see Section 3.5 of 42 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 43 | * 44 | * @author Robert Sedgewick 45 | * @author Kevin Wayne 46 | */ 47 | public class LookupCSV { 48 | 49 | // Do not instantiate. 50 | private LookupCSV() { } 51 | 52 | public static void main(String[] args) { 53 | int keyField = Integer.parseInt(args[1]); 54 | int valField = Integer.parseInt(args[2]); 55 | 56 | // symbol table 57 | ST st = new ST(); 58 | 59 | // read in the data from csv file 60 | In in = new In(args[0]); 61 | while (in.hasNextLine()) { 62 | String line = in.readLine(); 63 | String[] tokens = line.split(","); 64 | String key = tokens[keyField]; 65 | String val = tokens[valField]; 66 | st.put(key, val); 67 | } 68 | 69 | while (!StdIn.isEmpty()) { 70 | String s = StdIn.readString(); 71 | if (st.contains(s)) StdOut.println(st.get(s)); 72 | else StdOut.println("Not found"); 73 | } 74 | } 75 | } 76 | 77 | /****************************************************************************** 78 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 79 | * 80 | * This file is part of algs4.jar, which accompanies the textbook 81 | * 82 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 83 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 84 | * http://algs4.cs.princeton.edu 85 | * 86 | * 87 | * algs4.jar is free software: you can redistribute it and/or modify 88 | * it under the terms of the GNU General Public License as published by 89 | * the Free Software Foundation, either version 3 of the License, or 90 | * (at your option) any later version. 91 | * 92 | * algs4.jar is distributed in the hope that it will be useful, 93 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 94 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 95 | * GNU General Public License for more details. 96 | * 97 | * You should have received a copy of the GNU General Public License 98 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 99 | ******************************************************************************/ 100 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/FrequencyCounter.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac FrequencyCounter.java 3 | * Execution: java FrequencyCounter L < input.txt 4 | * Dependencies: ST.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/31elementary/tnyTale.txt 6 | * https://algs4.cs.princeton.edu/31elementary/tale.txt 7 | * https://algs4.cs.princeton.edu/31elementary/leipzig100K.txt 8 | * https://algs4.cs.princeton.edu/31elementary/leipzig300K.txt 9 | * https://algs4.cs.princeton.edu/31elementary/leipzig1M.txt 10 | * 11 | * Read in a list of words from standard input and print out 12 | * the most frequently occurring word that has length greater than 13 | * a given threshold. 14 | * 15 | * % java FrequencyCounter 1 < tinyTale.txt 16 | * it 10 17 | * 18 | * % java FrequencyCounter 8 < tale.txt 19 | * business 122 20 | * 21 | * % java FrequencyCounter 10 < leipzig1M.txt 22 | * government 24763 23 | * 24 | * 25 | ******************************************************************************/ 26 | 27 | package edu.princeton.cs.algs4; 28 | 29 | /** 30 | * The {@code FrequencyCounter} class provides a client for 31 | * reading in a sequence of words and printing a word (exceeding 32 | * a given length) that occurs most frequently. It is useful as 33 | * a test client for various symbol table implementations. 34 | *

35 | * For additional documentation, see Section 3.1 of 36 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | public class FrequencyCounter { 42 | 43 | // Do not instantiate. 44 | private FrequencyCounter() { } 45 | 46 | /** 47 | * Reads in a command-line integer and sequence of words from 48 | * standard input and prints out a word (whose length exceeds 49 | * the threshold) that occurs most frequently to standard output. 50 | * It also prints out the number of words whose length exceeds 51 | * the threshold and the number of distinct such words. 52 | * 53 | * @param args the command-line arguments 54 | */ 55 | public static void main(String[] args) { 56 | int distinct = 0, words = 0; 57 | int minlen = Integer.parseInt(args[0]); 58 | ST st = new ST(); 59 | 60 | // compute frequency counts 61 | while (!StdIn.isEmpty()) { 62 | String key = StdIn.readString(); 63 | if (key.length() < minlen) continue; 64 | words++; 65 | if (st.contains(key)) { 66 | st.put(key, st.get(key) + 1); 67 | } 68 | else { 69 | st.put(key, 1); 70 | distinct++; 71 | } 72 | } 73 | 74 | // find a key with the highest frequency count 75 | String max = ""; 76 | st.put(max, 0); 77 | for (String word : st.keys()) { 78 | if (st.get(word) > st.get(max)) 79 | max = word; 80 | } 81 | 82 | StdOut.println(max + " " + st.get(max)); 83 | StdOut.println("distinct = " + distinct); 84 | StdOut.println("words = " + words); 85 | } 86 | } 87 | 88 | /****************************************************************************** 89 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 90 | * 91 | * This file is part of algs4.jar, which accompanies the textbook 92 | * 93 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 94 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 95 | * http://algs4.cs.princeton.edu 96 | * 97 | * 98 | * algs4.jar is free software: you can redistribute it and/or modify 99 | * it under the terms of the GNU General Public License as published by 100 | * the Free Software Foundation, either version 3 of the License, or 101 | * (at your option) any later version. 102 | * 103 | * algs4.jar is distributed in the hope that it will be useful, 104 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 105 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 106 | * GNU General Public License for more details. 107 | * 108 | * You should have received a copy of the GNU General Public License 109 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 110 | ******************************************************************************/ 111 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Heap.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Heap.java 3 | * Execution: java Heap < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: https://algs4.cs.princeton.edu/24pq/tiny.txt 6 | * https://algs4.cs.princeton.edu/24pq/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using heapsort. 9 | * 10 | * % more tiny.txt 11 | * S O R T E X A M P L E 12 | * 13 | * % java Heap < tiny.txt 14 | * A E E L M O P R S T X [ one string per line ] 15 | * 16 | * % more words3.txt 17 | * bed bug dad yes zoo ... all bad yet 18 | * 19 | * % java Heap < words3.txt 20 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 21 | * 22 | ******************************************************************************/ 23 | 24 | package edu.princeton.cs.algs4; 25 | 26 | /** 27 | * The {@code Heap} class provides a static methods for heapsorting 28 | * an array. 29 | *

30 | * For additional documentation, see Section 2.4 of 31 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 32 | * 33 | * @author Robert Sedgewick 34 | * @author Kevin Wayne 35 | */ 36 | public class Heap { 37 | 38 | // This class should not be instantiated. 39 | private Heap() { } 40 | 41 | /** 42 | * Rearranges the array in ascending order, using the natural order. 43 | * @param pq the array to be sorted 44 | */ 45 | public static void sort(Comparable[] pq) { 46 | int n = pq.length; 47 | for (int k = n/2; k >= 1; k--) 48 | sink(pq, k, n); 49 | while (n > 1) { 50 | exch(pq, 1, n--); 51 | sink(pq, 1, n); 52 | } 53 | } 54 | 55 | /*************************************************************************** 56 | * Helper functions to restore the heap invariant. 57 | ***************************************************************************/ 58 | 59 | private static void sink(Comparable[] pq, int k, int n) { 60 | while (2*k <= n) { 61 | int j = 2*k; 62 | if (j < n && less(pq, j, j+1)) j++; 63 | if (!less(pq, k, j)) break; 64 | exch(pq, k, j); 65 | k = j; 66 | } 67 | } 68 | 69 | /*************************************************************************** 70 | * Helper functions for comparisons and swaps. 71 | * Indices are "off-by-one" to support 1-based indexing. 72 | ***************************************************************************/ 73 | private static boolean less(Comparable[] pq, int i, int j) { 74 | return pq[i-1].compareTo(pq[j-1]) < 0; 75 | } 76 | 77 | private static void exch(Object[] pq, int i, int j) { 78 | Object swap = pq[i-1]; 79 | pq[i-1] = pq[j-1]; 80 | pq[j-1] = swap; 81 | } 82 | 83 | // print array to standard output 84 | private static void show(Comparable[] a) { 85 | for (int i = 0; i < a.length; i++) { 86 | StdOut.println(a[i]); 87 | } 88 | } 89 | 90 | /** 91 | * Reads in a sequence of strings from standard input; heapsorts them; 92 | * and prints them to standard output in ascending order. 93 | * 94 | * @param args the command-line arguments 95 | */ 96 | public static void main(String[] args) { 97 | String[] a = StdIn.readAllStrings(); 98 | Heap.sort(a); 99 | show(a); 100 | } 101 | } 102 | 103 | /****************************************************************************** 104 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 105 | * 106 | * This file is part of algs4.jar, which accompanies the textbook 107 | * 108 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 109 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 110 | * http://algs4.cs.princeton.edu 111 | * 112 | * 113 | * algs4.jar is free software: you can redistribute it and/or modify 114 | * it under the terms of the GNU General Public License as published by 115 | * the Free Software Foundation, either version 3 of the License, or 116 | * (at your option) any later version. 117 | * 118 | * algs4.jar is distributed in the hope that it will be useful, 119 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 120 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 121 | * GNU General Public License for more details. 122 | * 123 | * You should have received a copy of the GNU General Public License 124 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 125 | ******************************************************************************/ 126 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/CPM.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac CPM.java 3 | * Execution: java CPM < input.txt 4 | * Dependencies: EdgeWeightedDigraph.java AcyclicDigraphLP.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/44sp/jobsPC.txt 6 | * 7 | * Critical path method. 8 | * 9 | * % java CPM < jobsPC.txt 10 | * job start finish 11 | * -------------------- 12 | * 0 0.0 41.0 13 | * 1 41.0 92.0 14 | * 2 123.0 173.0 15 | * 3 91.0 127.0 16 | * 4 70.0 108.0 17 | * 5 0.0 45.0 18 | * 6 70.0 91.0 19 | * 7 41.0 73.0 20 | * 8 91.0 123.0 21 | * 9 41.0 70.0 22 | * Finish time: 173.0 23 | * 24 | ******************************************************************************/ 25 | 26 | package edu.princeton.cs.algs4; 27 | 28 | /** 29 | * The {@code CPM} class provides a client that solves the 30 | * parallel precedence-constrained job scheduling problem 31 | * via the critical path method. It reduces the problem 32 | * to the longest-paths problem in edge-weighted DAGs. 33 | * It builds an edge-weighted digraph (which must be a DAG) 34 | * from the job-scheduling problem specification, 35 | * finds the longest-paths tree, and computes the longest-paths 36 | * lengths (which are precisely the start times for each job). 37 | *

38 | * This implementation uses {@link AcyclicLP} to find a longest 39 | * path in a DAG. 40 | * The running time is proportional to V + E, 41 | * where V is the number of jobs and E is the 42 | * number of precedence constraints. 43 | *

44 | * For additional documentation, 45 | * see Section 4.4 of 46 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 47 | * 48 | * @author Robert Sedgewick 49 | * @author Kevin Wayne 50 | */ 51 | public class CPM { 52 | 53 | // this class cannot be instantiated 54 | private CPM() { } 55 | 56 | /** 57 | * Reads the precedence constraints from standard input 58 | * and prints a feasible schedule to standard output. 59 | * 60 | * @param args the command-line arguments 61 | */ 62 | public static void main(String[] args) { 63 | 64 | // number of jobs 65 | int n = StdIn.readInt(); 66 | 67 | // source and sink 68 | int source = 2*n; 69 | int sink = 2*n + 1; 70 | 71 | // build network 72 | EdgeWeightedDigraph G = new EdgeWeightedDigraph(2*n + 2); 73 | for (int i = 0; i < n; i++) { 74 | double duration = StdIn.readDouble(); 75 | G.addEdge(new DirectedEdge(source, i, 0.0)); 76 | G.addEdge(new DirectedEdge(i+n, sink, 0.0)); 77 | G.addEdge(new DirectedEdge(i, i+n, duration)); 78 | 79 | // precedence constraints 80 | int m = StdIn.readInt(); 81 | for (int j = 0; j < m; j++) { 82 | int precedent = StdIn.readInt(); 83 | G.addEdge(new DirectedEdge(n+i, precedent, 0.0)); 84 | } 85 | } 86 | 87 | // compute longest path 88 | AcyclicLP lp = new AcyclicLP(G, source); 89 | 90 | // print results 91 | StdOut.println(" job start finish"); 92 | StdOut.println("--------------------"); 93 | for (int i = 0; i < n; i++) { 94 | StdOut.printf("%4d %7.1f %7.1f\n", i, lp.distTo(i), lp.distTo(i+n)); 95 | } 96 | StdOut.printf("Finish time: %7.1f\n", lp.distTo(sink)); 97 | } 98 | 99 | } 100 | 101 | /****************************************************************************** 102 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 103 | * 104 | * This file is part of algs4.jar, which accompanies the textbook 105 | * 106 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 107 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 108 | * http://algs4.cs.princeton.edu 109 | * 110 | * 111 | * algs4.jar is free software: you can redistribute it and/or modify 112 | * it under the terms of the GNU General Public License as published by 113 | * the Free Software Foundation, either version 3 of the License, or 114 | * (at your option) any later version. 115 | * 116 | * algs4.jar is distributed in the hope that it will be useful, 117 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 118 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 119 | * GNU General Public License for more details. 120 | * 121 | * You should have received a copy of the GNU General Public License 122 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 123 | ******************************************************************************/ 124 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/RunLength.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac RunLength.java 3 | * Execution: java RunLength - < input.txt (compress) 4 | * Execution: java RunLength + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * Data files: https://algs4.cs.princeton.edu/55compression/4runs.bin 7 | * https://algs4.cs.princeton.edu/55compression/q32x48.bin 8 | * https://algs4.cs.princeton.edu/55compression/q64x96.bin 9 | * 10 | * Compress or expand binary input from standard input using 11 | * run-length encoding. 12 | * 13 | * % java BinaryDump 40 < 4runs.bin 14 | * 0000000000000001111111000000011111111111 15 | * 40 bits 16 | * 17 | * This has runs of 15 0s, 7 1s, 7 0s, and 11 1s. 18 | * 19 | * % java RunLength - < 4runs.bin | java HexDump 20 | * 0f 07 07 0b 21 | * 4 bytes 22 | * 23 | ******************************************************************************/ 24 | 25 | package edu.princeton.cs.algs4; 26 | 27 | /** 28 | * The {@code RunLength} class provides static methods for compressing 29 | * and expanding a binary input using run-length coding with 8-bit 30 | * run lengths. 31 | *

32 | * For additional documentation, 33 | * see Section 5.5 of 34 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 35 | * 36 | * @author Robert Sedgewick 37 | * @author Kevin Wayne 38 | */ 39 | public class RunLength { 40 | private static final int R = 256; 41 | private static final int LG_R = 8; 42 | 43 | // Do not instantiate. 44 | private RunLength() { } 45 | 46 | /** 47 | * Reads a sequence of bits from standard input (that are encoded 48 | * using run-length encoding with 8-bit run lengths); decodes them; 49 | * and writes the results to standard output. 50 | */ 51 | public static void expand() { 52 | boolean b = false; 53 | while (!BinaryStdIn.isEmpty()) { 54 | int run = BinaryStdIn.readInt(LG_R); 55 | for (int i = 0; i < run; i++) 56 | BinaryStdOut.write(b); 57 | b = !b; 58 | } 59 | BinaryStdOut.close(); 60 | } 61 | 62 | /** 63 | * Reads a sequence of bits from standard input; compresses 64 | * them using run-length coding with 8-bit run lengths; and writes the 65 | * results to standard output. 66 | */ 67 | public static void compress() { 68 | char run = 0; 69 | boolean old = false; 70 | while (!BinaryStdIn.isEmpty()) { 71 | boolean b = BinaryStdIn.readBoolean(); 72 | if (b != old) { 73 | BinaryStdOut.write(run, LG_R); 74 | run = 1; 75 | old = !old; 76 | } 77 | else { 78 | if (run == R-1) { 79 | BinaryStdOut.write(run, LG_R); 80 | run = 0; 81 | BinaryStdOut.write(run, LG_R); 82 | } 83 | run++; 84 | } 85 | } 86 | BinaryStdOut.write(run, LG_R); 87 | BinaryStdOut.close(); 88 | } 89 | 90 | 91 | /** 92 | * Sample client that calls {@code compress()} if the command-line 93 | * argument is "-" an {@code expand()} if it is "+". 94 | * 95 | * @param args the command-line arguments 96 | */ 97 | public static void main(String[] args) { 98 | if (args[0].equals("-")) compress(); 99 | else if (args[0].equals("+")) expand(); 100 | else throw new IllegalArgumentException("Illegal command line argument"); 101 | } 102 | 103 | } 104 | 105 | /****************************************************************************** 106 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 107 | * 108 | * This file is part of algs4.jar, which accompanies the textbook 109 | * 110 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 111 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 112 | * http://algs4.cs.princeton.edu 113 | * 114 | * 115 | * algs4.jar is free software: you can redistribute it and/or modify 116 | * it under the terms of the GNU General Public License as published by 117 | * the Free Software Foundation, either version 3 of the License, or 118 | * (at your option) any later version. 119 | * 120 | * algs4.jar is distributed in the hope that it will be useful, 121 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 122 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 123 | * GNU General Public License for more details. 124 | * 125 | * You should have received a copy of the GNU General Public License 126 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 127 | ******************************************************************************/ 128 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/KWIK.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac KWIK.java 3 | * Execution: java KWIK file.txt 4 | * Dependencies: StdIn.java StdOut.java In.java SuffixArray.java 5 | * Data files: https://algs4.cs.princeton.edu/63suffix/tale.txt 6 | * https://algs4.cs.princeton.edu/63suffix/mobydick.txt 7 | * 8 | * Keyword-in-context search. 9 | * 10 | * % java KWIK tale.txt 15 11 | * majesty 12 | * most gracious majesty king george th 13 | * rnkeys and the majesty of the law fir 14 | * on against the majesty of the people 15 | * se them to his majestys chief secreta 16 | * h lists of his majestys forces and of 17 | * 18 | * the worst 19 | * w the best and the worst are known to y 20 | * f them give me the worst first there th 21 | * for in case of the worst is a friend in 22 | * e roomdoor and the worst is over then a 23 | * pect mr darnay the worst its the wisest 24 | * is his brother the worst of a bad race 25 | * ss in them for the worst of health for 26 | * you have seen the worst of her agitati 27 | * cumwented into the worst of luck buuust 28 | * n your brother the worst of the bad rac 29 | * full share in the worst of the day pla 30 | * mes to himself the worst of the strife 31 | * f times it was the worst of times it wa 32 | * ould hope that the worst was over well 33 | * urage business the worst will be over i 34 | * clesiastics of the worst world worldly 35 | * 36 | ******************************************************************************/ 37 | 38 | package edu.princeton.cs.algs4; 39 | 40 | /** 41 | * The {@code KWIK} class provides a {@link SuffixArray} client for computing 42 | * all occurrences of a keyword in a given string, with surrounding context. 43 | * This is known as keyword-in-context search. 44 | *

45 | * For additional documentation, 46 | * see Section 6.3 of 47 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 48 | * 49 | * @author Robert Sedgewick 50 | * @author Kevin Wayne 51 | */ 52 | public class KWIK { 53 | 54 | // Do not instantiate. 55 | private KWIK() { } 56 | 57 | /** 58 | * Reads a string from a file specified as the first 59 | * command-line argument; read an integer k specified as the 60 | * second command line argument; then repeatedly processes 61 | * use queries, printing all occurrences of the given query 62 | * string in the text string with k characters of surrounding 63 | * context on either side. 64 | * 65 | * @param args the command-line arguments 66 | */ 67 | public static void main(String[] args) { 68 | In in = new In(args[0]); 69 | int context = Integer.parseInt(args[1]); 70 | 71 | // read in text 72 | String text = in.readAll().replaceAll("\\s+", " "); 73 | int n = text.length(); 74 | 75 | // build suffix array 76 | SuffixArray sa = new SuffixArray(text); 77 | 78 | // find all occurrences of queries and give context 79 | while (StdIn.hasNextLine()) { 80 | String query = StdIn.readLine(); 81 | for (int i = sa.rank(query); i < n; i++) { 82 | int from1 = sa.index(i); 83 | int to1 = Math.min(n, from1 + query.length()); 84 | if (!query.equals(text.substring(from1, to1))) break; 85 | int from2 = Math.max(0, sa.index(i) - context); 86 | int to2 = Math.min(n, sa.index(i) + context + query.length()); 87 | StdOut.println(text.substring(from2, to2)); 88 | } 89 | StdOut.println(); 90 | } 91 | } 92 | } 93 | 94 | /****************************************************************************** 95 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 96 | * 97 | * This file is part of algs4.jar, which accompanies the textbook 98 | * 99 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 100 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 101 | * http://algs4.cs.princeton.edu 102 | * 103 | * 104 | * algs4.jar is free software: you can redistribute it and/or modify 105 | * it under the terms of the GNU General Public License as published by 106 | * the Free Software Foundation, either version 3 of the License, or 107 | * (at your option) any later version. 108 | * 109 | * algs4.jar is distributed in the hope that it will be useful, 110 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 111 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 112 | * GNU General Public License for more details. 113 | * 114 | * You should have received a copy of the GNU General Public License 115 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 116 | ******************************************************************************/ 117 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Counter.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Counter.java 3 | * Execution: java Counter n trials 4 | * Dependencies: StdRandom.java StdOut.java 5 | * 6 | * A mutable data type for an integer counter. 7 | * 8 | * The test clients create n counters and performs trials increment 9 | * operations on random counters. 10 | * 11 | * java Counter 6 600000 12 | * 100140 counter0 13 | * 100273 counter1 14 | * 99848 counter2 15 | * 100129 counter3 16 | * 99973 counter4 17 | * 99637 counter5 18 | * 19 | ******************************************************************************/ 20 | 21 | package edu.princeton.cs.algs4; 22 | 23 | /** 24 | * The {@code Counter} class is a mutable data type to encapsulate a counter. 25 | *

26 | * For additional documentation, 27 | * see Section 1.2 of 28 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 29 | * 30 | * @author Robert Sedgewick 31 | * @author Kevin Wayne 32 | */ 33 | public class Counter implements Comparable { 34 | 35 | private final String name; // counter name 36 | private int count = 0; // current value 37 | 38 | /** 39 | * Initializes a new counter starting at 0, with the given id. 40 | * 41 | * @param id the name of the counter 42 | */ 43 | public Counter(String id) { 44 | name = id; 45 | } 46 | 47 | /** 48 | * Increments the counter by 1. 49 | */ 50 | public void increment() { 51 | count++; 52 | } 53 | 54 | /** 55 | * Returns the current value of this counter. 56 | * 57 | * @return the current value of this counter 58 | */ 59 | public int tally() { 60 | return count; 61 | } 62 | 63 | /** 64 | * Returns a string representation of this counter. 65 | * 66 | * @return a string representation of this counter 67 | */ 68 | public String toString() { 69 | return count + " " + name; 70 | } 71 | 72 | /** 73 | * Compares this counter to the specified counter. 74 | * 75 | * @param that the other counter 76 | * @return {@code 0} if the value of this counter equals 77 | * the value of that counter; a negative integer if 78 | * the value of this counter is less than the value of 79 | * that counter; and a positive integer if the value 80 | * of this counter is greater than the value of that 81 | * counter 82 | */ 83 | @Override 84 | public int compareTo(Counter that) { 85 | if (this.count < that.count) return -1; 86 | else if (this.count > that.count) return +1; 87 | else return 0; 88 | } 89 | 90 | 91 | /** 92 | * Reads two command-line integers n and trials; creates n counters; 93 | * increments trials counters at random; and prints results. 94 | * 95 | * @param args the command-line arguments 96 | */ 97 | public static void main(String[] args) { 98 | int n = Integer.parseInt(args[0]); 99 | int trials = Integer.parseInt(args[1]); 100 | 101 | // create n counters 102 | Counter[] hits = new Counter[n]; 103 | for (int i = 0; i < n; i++) { 104 | hits[i] = new Counter("counter" + i); 105 | } 106 | 107 | // increment trials counters at random 108 | for (int t = 0; t < trials; t++) { 109 | hits[StdRandom.uniform(n)].increment(); 110 | } 111 | 112 | // print results 113 | for (int i = 0; i < n; i++) { 114 | StdOut.println(hits[i]); 115 | } 116 | } 117 | } 118 | 119 | /****************************************************************************** 120 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 121 | * 122 | * This file is part of algs4.jar, which accompanies the textbook 123 | * 124 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 125 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 126 | * http://algs4.cs.princeton.edu 127 | * 128 | * 129 | * algs4.jar is free software: you can redistribute it and/or modify 130 | * it under the terms of the GNU General Public License as published by 131 | * the Free Software Foundation, either version 3 of the License, or 132 | * (at your option) any later version. 133 | * 134 | * algs4.jar is distributed in the hope that it will be useful, 135 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 136 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 137 | * GNU General Public License for more details. 138 | * 139 | * You should have received a copy of the GNU General Public License 140 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 141 | ******************************************************************************/ 142 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/BinarySearch.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac BinarySearch.java 3 | * Execution: java BinarySearch whitelist.txt < input.txt 4 | * Dependencies: In.java StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/11model/tinyW.txt 6 | * https://algs4.cs.princeton.edu/11model/tinyT.txt 7 | * https://algs4.cs.princeton.edu/11model/largeW.txt 8 | * https://algs4.cs.princeton.edu/11model/largeT.txt 9 | * 10 | * % java BinarySearch tinyW.txt < tinyT.txt 11 | * 50 12 | * 99 13 | * 13 14 | * 15 | * % java BinarySearch largeW.txt < largeT.txt | more 16 | * 499569 17 | * 984875 18 | * 295754 19 | * 207807 20 | * 140925 21 | * 161828 22 | * [367,966 total values] 23 | * 24 | ******************************************************************************/ 25 | 26 | package edu.princeton.cs.algs4; 27 | 28 | import java.util.Arrays; 29 | 30 | /** 31 | * The {@code BinarySearch} class provides a static method for binary 32 | * searching for an integer in a sorted array of integers. 33 | *

34 | * The indexOf operations takes logarithmic time in the worst case. 35 | *

36 | * For additional documentation, see Section 1.1 of 37 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 38 | * 39 | * @author Robert Sedgewick 40 | * @author Kevin Wayne 41 | */ 42 | public class BinarySearch { 43 | 44 | /** 45 | * This class should not be instantiated. 46 | */ 47 | private BinarySearch() { } 48 | 49 | /** 50 | * Returns the index of the specified key in the specified array. 51 | * 52 | * @param a the array of integers, must be sorted in ascending order 53 | * @param key the search key 54 | * @return index of key in array {@code a} if present; {@code -1} otherwise 55 | */ 56 | public static int indexOf(int[] a, int key) { 57 | int lo = 0; 58 | int hi = a.length - 1; 59 | while (lo <= hi) { 60 | // Key is in a[lo..hi] or not present. 61 | int mid = lo + (hi - lo) / 2; 62 | if (key < a[mid]) hi = mid - 1; 63 | else if (key > a[mid]) lo = mid + 1; 64 | else return mid; 65 | } 66 | return -1; 67 | } 68 | 69 | /** 70 | * Returns the index of the specified key in the specified array. 71 | * This function is poorly named because it does not give the rank 72 | * if the array has duplicate keys or if the key is not in the array. 73 | * 74 | * @param key the search key 75 | * @param a the array of integers, must be sorted in ascending order 76 | * @return index of key in array {@code a} if present; {@code -1} otherwise 77 | * @deprecated Replaced by {@link #indexOf(int[], int)}. 78 | */ 79 | @Deprecated 80 | public static int rank(int key, int[] a) { 81 | return indexOf(a, key); 82 | } 83 | 84 | /** 85 | * Reads in a sequence of integers from the whitelist file, specified as 86 | * a command-line argument; reads in integers from standard input; 87 | * prints to standard output those integers that do not appear in the file. 88 | * 89 | * @param args the command-line arguments 90 | */ 91 | public static void main(String[] args) { 92 | 93 | // read the integers from a file 94 | In in = new In(args[0]); 95 | int[] whitelist = in.readAllInts(); 96 | 97 | // sort the array 98 | Arrays.sort(whitelist); 99 | 100 | // read integer key from standard input; print if not in whitelist 101 | while (!StdIn.isEmpty()) { 102 | int key = StdIn.readInt(); 103 | if (BinarySearch.indexOf(whitelist, key) == -1) 104 | StdOut.println(key); 105 | } 106 | } 107 | } 108 | 109 | /****************************************************************************** 110 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 111 | * 112 | * This file is part of algs4.jar, which accompanies the textbook 113 | * 114 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 115 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 116 | * http://algs4.cs.princeton.edu 117 | * 118 | * 119 | * algs4.jar is free software: you can redistribute it and/or modify 120 | * it under the terms of the GNU General Public License as published by 121 | * the Free Software Foundation, either version 3 of the License, or 122 | * (at your option) any later version. 123 | * 124 | * algs4.jar is distributed in the hope that it will be useful, 125 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 126 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 127 | * GNU General Public License for more details. 128 | * 129 | * You should have received a copy of the GNU General Public License 130 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 131 | ******************************************************************************/ 132 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/ThreeSum.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac ThreeSum.java 3 | * Execution: java ThreeSum input.txt 4 | * Dependencies: In.java StdOut.java Stopwatch.java 5 | * Data files: https://algs4.cs.princeton.edu/14analysis/1Kints.txt 6 | * https://algs4.cs.princeton.edu/14analysis/2Kints.txt 7 | * https://algs4.cs.princeton.edu/14analysis/4Kints.txt 8 | * https://algs4.cs.princeton.edu/14analysis/8Kints.txt 9 | * https://algs4.cs.princeton.edu/14analysis/16Kints.txt 10 | * https://algs4.cs.princeton.edu/14analysis/32Kints.txt 11 | * https://algs4.cs.princeton.edu/14analysis/1Mints.txt 12 | * 13 | * A program with cubic running time. Reads n integers 14 | * and counts the number of triples that sum to exactly 0 15 | * (ignoring integer overflow). 16 | * 17 | * % java ThreeSum 1Kints.txt 18 | * 70 19 | * 20 | * % java ThreeSum 2Kints.txt 21 | * 528 22 | * 23 | * % java ThreeSum 4Kints.txt 24 | * 4039 25 | * 26 | ******************************************************************************/ 27 | 28 | package edu.princeton.cs.algs4; 29 | 30 | /** 31 | * The {@code ThreeSum} class provides static methods for counting 32 | * and printing the number of triples in an array of integers that sum to 0 33 | * (ignoring integer overflow). 34 | *

35 | * This implementation uses a triply nested loop and takes proportional to n^3, 36 | * where n is the number of integers. 37 | *

38 | * For additional documentation, see Section 1.4 of 39 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 40 | * 41 | * @author Robert Sedgewick 42 | * @author Kevin Wayne 43 | */ 44 | public class ThreeSum { 45 | 46 | // Do not instantiate. 47 | private ThreeSum() { } 48 | 49 | /** 50 | * Prints to standard output the (i, j, k) with {@code i < j < k} 51 | * such that {@code a[i] + a[j] + a[k] == 0}. 52 | * 53 | * @param a the array of integers 54 | */ 55 | public static void printAll(int[] a) { 56 | int n = a.length; 57 | for (int i = 0; i < n; i++) { 58 | for (int j = i+1; j < n; j++) { 59 | for (int k = j+1; k < n; k++) { 60 | if (a[i] + a[j] + a[k] == 0) { 61 | StdOut.println(a[i] + " " + a[j] + " " + a[k]); 62 | } 63 | } 64 | } 65 | } 66 | } 67 | 68 | /** 69 | * Returns the number of triples (i, j, k) with {@code i < j < k} 70 | * such that {@code a[i] + a[j] + a[k] == 0}. 71 | * 72 | * @param a the array of integers 73 | * @return the number of triples (i, j, k) with {@code i < j < k} 74 | * such that {@code a[i] + a[j] + a[k] == 0} 75 | */ 76 | public static int count(int[] a) { 77 | int n = a.length; 78 | int count = 0; 79 | for (int i = 0; i < n; i++) { 80 | for (int j = i+1; j < n; j++) { 81 | for (int k = j+1; k < n; k++) { 82 | if (a[i] + a[j] + a[k] == 0) { 83 | count++; 84 | } 85 | } 86 | } 87 | } 88 | return count; 89 | } 90 | 91 | /** 92 | * Reads in a sequence of integers from a file, specified as a command-line argument; 93 | * counts the number of triples sum to exactly zero; prints out the time to perform 94 | * the computation. 95 | * 96 | * @param args the command-line arguments 97 | */ 98 | public static void main(String[] args) { 99 | In in = new In(args[0]); 100 | int[] a = in.readAllInts(); 101 | 102 | Stopwatch timer = new Stopwatch(); 103 | int count = count(a); 104 | StdOut.println("elapsed time = " + timer.elapsedTime()); 105 | StdOut.println(count); 106 | } 107 | } 108 | 109 | /****************************************************************************** 110 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 111 | * 112 | * This file is part of algs4.jar, which accompanies the textbook 113 | * 114 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 115 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 116 | * http://algs4.cs.princeton.edu 117 | * 118 | * 119 | * algs4.jar is free software: you can redistribute it and/or modify 120 | * it under the terms of the GNU General Public License as published by 121 | * the Free Software Foundation, either version 3 of the License, or 122 | * (at your option) any later version. 123 | * 124 | * algs4.jar is distributed in the hope that it will be useful, 125 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 126 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 127 | * GNU General Public License for more details. 128 | * 129 | * You should have received a copy of the GNU General Public License 130 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 131 | ******************************************************************************/ 132 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/ResizingArrayBag.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac ResizingArrayBag.java 3 | * Execution: java ResizingArrayBag 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * Bag implementation with a resizing array. 7 | * 8 | ******************************************************************************/ 9 | 10 | package edu.princeton.cs.algs4; 11 | 12 | import java.util.Iterator; 13 | import java.util.NoSuchElementException; 14 | 15 | /** 16 | * The {@code ResizingArrayBag} class represents a bag (or multiset) of 17 | * generic items. It supports insertion and iterating over the 18 | * items in arbitrary order. 19 | *

20 | * This implementation uses a resizing array. 21 | * See {@link LinkedBag} for a version that uses a singly linked list. 22 | * The add operation takes constant amortized time; the 23 | * isEmpty, and size operations 24 | * take constant time. Iteration takes time proportional to the number of items. 25 | *

26 | * For additional documentation, see Section 1.3 of 27 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 28 | * 29 | * @author Robert Sedgewick 30 | * @author Kevin Wayne 31 | */ 32 | public class ResizingArrayBag implements Iterable { 33 | private Item[] a; // array of items 34 | private int n; // number of elements on bag 35 | 36 | /** 37 | * Initializes an empty bag. 38 | */ 39 | public ResizingArrayBag() { 40 | a = (Item[]) new Object[2]; 41 | n = 0; 42 | } 43 | 44 | /** 45 | * Is this bag empty? 46 | * @return true if this bag is empty; false otherwise 47 | */ 48 | public boolean isEmpty() { 49 | return n == 0; 50 | } 51 | 52 | /** 53 | * Returns the number of items in this bag. 54 | * @return the number of items in this bag 55 | */ 56 | public int size() { 57 | return n; 58 | } 59 | 60 | // resize the underlying array holding the elements 61 | private void resize(int capacity) { 62 | assert capacity >= n; 63 | Item[] temp = (Item[]) new Object[capacity]; 64 | for (int i = 0; i < n; i++) 65 | temp[i] = a[i]; 66 | a = temp; 67 | } 68 | 69 | /** 70 | * Adds the item to this bag. 71 | * @param item the item to add to this bag 72 | */ 73 | public void add(Item item) { 74 | if (n == a.length) resize(2*a.length); // double size of array if necessary 75 | a[n++] = item; // add item 76 | } 77 | 78 | 79 | /** 80 | * Returns an iterator that iterates over the items in the bag in arbitrary order. 81 | * @return an iterator that iterates over the items in the bag in arbitrary order 82 | */ 83 | public Iterator iterator() { 84 | return new ArrayIterator(); 85 | } 86 | 87 | // an iterator, doesn't implement remove() since it's optional 88 | private class ArrayIterator implements Iterator { 89 | private int i = 0; 90 | public boolean hasNext() { return i < n; } 91 | public void remove() { throw new UnsupportedOperationException(); } 92 | 93 | public Item next() { 94 | if (!hasNext()) throw new NoSuchElementException(); 95 | return a[i++]; 96 | } 97 | } 98 | 99 | /** 100 | * Unit tests the {@code ResizingArrayBag} data type. 101 | * 102 | * @param args the command-line arguments 103 | */ 104 | public static void main(String[] args) { 105 | ResizingArrayBag bag = new ResizingArrayBag(); 106 | bag.add("Hello"); 107 | bag.add("World"); 108 | bag.add("how"); 109 | bag.add("are"); 110 | bag.add("you"); 111 | 112 | for (String s : bag) 113 | StdOut.println(s); 114 | } 115 | 116 | } 117 | 118 | /****************************************************************************** 119 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 120 | * 121 | * This file is part of algs4.jar, which accompanies the textbook 122 | * 123 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 124 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 125 | * http://algs4.cs.princeton.edu 126 | * 127 | * 128 | * algs4.jar is free software: you can redistribute it and/or modify 129 | * it under the terms of the GNU General Public License as published by 130 | * the Free Software Foundation, either version 3 of the License, or 131 | * (at your option) any later version. 132 | * 133 | * algs4.jar is distributed in the hope that it will be useful, 134 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 135 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 136 | * GNU General Public License for more details. 137 | * 138 | * You should have received a copy of the GNU General Public License 139 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 140 | ******************************************************************************/ 141 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Edge.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Edge.java 3 | * Execution: java Edge 4 | * Dependencies: StdOut.java 5 | * 6 | * Immutable weighted edge. 7 | * 8 | ******************************************************************************/ 9 | 10 | package edu.princeton.cs.algs4; 11 | 12 | /** 13 | * The {@code Edge} class represents a weighted edge in an 14 | * {@link EdgeWeightedGraph}. Each edge consists of two integers 15 | * (naming the two vertices) and a real-value weight. The data type 16 | * provides methods for accessing the two endpoints of the edge and 17 | * the weight. The natural order for this data type is by 18 | * ascending order of weight. 19 | *

20 | * For additional documentation, see Section 4.3 of 21 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 22 | * 23 | * @author Robert Sedgewick 24 | * @author Kevin Wayne 25 | */ 26 | public class Edge implements Comparable { 27 | 28 | private final int v; 29 | private final int w; 30 | private final double weight; 31 | 32 | /** 33 | * Initializes an edge between vertices {@code v} and {@code w} of 34 | * the given {@code weight}. 35 | * 36 | * @param v one vertex 37 | * @param w the other vertex 38 | * @param weight the weight of this edge 39 | * @throws IllegalArgumentException if either {@code v} or {@code w} 40 | * is a negative integer 41 | * @throws IllegalArgumentException if {@code weight} is {@code NaN} 42 | */ 43 | public Edge(int v, int w, double weight) { 44 | if (v < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer"); 45 | if (w < 0) throw new IllegalArgumentException("vertex index must be a nonnegative integer"); 46 | if (Double.isNaN(weight)) throw new IllegalArgumentException("Weight is NaN"); 47 | this.v = v; 48 | this.w = w; 49 | this.weight = weight; 50 | } 51 | 52 | /** 53 | * Returns the weight of this edge. 54 | * 55 | * @return the weight of this edge 56 | */ 57 | public double weight() { 58 | return weight; 59 | } 60 | 61 | /** 62 | * Returns either endpoint of this edge. 63 | * 64 | * @return either endpoint of this edge 65 | */ 66 | public int either() { 67 | return v; 68 | } 69 | 70 | /** 71 | * Returns the endpoint of this edge that is different from the given vertex. 72 | * 73 | * @param vertex one endpoint of this edge 74 | * @return the other endpoint of this edge 75 | * @throws IllegalArgumentException if the vertex is not one of the 76 | * endpoints of this edge 77 | */ 78 | public int other(int vertex) { 79 | if (vertex == v) return w; 80 | else if (vertex == w) return v; 81 | else throw new IllegalArgumentException("Illegal endpoint"); 82 | } 83 | 84 | /** 85 | * Compares two edges by weight. 86 | * Note that {@code compareTo()} is not consistent with {@code equals()}, 87 | * which uses the reference equality implementation inherited from {@code Object}. 88 | * 89 | * @param that the other edge 90 | * @return a negative integer, zero, or positive integer depending on whether 91 | * the weight of this is less than, equal to, or greater than the 92 | * argument edge 93 | */ 94 | @Override 95 | public int compareTo(Edge that) { 96 | return Double.compare(this.weight, that.weight); 97 | } 98 | 99 | /** 100 | * Returns a string representation of this edge. 101 | * 102 | * @return a string representation of this edge 103 | */ 104 | public String toString() { 105 | return String.format("%d-%d %.5f", v, w, weight); 106 | } 107 | 108 | /** 109 | * Unit tests the {@code Edge} data type. 110 | * 111 | * @param args the command-line arguments 112 | */ 113 | public static void main(String[] args) { 114 | Edge e = new Edge(12, 34, 5.67); 115 | StdOut.println(e); 116 | } 117 | } 118 | 119 | /****************************************************************************** 120 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 121 | * 122 | * This file is part of algs4.jar, which accompanies the textbook 123 | * 124 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 125 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 126 | * http://algs4.cs.princeton.edu 127 | * 128 | * 129 | * algs4.jar is free software: you can redistribute it and/or modify 130 | * it under the terms of the GNU General Public License as published by 131 | * the Free Software Foundation, either version 3 of the License, or 132 | * (at your option) any later version. 133 | * 134 | * algs4.jar is distributed in the hope that it will be useful, 135 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 136 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 137 | * GNU General Public License for more details. 138 | * 139 | * You should have received a copy of the GNU General Public License 140 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 141 | ******************************************************************************/ 142 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/InsertionX.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac InsertionX.java 3 | * Execution: java InsertionX < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt 6 | * https://algs4.cs.princeton.edu/21elementary/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using an optimized 9 | * version of insertion sort that uses half exchanges instead of 10 | * full exchanges to reduce data movement.. 11 | * 12 | * % more tiny.txt 13 | * S O R T E X A M P L E 14 | * 15 | * % java InsertionX < tiny.txt 16 | * A E E L M O P R S T X [ one string per line ] 17 | * 18 | * % more words3.txt 19 | * bed bug dad yes zoo ... all bad yet 20 | * 21 | * % java InsertionX < words3.txt 22 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 23 | * 24 | ******************************************************************************/ 25 | 26 | package edu.princeton.cs.algs4; 27 | /** 28 | * The {@code InsertionX} class provides static methods for sorting 29 | * an array using an optimized version of insertion sort (with half exchanges 30 | * and a sentinel). 31 | *

32 | * For additional documentation, see Section 2.1 of 33 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 34 | * 35 | * @author Robert Sedgewick 36 | * @author Kevin Wayne 37 | */ 38 | 39 | public class InsertionX { 40 | 41 | // This class should not be instantiated. 42 | private InsertionX() { } 43 | 44 | /** 45 | * Rearranges the array in ascending order, using the natural order. 46 | * @param a the array to be sorted 47 | */ 48 | public static void sort(Comparable[] a) { 49 | int n = a.length; 50 | 51 | // put smallest element in position to serve as sentinel 52 | int exchanges = 0; 53 | for (int i = n-1; i > 0; i--) { 54 | if (less(a[i], a[i-1])) { 55 | exch(a, i, i-1); 56 | exchanges++; 57 | } 58 | } 59 | if (exchanges == 0) return; 60 | 61 | 62 | // insertion sort with half-exchanges 63 | for (int i = 2; i < n; i++) { 64 | Comparable v = a[i]; 65 | int j = i; 66 | while (less(v, a[j-1])) { 67 | a[j] = a[j-1]; 68 | j--; 69 | } 70 | a[j] = v; 71 | } 72 | 73 | assert isSorted(a); 74 | } 75 | 76 | 77 | /*************************************************************************** 78 | * Helper sorting functions. 79 | ***************************************************************************/ 80 | 81 | // is v < w ? 82 | private static boolean less(Comparable v, Comparable w) { 83 | return v.compareTo(w) < 0; 84 | } 85 | 86 | // exchange a[i] and a[j] 87 | private static void exch(Object[] a, int i, int j) { 88 | Object swap = a[i]; 89 | a[i] = a[j]; 90 | a[j] = swap; 91 | } 92 | 93 | 94 | /*************************************************************************** 95 | * Check if array is sorted - useful for debugging. 96 | ***************************************************************************/ 97 | private static boolean isSorted(Comparable[] a) { 98 | for (int i = 1; i < a.length; i++) 99 | if (less(a[i], a[i-1])) return false; 100 | return true; 101 | } 102 | 103 | // print array to standard output 104 | private static void show(Comparable[] a) { 105 | for (int i = 0; i < a.length; i++) { 106 | StdOut.println(a[i]); 107 | } 108 | } 109 | 110 | /** 111 | * Reads in a sequence of strings from standard input; insertion sorts them; 112 | * and prints them to standard output in ascending order. 113 | * 114 | * @param args the command-line arguments 115 | */ 116 | public static void main(String[] args) { 117 | String[] a = StdIn.readAllStrings(); 118 | InsertionX.sort(a); 119 | show(a); 120 | } 121 | 122 | } 123 | 124 | /****************************************************************************** 125 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 126 | * 127 | * This file is part of algs4.jar, which accompanies the textbook 128 | * 129 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 130 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 131 | * http://algs4.cs.princeton.edu 132 | * 133 | * 134 | * algs4.jar is free software: you can redistribute it and/or modify 135 | * it under the terms of the GNU General Public License as published by 136 | * the Free Software Foundation, either version 3 of the License, or 137 | * (at your option) any later version. 138 | * 139 | * algs4.jar is distributed in the hope that it will be useful, 140 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 141 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 142 | * GNU General Public License for more details. 143 | * 144 | * You should have received a copy of the GNU General Public License 145 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 146 | ******************************************************************************/ 147 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/MergeBU.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac MergeBU.java 3 | * Execution: java MergeBU < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: https://algs4.cs.princeton.edu/22mergesort/tiny.txt 6 | * https://algs4.cs.princeton.edu/22mergesort/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using 9 | * bottom-up mergesort. 10 | * 11 | * % more tiny.txt 12 | * S O R T E X A M P L E 13 | * 14 | * % java MergeBU < tiny.txt 15 | * A E E L M O P R S T X [ one string per line ] 16 | * 17 | * % more words3.txt 18 | * bed bug dad yes zoo ... all bad yet 19 | * 20 | * % java MergeBU < words3.txt 21 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 22 | * 23 | ******************************************************************************/ 24 | 25 | package edu.princeton.cs.algs4; 26 | 27 | /** 28 | * The {@code MergeBU} class provides static methods for sorting an 29 | * array using bottom-up mergesort. 30 | *

31 | * For additional documentation, see Section 2.1 of 32 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 33 | * 34 | * @author Robert Sedgewick 35 | * @author Kevin Wayne 36 | */ 37 | public class MergeBU { 38 | 39 | // This class should not be instantiated. 40 | private MergeBU() { } 41 | 42 | // stably merge a[lo..mid] with a[mid+1..hi] using aux[lo..hi] 43 | private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { 44 | 45 | // copy to aux[] 46 | for (int k = lo; k <= hi; k++) { 47 | aux[k] = a[k]; 48 | } 49 | 50 | // merge back to a[] 51 | int i = lo, j = mid+1; 52 | for (int k = lo; k <= hi; k++) { 53 | if (i > mid) a[k] = aux[j++]; // this copying is unneccessary 54 | else if (j > hi) a[k] = aux[i++]; 55 | else if (less(aux[j], aux[i])) a[k] = aux[j++]; 56 | else a[k] = aux[i++]; 57 | } 58 | 59 | } 60 | 61 | /** 62 | * Rearranges the array in ascending order, using the natural order. 63 | * @param a the array to be sorted 64 | */ 65 | public static void sort(Comparable[] a) { 66 | int n = a.length; 67 | Comparable[] aux = new Comparable[n]; 68 | for (int len = 1; len < n; len *= 2) { 69 | for (int lo = 0; lo < n-len; lo += len+len) { 70 | int mid = lo+len-1; 71 | int hi = Math.min(lo+len+len-1, n-1); 72 | merge(a, aux, lo, mid, hi); 73 | } 74 | } 75 | assert isSorted(a); 76 | } 77 | 78 | /*********************************************************************** 79 | * Helper sorting functions. 80 | ***************************************************************************/ 81 | 82 | // is v < w ? 83 | private static boolean less(Comparable v, Comparable w) { 84 | return v.compareTo(w) < 0; 85 | } 86 | 87 | 88 | /*************************************************************************** 89 | * Check if array is sorted - useful for debugging. 90 | ***************************************************************************/ 91 | private static boolean isSorted(Comparable[] a) { 92 | for (int i = 1; i < a.length; i++) 93 | if (less(a[i], a[i-1])) return false; 94 | return true; 95 | } 96 | 97 | // print array to standard output 98 | private static void show(Comparable[] a) { 99 | for (int i = 0; i < a.length; i++) { 100 | StdOut.println(a[i]); 101 | } 102 | } 103 | 104 | /** 105 | * Reads in a sequence of strings from standard input; bottom-up 106 | * mergesorts them; and prints them to standard output in ascending order. 107 | * 108 | * @param args the command-line arguments 109 | */ 110 | public static void main(String[] args) { 111 | String[] a = StdIn.readAllStrings(); 112 | MergeBU.sort(a); 113 | show(a); 114 | } 115 | } 116 | 117 | /****************************************************************************** 118 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 119 | * 120 | * This file is part of algs4.jar, which accompanies the textbook 121 | * 122 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 123 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 124 | * http://algs4.cs.princeton.edu 125 | * 126 | * 127 | * algs4.jar is free software: you can redistribute it and/or modify 128 | * it under the terms of the GNU General Public License as published by 129 | * the Free Software Foundation, either version 3 of the License, or 130 | * (at your option) any later version. 131 | * 132 | * algs4.jar is distributed in the hope that it will be useful, 133 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 134 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 135 | * GNU General Public License for more details. 136 | * 137 | * You should have received a copy of the GNU General Public License 138 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 139 | ******************************************************************************/ 140 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Knuth.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Knuth.java 3 | * Execution: java Knuth < list.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/11model/cards.txt 6 | * https://algs4.cs.princeton.edu/11model/cardsUnicode.txt 7 | * 8 | * Reads in a list of strings and prints them in random order. 9 | * The Knuth (or Fisher-Yates) shuffling algorithm guarantees 10 | * to rearrange the elements in uniformly random order, under 11 | * the assumption that Math.random() generates independent and 12 | * uniformly distributed numbers between 0 and 1. 13 | * 14 | * % more cards.txt 15 | * 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC AC 16 | * 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD AD 17 | * 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH AH 18 | * 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS AS 19 | * 20 | * % java Knuth < cards.txt 21 | * 6H 22 | * 9C 23 | * 8H 24 | * 7C 25 | * JS 26 | * ... 27 | * KH 28 | * 29 | * % more cardsUnicode.txt 30 | * 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣ 31 | * 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦ 32 | * 2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥ 33 | * 2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠ 34 | * 35 | * % java Knuth < cardsUnicode.txt 36 | * 2♠ 37 | * K♥ 38 | * 6♥ 39 | * 5♣ 40 | * J♣ 41 | * ... 42 | * A♦ 43 | * 44 | ******************************************************************************/ 45 | 46 | package edu.princeton.cs.algs4; 47 | 48 | /** 49 | * The {@code Knuth} class provides a client for reading in a 50 | * sequence of strings and shuffling them using the Knuth (or Fisher-Yates) 51 | * shuffling algorithm. This algorithm guarantees to rearrange the 52 | * elements in uniformly random order, under 53 | * the assumption that Math.random() generates independent and 54 | * uniformly distributed numbers between 0 and 1. 55 | *

56 | * For additional documentation, 57 | * see Section 1.1 of 58 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 59 | * See {@link StdRandom} for versions that shuffle arrays and 60 | * subarrays of objects, doubles, and ints. 61 | * 62 | * @author Robert Sedgewick 63 | * @author Kevin Wayne 64 | */ 65 | public class Knuth { 66 | 67 | // this class should not be instantiated 68 | private Knuth() { } 69 | 70 | /** 71 | * Rearranges an array of objects in uniformly random order 72 | * (under the assumption that {@code Math.random()} generates independent 73 | * and uniformly distributed numbers between 0 and 1). 74 | * @param a the array to be shuffled 75 | */ 76 | public static void shuffle(Object[] a) { 77 | int n = a.length; 78 | for (int i = 0; i < n; i++) { 79 | // choose index uniformly in [0, i] 80 | int r = (int) (Math.random() * (i + 1)); 81 | Object swap = a[r]; 82 | a[r] = a[i]; 83 | a[i] = swap; 84 | } 85 | } 86 | 87 | /** 88 | * Rearranges an array of objects in uniformly random order 89 | * (under the assumption that {@code Math.random()} generates independent 90 | * and uniformly distributed numbers between 0 and 1). 91 | * @param a the array to be shuffled 92 | */ 93 | public static void shuffleAlternate(Object[] a) { 94 | int n = a.length; 95 | for (int i = 0; i < n; i++) { 96 | // choose index uniformly in [i, n-1] 97 | int r = i + (int) (Math.random() * (n - i)); 98 | Object swap = a[r]; 99 | a[r] = a[i]; 100 | a[i] = swap; 101 | } 102 | } 103 | 104 | /** 105 | * Reads in a sequence of strings from standard input, shuffles 106 | * them, and prints out the results. 107 | * 108 | * @param args the command-line arguments 109 | */ 110 | public static void main(String[] args) { 111 | 112 | // read in the data 113 | String[] a = StdIn.readAllStrings(); 114 | 115 | // shuffle the array 116 | Knuth.shuffle(a); 117 | 118 | // print results. 119 | for (int i = 0; i < a.length; i++) 120 | StdOut.println(a[i]); 121 | } 122 | } 123 | 124 | /****************************************************************************** 125 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 126 | * 127 | * This file is part of algs4.jar, which accompanies the textbook 128 | * 129 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 130 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 131 | * http://algs4.cs.princeton.edu 132 | * 133 | * 134 | * algs4.jar is free software: you can redistribute it and/or modify 135 | * it under the terms of the GNU General Public License as published by 136 | * the Free Software Foundation, either version 3 of the License, or 137 | * (at your option) any later version. 138 | * 139 | * algs4.jar is distributed in the hope that it will be useful, 140 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 141 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 142 | * GNU General Public License for more details. 143 | * 144 | * You should have received a copy of the GNU General Public License 145 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 146 | ******************************************************************************/ 147 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Quick3way.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Quick3way.java 3 | * Execution: java Quick3way < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: https://algs4.cs.princeton.edu/23quicksort/tiny.txt 6 | * https://algs4.cs.princeton.edu/23quicksort/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using 3-way quicksort. 9 | * 10 | * % more tiny.txt 11 | * S O R T E X A M P L E 12 | * 13 | * % java Quick3way < tiny.txt 14 | * A E E L M O P R S T X [ one string per line ] 15 | * 16 | * % more words3.txt 17 | * bed bug dad yes zoo ... all bad yet 18 | * 19 | * % java Quick3way < words3.txt 20 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 21 | * 22 | ******************************************************************************/ 23 | 24 | package edu.princeton.cs.algs4; 25 | 26 | /** 27 | * The {@code Quick3way} class provides static methods for sorting an 28 | * array using quicksort with 3-way partitioning. 29 | *

30 | * For additional documentation, 31 | * see Section 2.3 of 32 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 33 | * 34 | * @author Robert Sedgewick 35 | * @author Kevin Wayne 36 | */ 37 | public class Quick3way { 38 | 39 | // This class should not be instantiated. 40 | private Quick3way() { } 41 | 42 | /** 43 | * Rearranges the array in ascending order, using the natural order. 44 | * @param a the array to be sorted 45 | */ 46 | public static void sort(Comparable[] a) { 47 | StdRandom.shuffle(a); 48 | sort(a, 0, a.length - 1); 49 | assert isSorted(a); 50 | } 51 | 52 | // quicksort the subarray a[lo .. hi] using 3-way partitioning 53 | private static void sort(Comparable[] a, int lo, int hi) { 54 | if (hi <= lo) return; 55 | int lt = lo, gt = hi; 56 | Comparable v = a[lo]; 57 | int i = lo + 1; 58 | while (i <= gt) { 59 | int cmp = a[i].compareTo(v); 60 | if (cmp < 0) exch(a, lt++, i++); 61 | else if (cmp > 0) exch(a, i, gt--); 62 | else i++; 63 | } 64 | 65 | // a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi]. 66 | sort(a, lo, lt-1); 67 | sort(a, gt+1, hi); 68 | assert isSorted(a, lo, hi); 69 | } 70 | 71 | 72 | 73 | /*************************************************************************** 74 | * Helper sorting functions. 75 | ***************************************************************************/ 76 | 77 | // is v < w ? 78 | private static boolean less(Comparable v, Comparable w) { 79 | return v.compareTo(w) < 0; 80 | } 81 | 82 | // exchange a[i] and a[j] 83 | private static void exch(Object[] a, int i, int j) { 84 | Object swap = a[i]; 85 | a[i] = a[j]; 86 | a[j] = swap; 87 | } 88 | 89 | 90 | /*************************************************************************** 91 | * Check if array is sorted - useful for debugging. 92 | ***************************************************************************/ 93 | private static boolean isSorted(Comparable[] a) { 94 | return isSorted(a, 0, a.length - 1); 95 | } 96 | 97 | private static boolean isSorted(Comparable[] a, int lo, int hi) { 98 | for (int i = lo + 1; i <= hi; i++) 99 | if (less(a[i], a[i-1])) return false; 100 | return true; 101 | } 102 | 103 | 104 | 105 | // print array to standard output 106 | private static void show(Comparable[] a) { 107 | for (int i = 0; i < a.length; i++) { 108 | StdOut.println(a[i]); 109 | } 110 | } 111 | 112 | /** 113 | * Reads in a sequence of strings from standard input; 3-way 114 | * quicksorts them; and prints them to standard output in ascending order. 115 | * 116 | * @param args the command-line arguments 117 | */ 118 | public static void main(String[] args) { 119 | String[] a = StdIn.readAllStrings(); 120 | Quick3way.sort(a); 121 | show(a); 122 | } 123 | 124 | } 125 | 126 | /****************************************************************************** 127 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 128 | * 129 | * This file is part of algs4.jar, which accompanies the textbook 130 | * 131 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 132 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 133 | * http://algs4.cs.princeton.edu 134 | * 135 | * 136 | * algs4.jar is free software: you can redistribute it and/or modify 137 | * it under the terms of the GNU General Public License as published by 138 | * the Free Software Foundation, either version 3 of the License, or 139 | * (at your option) any later version. 140 | * 141 | * algs4.jar is distributed in the hope that it will be useful, 142 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 143 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 144 | * GNU General Public License for more details. 145 | * 146 | * You should have received a copy of the GNU General Public License 147 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 148 | ******************************************************************************/ 149 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Accumulator.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Accumulator.java 3 | * Execution: java Accumulator < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * 6 | * Mutable data type that calculates the mean, sample standard 7 | * deviation, and sample variance of a stream of real numbers 8 | * use a stable, one-pass algorithm. 9 | * 10 | ******************************************************************************/ 11 | 12 | package edu.princeton.cs.algs4; 13 | 14 | 15 | /** 16 | * The {@code Accumulator} class is a data type for computing the running 17 | * mean, sample standard deviation, and sample variance of a stream of real 18 | * numbers. It provides an example of a mutable data type and a streaming 19 | * algorithm. 20 | *

21 | * This implementation uses a one-pass algorithm that is less susceptible 22 | * to floating-point roundoff error than the more straightforward 23 | * implementation based on saving the sum of the squares of the numbers. 24 | * This technique is due to 25 | * B. P. Welford. 26 | * Each operation takes constant time in the worst case. 27 | * The amount of memory is constant - the data values are not stored. 28 | *

29 | * For additional documentation, 30 | * see Section 1.2 of 31 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 32 | * 33 | * @author Robert Sedgewick 34 | * @author Kevin Wayne 35 | */ 36 | public class Accumulator { 37 | private int n = 0; // number of data values 38 | private double sum = 0.0; // sample variance * (n-1) 39 | private double mu = 0.0; // sample mean 40 | 41 | /** 42 | * Initializes an accumulator. 43 | */ 44 | public Accumulator() { 45 | } 46 | 47 | /** 48 | * Adds the specified data value to the accumulator. 49 | * @param x the data value 50 | */ 51 | public void addDataValue(double x) { 52 | n++; 53 | double delta = x - mu; 54 | mu += delta / n; 55 | sum += (double) (n - 1) / n * delta * delta; 56 | } 57 | 58 | /** 59 | * Returns the mean of the data values. 60 | * @return the mean of the data values 61 | */ 62 | public double mean() { 63 | return mu; 64 | } 65 | 66 | /** 67 | * Returns the sample variance of the data values. 68 | * @return the sample variance of the data values 69 | */ 70 | public double var() { 71 | if (n <= 1) return Double.NaN; 72 | return sum / (n - 1); 73 | } 74 | 75 | /** 76 | * Returns the sample standard deviation of the data values. 77 | * @return the sample standard deviation of the data values 78 | */ 79 | public double stddev() { 80 | return Math.sqrt(this.var()); 81 | } 82 | 83 | /** 84 | * Returns the number of data values. 85 | * @return the number of data values 86 | */ 87 | public int count() { 88 | return n; 89 | } 90 | 91 | /** 92 | * Returns a string representation of this accumulator. 93 | * @return a string representation of this accumulator 94 | */ 95 | public String toString() { 96 | return "n = " + n + ", mean = " + mean() + ", stddev = " + stddev(); 97 | } 98 | 99 | /** 100 | * Unit tests the {@code Accumulator} data type. 101 | * Reads in a stream of real number from standard input; 102 | * adds them to the accumulator; and prints the mean, 103 | * sample standard deviation, and sample variance to standard 104 | * output. 105 | * 106 | * @param args the command-line arguments 107 | */ 108 | public static void main(String[] args) { 109 | Accumulator stats = new Accumulator(); 110 | while (!StdIn.isEmpty()) { 111 | double x = StdIn.readDouble(); 112 | stats.addDataValue(x); 113 | } 114 | 115 | StdOut.printf("n = %d\n", stats.count()); 116 | StdOut.printf("mean = %.5f\n", stats.mean()); 117 | StdOut.printf("stddev = %.5f\n", stats.stddev()); 118 | StdOut.printf("var = %.5f\n", stats.var()); 119 | StdOut.println(stats); 120 | } 121 | } 122 | 123 | /****************************************************************************** 124 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 125 | * 126 | * This file is part of algs4.jar, which accompanies the textbook 127 | * 128 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 129 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 130 | * http://algs4.cs.princeton.edu 131 | * 132 | * 133 | * algs4.jar is free software: you can redistribute it and/or modify 134 | * it under the terms of the GNU General Public License as published by 135 | * the Free Software Foundation, either version 3 of the License, or 136 | * (at your option) any later version. 137 | * 138 | * algs4.jar is distributed in the hope that it will be useful, 139 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 140 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 141 | * GNU General Public License for more details. 142 | * 143 | * You should have received a copy of the GNU General Public License 144 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 145 | ******************************************************************************/ 146 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac DepthFirstSearch.java 3 | * Execution: java DepthFirstSearch filename.txt s 4 | * Dependencies: Graph.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt 6 | * https://algs4.cs.princeton.edu/41graph/mediumG.txt 7 | * 8 | * Run depth first search on an undirected graph. 9 | * Runs in O(E + V) time. 10 | * 11 | * % java DepthFirstSearch tinyG.txt 0 12 | * 0 1 2 3 4 5 6 13 | * NOT connected 14 | * 15 | * % java DepthFirstSearch tinyG.txt 9 16 | * 9 10 11 12 17 | * NOT connected 18 | * 19 | ******************************************************************************/ 20 | 21 | package edu.princeton.cs.algs4; 22 | 23 | /** 24 | * The {@code DepthFirstSearch} class represents a data type for 25 | * determining the vertices connected to a given source vertex s 26 | * in an undirected graph. For versions that find the paths, see 27 | * {@link DepthFirstPaths} and {@link BreadthFirstPaths}. 28 | *

29 | * This implementation uses depth-first search. 30 | * See {@link NonrecursiveDFS} for a non-recursive version. 31 | * The constructor takes time proportional to V + E 32 | * (in the worst case), 33 | * where V is the number of vertices and E is the number of edges. 34 | * It uses extra space (not including the graph) proportional to V. 35 | *

36 | * For additional documentation, see Section 4.1 37 | * of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 38 | * 39 | * @author Robert Sedgewick 40 | * @author Kevin Wayne 41 | */ 42 | public class DepthFirstSearch { 43 | private boolean[] marked; // marked[v] = is there an s-v path? 44 | private int count; // number of vertices connected to s 45 | 46 | /** 47 | * Computes the vertices in graph {@code G} that are 48 | * connected to the source vertex {@code s}. 49 | * @param G the graph 50 | * @param s the source vertex 51 | * @throws IllegalArgumentException unless {@code 0 <= s < V} 52 | */ 53 | public DepthFirstSearch(Graph G, int s) { 54 | marked = new boolean[G.V()]; 55 | validateVertex(s); 56 | dfs(G, s); 57 | } 58 | 59 | // depth first search from v 60 | private void dfs(Graph G, int v) { 61 | count++; 62 | marked[v] = true; 63 | for (int w : G.adj(v)) { 64 | if (!marked[w]) { 65 | dfs(G, w); 66 | } 67 | } 68 | } 69 | 70 | /** 71 | * Is there a path between the source vertex {@code s} and vertex {@code v}? 72 | * @param v the vertex 73 | * @return {@code true} if there is a path, {@code false} otherwise 74 | * @throws IllegalArgumentException unless {@code 0 <= v < V} 75 | */ 76 | public boolean marked(int v) { 77 | validateVertex(v); 78 | return marked[v]; 79 | } 80 | 81 | /** 82 | * Returns the number of vertices connected to the source vertex {@code s}. 83 | * @return the number of vertices connected to the source vertex {@code s} 84 | */ 85 | public int count() { 86 | return count; 87 | } 88 | 89 | // throw an IllegalArgumentException unless {@code 0 <= v < V} 90 | private void validateVertex(int v) { 91 | int V = marked.length; 92 | if (v < 0 || v >= V) 93 | throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); 94 | } 95 | 96 | /** 97 | * Unit tests the {@code DepthFirstSearch} data type. 98 | * 99 | * @param args the command-line arguments 100 | */ 101 | public static void main(String[] args) { 102 | In in = new In(args[0]); 103 | Graph G = new Graph(in); 104 | int s = Integer.parseInt(args[1]); 105 | DepthFirstSearch search = new DepthFirstSearch(G, s); 106 | for (int v = 0; v < G.V(); v++) { 107 | if (search.marked(v)) 108 | StdOut.print(v + " "); 109 | } 110 | 111 | StdOut.println(); 112 | if (search.count() != G.V()) StdOut.println("NOT connected"); 113 | else StdOut.println("connected"); 114 | } 115 | 116 | } 117 | 118 | /****************************************************************************** 119 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 120 | * 121 | * This file is part of algs4.jar, which accompanies the textbook 122 | * 123 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 124 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 125 | * http://algs4.cs.princeton.edu 126 | * 127 | * 128 | * algs4.jar is free software: you can redistribute it and/or modify 129 | * it under the terms of the GNU General Public License as published by 130 | * the Free Software Foundation, either version 3 of the License, or 131 | * (at your option) any later version. 132 | * 133 | * algs4.jar is distributed in the hope that it will be useful, 134 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 135 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 136 | * GNU General Public License for more details. 137 | * 138 | * You should have received a copy of the GNU General Public License 139 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 140 | ******************************************************************************/ 141 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LongestCommonSubstring.java 3 | * Execution: java LongestCommonSubstring file1.txt file2.txt 4 | * Dependencies: SuffixArray.java In.java StdOut.java 5 | * Data files: https://algs4.cs.princeton.edu/63suffix/tale.txt 6 | * https://algs4.cs.princeton.edu/63suffix/mobydick.txt 7 | * 8 | * Read in two text files and find the longest substring that 9 | * appears in both texts. 10 | * 11 | * % java LongestCommonSubstring tale.txt mobydick.txt 12 | * ' seemed on the point of being ' 13 | * 14 | ******************************************************************************/ 15 | 16 | package edu.princeton.cs.algs4; 17 | 18 | /** 19 | * The {@code LongestCommonSubstring} class provides a {@link SuffixArray} 20 | * client for computing the longest common substring that appears in two 21 | * given strings. 22 | *

23 | * This implementation computes the suffix array of each string and applies a 24 | * merging operation to determine the longest common substring. 25 | * For an alternate implementation, see 26 | * LongestCommonSubstringConcatenate.java. 27 | *

28 | * For additional documentation, 29 | * see Section 6.3 of 30 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 31 | *

32 | * 33 | * @author Robert Sedgewick 34 | * @author Kevin Wayne 35 | */ 36 | public class LongestCommonSubstring { 37 | 38 | // Do not instantiate. 39 | private LongestCommonSubstring() { } 40 | 41 | // return the longest common prefix of suffix s[p..] and suffix t[q..] 42 | private static String lcp(String s, int p, String t, int q) { 43 | int n = Math.min(s.length() - p, t.length() - q); 44 | for (int i = 0; i < n; i++) { 45 | if (s.charAt(p + i) != t.charAt(q + i)) 46 | return s.substring(p, p + i); 47 | } 48 | return s.substring(p, p + n); 49 | } 50 | 51 | // compare suffix s[p..] and suffix t[q..] 52 | private static int compare(String s, int p, String t, int q) { 53 | int n = Math.min(s.length() - p, t.length() - q); 54 | for (int i = 0; i < n; i++) { 55 | if (s.charAt(p + i) != t.charAt(q + i)) 56 | return s.charAt(p+i) - t.charAt(q+i); 57 | } 58 | if (s.length() - p < t.length() - q) return -1; 59 | else if (s.length() - p > t.length() - q) return +1; 60 | else return 0; 61 | } 62 | 63 | /** 64 | * Returns the longest common string of the two specified strings. 65 | * 66 | * @param s one string 67 | * @param t the other string 68 | * @return the longest common string that appears as a substring 69 | * in both {@code s} and {@code t}; the empty string 70 | * if no such string 71 | */ 72 | public static String lcs(String s, String t) { 73 | SuffixArray suffix1 = new SuffixArray(s); 74 | SuffixArray suffix2 = new SuffixArray(t); 75 | 76 | // find longest common substring by "merging" sorted suffixes 77 | String lcs = ""; 78 | int i = 0, j = 0; 79 | while (i < s.length() && j < t.length()) { 80 | int p = suffix1.index(i); 81 | int q = suffix2.index(j); 82 | String x = lcp(s, p, t, q); 83 | if (x.length() > lcs.length()) lcs = x; 84 | if (compare(s, p, t, q) < 0) i++; 85 | else j++; 86 | } 87 | return lcs; 88 | } 89 | 90 | /** 91 | * Unit tests the {@code lcs()} method. 92 | * Reads in two strings from files specified as command-line arguments; 93 | * computes the longest common substring; and prints the results to 94 | * standard output. 95 | * 96 | * @param args the command-line arguments 97 | */ 98 | public static void main(String[] args) { 99 | In in1 = new In(args[0]); 100 | In in2 = new In(args[1]); 101 | String s = in1.readAll().trim().replaceAll("\\s+", " "); 102 | String t = in2.readAll().trim().replaceAll("\\s+", " "); 103 | StdOut.println("'" + lcs(s, t) + "'"); 104 | } 105 | } 106 | 107 | 108 | /****************************************************************************** 109 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 110 | * 111 | * This file is part of algs4.jar, which accompanies the textbook 112 | * 113 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 114 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 115 | * http://algs4.cs.princeton.edu 116 | * 117 | * 118 | * algs4.jar is free software: you can redistribute it and/or modify 119 | * it under the terms of the GNU General Public License as published by 120 | * the Free Software Foundation, either version 3 of the License, or 121 | * (at your option) any later version. 122 | * 123 | * algs4.jar is distributed in the hope that it will be useful, 124 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 125 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 126 | * GNU General Public License for more details. 127 | * 128 | * You should have received a copy of the GNU General Public License 129 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 130 | ******************************************************************************/ 131 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/Shell.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac Shell.java 3 | * Execution: java Shell < input.txt 4 | * Dependencies: StdOut.java StdIn.java 5 | * Data files: https://algs4.cs.princeton.edu/21elementary/tiny.txt 6 | * https://algs4.cs.princeton.edu/21elementary/words3.txt 7 | * 8 | * Sorts a sequence of strings from standard input using shellsort. 9 | * 10 | * Uses increment sequence proposed by Sedgewick and Incerpi. 11 | * The nth element of the sequence is the smallest integer >= 2.5^n 12 | * that is relatively prime to all previous terms in the sequence. 13 | * For example, incs[4] is 41 because 2.5^4 = 39.0625 and 41 is 14 | * the next integer that is relatively prime to 3, 7, and 16. 15 | * 16 | * % more tiny.txt 17 | * S O R T E X A M P L E 18 | * 19 | * % java Shell < tiny.txt 20 | * A E E L M O P R S T X [ one string per line ] 21 | * 22 | * % more words3.txt 23 | * bed bug dad yes zoo ... all bad yet 24 | * 25 | * % java Shell < words3.txt 26 | * all bad bed bug dad ... yes yet zoo [ one string per line ] 27 | * 28 | * 29 | ******************************************************************************/ 30 | 31 | package edu.princeton.cs.algs4; 32 | 33 | /** 34 | * The {@code Shell} class provides static methods for sorting an 35 | * array using Shellsort with Knuth's increment sequence (1, 4, 13, 40, ...). 36 | *

37 | * For additional documentation, see Section 2.1 of 38 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 39 | * 40 | * @author Robert Sedgewick 41 | * @author Kevin Wayne 42 | */ 43 | public class Shell { 44 | 45 | // This class should not be instantiated. 46 | private Shell() { } 47 | 48 | /** 49 | * Rearranges the array in ascending order, using the natural order. 50 | * @param a the array to be sorted 51 | */ 52 | public static void sort(Comparable[] a) { 53 | int n = a.length; 54 | 55 | // 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ... 56 | int h = 1; 57 | while (h < n/3) h = 3*h + 1; 58 | 59 | while (h >= 1) { 60 | // h-sort the array 61 | for (int i = h; i < n; i++) { 62 | for (int j = i; j >= h && less(a[j], a[j-h]); j -= h) { 63 | exch(a, j, j-h); 64 | } 65 | } 66 | assert isHsorted(a, h); 67 | h /= 3; 68 | } 69 | assert isSorted(a); 70 | } 71 | 72 | 73 | 74 | /*************************************************************************** 75 | * Helper sorting functions. 76 | ***************************************************************************/ 77 | 78 | // is v < w ? 79 | private static boolean less(Comparable v, Comparable w) { 80 | return v.compareTo(w) < 0; 81 | } 82 | 83 | // exchange a[i] and a[j] 84 | private static void exch(Object[] a, int i, int j) { 85 | Object swap = a[i]; 86 | a[i] = a[j]; 87 | a[j] = swap; 88 | } 89 | 90 | 91 | /*************************************************************************** 92 | * Check if array is sorted - useful for debugging. 93 | ***************************************************************************/ 94 | private static boolean isSorted(Comparable[] a) { 95 | for (int i = 1; i < a.length; i++) 96 | if (less(a[i], a[i-1])) return false; 97 | return true; 98 | } 99 | 100 | // is the array h-sorted? 101 | private static boolean isHsorted(Comparable[] a, int h) { 102 | for (int i = h; i < a.length; i++) 103 | if (less(a[i], a[i-h])) return false; 104 | return true; 105 | } 106 | 107 | // print array to standard output 108 | private static void show(Comparable[] a) { 109 | for (int i = 0; i < a.length; i++) { 110 | StdOut.println(a[i]); 111 | } 112 | } 113 | 114 | /** 115 | * Reads in a sequence of strings from standard input; Shellsorts them; 116 | * and prints them to standard output in ascending order. 117 | * 118 | * @param args the command-line arguments 119 | */ 120 | public static void main(String[] args) { 121 | String[] a = StdIn.readAllStrings(); 122 | Shell.sort(a); 123 | show(a); 124 | } 125 | 126 | } 127 | 128 | /****************************************************************************** 129 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 130 | * 131 | * This file is part of algs4.jar, which accompanies the textbook 132 | * 133 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 134 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 135 | * http://algs4.cs.princeton.edu 136 | * 137 | * 138 | * algs4.jar is free software: you can redistribute it and/or modify 139 | * it under the terms of the GNU General Public License as published by 140 | * the Free Software Foundation, either version 3 of the License, or 141 | * (at your option) any later version. 142 | * 143 | * algs4.jar is distributed in the hope that it will be useful, 144 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 145 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 146 | * GNU General Public License for more details. 147 | * 148 | * You should have received a copy of the GNU General Public License 149 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 150 | ******************************************************************************/ 151 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LinkedBag.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LinkedBag.java 3 | * Execution: java LinkedBag < input.txt 4 | * Dependencies: StdIn.java StdOut.java 5 | * 6 | * A generic bag or multiset, implemented using a singly linked list. 7 | * 8 | * % more tobe.txt 9 | * to be or not to - be - - that - - - is 10 | * 11 | * % java LinkedBag < tobe.txt 12 | * size of bag = 14 13 | * is 14 | * - 15 | * - 16 | * - 17 | * that 18 | * - 19 | * - 20 | * be 21 | * - 22 | * to 23 | * not 24 | * or 25 | * be 26 | * to 27 | * 28 | ******************************************************************************/ 29 | 30 | package edu.princeton.cs.algs4; 31 | 32 | import java.util.Iterator; 33 | import java.util.NoSuchElementException; 34 | 35 | /** 36 | * The {@code LinkedBag} class represents a bag (or multiset) of 37 | * generic items. It supports insertion and iterating over the 38 | * items in arbitrary order. 39 | *

40 | * This implementation uses a singly linked list with a non-static nested class Node. 41 | * See {@link Bag} for a version that uses a static nested class. 42 | * The add, isEmpty, and size operations 43 | * take constant time. Iteration takes time proportional to the number of items. 44 | *

45 | * For additional documentation, see Section 1.3 of 46 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 47 | * 48 | * @author Robert Sedgewick 49 | * @author Kevin Wayne 50 | */ 51 | public class LinkedBag implements Iterable { 52 | private Node first; // beginning of bag 53 | private int n; // number of elements in bag 54 | 55 | // helper linked list class 56 | private class Node { 57 | private Item item; 58 | private Node next; 59 | } 60 | 61 | /** 62 | * Initializes an empty bag. 63 | */ 64 | public LinkedBag() { 65 | first = null; 66 | n = 0; 67 | } 68 | 69 | /** 70 | * Is this bag empty? 71 | * @return true if this bag is empty; false otherwise 72 | */ 73 | public boolean isEmpty() { 74 | return first == null; 75 | } 76 | 77 | /** 78 | * Returns the number of items in this bag. 79 | * @return the number of items in this bag 80 | */ 81 | public int size() { 82 | return n; 83 | } 84 | 85 | /** 86 | * Adds the item to this bag. 87 | * @param item the item to add to this bag 88 | */ 89 | public void add(Item item) { 90 | Node oldfirst = first; 91 | first = new Node(); 92 | first.item = item; 93 | first.next = oldfirst; 94 | n++; 95 | } 96 | 97 | 98 | /** 99 | * Returns an iterator that iterates over the items in the bag. 100 | */ 101 | public Iterator iterator() { 102 | return new ListIterator(); 103 | } 104 | 105 | // an iterator over a linked list 106 | private class ListIterator implements Iterator { 107 | private Node current; 108 | 109 | // creates a new iterator 110 | public ListIterator() { 111 | current = first; 112 | } 113 | 114 | // is there a next item in the iterator? 115 | public boolean hasNext() { 116 | return current != null; 117 | } 118 | 119 | // this method is optional in Iterator interface 120 | public void remove() { 121 | throw new UnsupportedOperationException(); 122 | } 123 | 124 | // returns the next item in the iterator (and advances the iterator) 125 | public Item next() { 126 | if (!hasNext()) throw new NoSuchElementException(); 127 | Item item = current.item; 128 | current = current.next; 129 | return item; 130 | } 131 | } 132 | 133 | /** 134 | * Unit tests the {@code LinkedBag} data type. 135 | * 136 | * @param args the command-line arguments 137 | */ 138 | public static void main(String[] args) { 139 | LinkedBag bag = new LinkedBag(); 140 | while (!StdIn.isEmpty()) { 141 | String item = StdIn.readString(); 142 | bag.add(item); 143 | } 144 | 145 | StdOut.println("size of bag = " + bag.size()); 146 | for (String s : bag) { 147 | StdOut.println(s); 148 | } 149 | } 150 | 151 | 152 | } 153 | 154 | /****************************************************************************** 155 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 156 | * 157 | * This file is part of algs4.jar, which accompanies the textbook 158 | * 159 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 160 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 161 | * http://algs4.cs.princeton.edu 162 | * 163 | * 164 | * algs4.jar is free software: you can redistribute it and/or modify 165 | * it under the terms of the GNU General Public License as published by 166 | * the Free Software Foundation, either version 3 of the License, or 167 | * (at your option) any later version. 168 | * 169 | * algs4.jar is distributed in the hope that it will be useful, 170 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 171 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 172 | * GNU General Public License for more details. 173 | * 174 | * You should have received a copy of the GNU General Public License 175 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 176 | ******************************************************************************/ 177 | -------------------------------------------------------------------------------- /src/main/java/edu/princeton/cs/algs4/LZW.java: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * Compilation: javac LZW.java 3 | * Execution: java LZW - < input.txt (compress) 4 | * Execution: java LZW + < input.txt (expand) 5 | * Dependencies: BinaryIn.java BinaryOut.java 6 | * Data files: https://algs4.cs.princeton.edu/55compression/abraLZW.txt 7 | * https://algs4.cs.princeton.edu/55compression/ababLZW.txt 8 | * 9 | * Compress or expand binary input from standard input using LZW. 10 | * 11 | * WARNING: STARTING WITH ORACLE JAVA 6, UPDATE 7 the SUBSTRING 12 | * METHOD TAKES TIME AND SPACE LINEAR IN THE SIZE OF THE EXTRACTED 13 | * SUBSTRING (INSTEAD OF CONSTANT SPACE AND TIME AS IN EARLIER 14 | * IMPLEMENTATIONS). 15 | * 16 | * See this article 17 | * for more details. 18 | * 19 | ******************************************************************************/ 20 | 21 | package edu.princeton.cs.algs4; 22 | 23 | /** 24 | * The {@code LZW} class provides static methods for compressing 25 | * and expanding a binary input using LZW compression over the 8-bit extended 26 | * ASCII alphabet with 12-bit codewords. 27 | *

28 | * For additional documentation, 29 | * see Section 5.5 of 30 | * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. 31 | * 32 | * @author Robert Sedgewick 33 | * @author Kevin Wayne 34 | */ 35 | public class LZW { 36 | private static final int R = 256; // number of input chars 37 | private static final int L = 4096; // number of codewords = 2^W 38 | private static final int W = 12; // codeword width 39 | 40 | // Do not instantiate. 41 | private LZW() { } 42 | 43 | /** 44 | * Reads a sequence of 8-bit bytes from standard input; compresses 45 | * them using LZW compression with 12-bit codewords; and writes the results 46 | * to standard output. 47 | */ 48 | public static void compress() { 49 | String input = BinaryStdIn.readString(); 50 | TST st = new TST(); 51 | for (int i = 0; i < R; i++) 52 | st.put("" + (char) i, i); 53 | int code = R+1; // R is codeword for EOF 54 | 55 | while (input.length() > 0) { 56 | String s = st.longestPrefixOf(input); // Find max prefix match s. 57 | BinaryStdOut.write(st.get(s), W); // Print s's encoding. 58 | int t = s.length(); 59 | if (t < input.length() && code < L) // Add s to symbol table. 60 | st.put(input.substring(0, t + 1), code++); 61 | input = input.substring(t); // Scan past s in input. 62 | } 63 | BinaryStdOut.write(R, W); 64 | BinaryStdOut.close(); 65 | } 66 | 67 | /** 68 | * Reads a sequence of bit encoded using LZW compression with 69 | * 12-bit codewords from standard input; expands them; and writes 70 | * the results to standard output. 71 | */ 72 | public static void expand() { 73 | String[] st = new String[L]; 74 | int i; // next available codeword value 75 | 76 | // initialize symbol table with all 1-character strings 77 | for (i = 0; i < R; i++) 78 | st[i] = "" + (char) i; 79 | st[i++] = ""; // (unused) lookahead for EOF 80 | 81 | int codeword = BinaryStdIn.readInt(W); 82 | if (codeword == R) return; // expanded message is empty string 83 | String val = st[codeword]; 84 | 85 | while (true) { 86 | BinaryStdOut.write(val); 87 | codeword = BinaryStdIn.readInt(W); 88 | if (codeword == R) break; 89 | String s = st[codeword]; 90 | if (i == codeword) s = val + val.charAt(0); // special case hack 91 | if (i < L) st[i++] = val + s.charAt(0); 92 | val = s; 93 | } 94 | BinaryStdOut.close(); 95 | } 96 | 97 | /** 98 | * Sample client that calls {@code compress()} if the command-line 99 | * argument is "-" an {@code expand()} if it is "+". 100 | * 101 | * @param args the command-line arguments 102 | */ 103 | public static void main(String[] args) { 104 | if (args[0].equals("-")) compress(); 105 | else if (args[0].equals("+")) expand(); 106 | else throw new IllegalArgumentException("Illegal command line argument"); 107 | } 108 | 109 | } 110 | 111 | /****************************************************************************** 112 | * Copyright 2002-2018, Robert Sedgewick and Kevin Wayne. 113 | * 114 | * This file is part of algs4.jar, which accompanies the textbook 115 | * 116 | * Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne, 117 | * Addison-Wesley Professional, 2011, ISBN 0-321-57351-X. 118 | * http://algs4.cs.princeton.edu 119 | * 120 | * 121 | * algs4.jar is free software: you can redistribute it and/or modify 122 | * it under the terms of the GNU General Public License as published by 123 | * the Free Software Foundation, either version 3 of the License, or 124 | * (at your option) any later version. 125 | * 126 | * algs4.jar is distributed in the hope that it will be useful, 127 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 128 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 129 | * GNU General Public License for more details. 130 | * 131 | * You should have received a copy of the GNU General Public License 132 | * along with algs4.jar. If not, see http://www.gnu.org/licenses. 133 | ******************************************************************************/ 134 | --------------------------------------------------------------------------------