├── Grades.png ├── LICENSE ├── README.md ├── Week 1 ├── CMYKtoRGB.class ├── CMYKtoRGB.java ├── GreatCircle.class ├── GreatCircle.java ├── HelloGoodbye.class ├── HelloGoodbye.java ├── HelloWorld.class ├── HelloWorld.java ├── Optional Enrichment │ ├── ThreeSort.class │ └── UniformRandomNumbers.class ├── Quiz 1 - Basic Programming Concepts.png ├── RightTriangle.class └── RightTriangle.java ├── Week 10 ├── Bar.java ├── BarChart.java ├── BarChartRacer.java └── Quiz 10 - Programming Languages.png ├── Week 2 ├── BandMatrix.java ├── GeneralizedHarmonic.java ├── Quiz 2 - Conditionals and Loops.png ├── RandomWalker.java └── RandomWalkers.java ├── Week 3 ├── Birthday.java ├── DiscreteDistribution.java ├── Minesweeper.java ├── Quiz 3 - Arrays.png └── ThueMorse.java ├── Week 4 ├── Checkerboard.java ├── Quiz 4 - Input and Output.png ├── ShannonEntropy.java └── WorldMap.java ├── Week 5 ├── ActivationFunction.java ├── AudioCollage.java ├── Divisors.java └── Quiz 5 - Functions and Libraries.png ├── Week 6 ├── Quiz 6 - Recursion.png ├── RecursiveSquares.java ├── RevesPuzzle.java ├── TrinomialBrute.java └── TrinomialDP.java ├── Week 7 ├── Inversions.java ├── MaximumSquareSubmatrix.java ├── Quiz 7 - Performance.png └── Ramanujan.java ├── Week 8 ├── Huntingtons.java ├── KernelFilter.java └── Quiz 8 - Abstract Data Types.png └── Week 9 ├── Clock.java ├── ColorHSB.java └── Quiz 9 - Creating Data Types.png /Grades.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Grades.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Liu Haohui 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Computer-Science-Programming-with-a-Purpose 2 | Quiz and Programming Assignment Solutions to the Coursera [Computer Science: Programming with a Purpose](https://www.coursera.org/learn/cs-programming-java) course by Princeton University 3 | 4 | **Instructors**: [Robert Sedgewick](https://www.coursera.org/instructor/~250165), [Kevin Wayne](https://www.coursera.org/instructor/~246867) 5 | 6 | ## Introduction 7 | This repository contains the quiz and programming assignment solutions to the course. All quizzes and programming assignments have achieved the 100% score. 8 | 9 | Date Started: 3 December 2020 10 | 11 | Date Completed: 10 February 2021 12 | 13 | The quiz and programming assignment solutions are uploaded only for reference purposes. Please attempt the quizzes and programming assignments yourself and only look at the explanations if you find that you still can't understand it after consulting the discussion forums and reviewing the lecture content. 14 | 15 | ## Quick Access 16 | Week 1: Basic Programming Concepts 17 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%201) 18 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%201/Quiz%201%20-%20Basic%20Programming%20Concepts.png) 19 | * [Optional Enrichment](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%201/Optional%20Enrichment) 20 | 21 | Week 2: Conditionals and Loops 22 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%202) 23 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%202/Quiz%202%20-%20Conditionals%20and%20Loops.png) 24 | 25 | Week 3: Arrays 26 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%203) 27 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%203/Quiz%203%20-%20Arrays.png) 28 | 29 | Week 4: Input and Output 30 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%204) 31 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%204/Quiz%204%20-%20Input%20and%20Output.png) 32 | 33 | Week 5: Functions and Libraries 34 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%205) 35 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%205/Quiz%205%20-%20Functions%20and%20Libraries.png) 36 | 37 | Week 6: Recursion 38 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%206) 39 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%206/Quiz%206%20-%20Recursion.png) 40 | 41 | Week 7: Performance 42 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%207) 43 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%207/Quiz%207%20-%20Performance.png) 44 | 45 | Week 8: Abstract Data Types 46 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%208) 47 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%208/Quiz%208%20-%20Abstract%20Data%20Types.png) 48 | 49 | Week 9: Creating Data Types 50 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%209) 51 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%209/Quiz%209%20-%20Creating%20Data%20Types.png) 52 | 53 | Week 10: Programming Languages 54 | * [Programming Assignments](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/tree/main/Week%2010) 55 | * [Quiz](https://github.com/liuhh02/Computer-Science-Programming-with-a-Purpose/blob/main/Week%2010/Quiz%2010%20-%20Programming%20Languages.png) 56 | 57 | ![Grades](Grades.png) 58 | -------------------------------------------------------------------------------- /Week 1/CMYKtoRGB.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/CMYKtoRGB.class -------------------------------------------------------------------------------- /Week 1/CMYKtoRGB.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class CMYKtoRGB { 8 | public static void main(String[] args) { 9 | double cyan = Double.parseDouble(args[0]); 10 | double magenta = Double.parseDouble(args[1]); 11 | double yellow = Double.parseDouble(args[2]); 12 | double black = Double.parseDouble(args[3]); 13 | double white = 1 - black; 14 | int red = (int) Math.round(255 * white * (1 - cyan)); 15 | int green = (int) Math.round(255 * white * (1 - magenta)); 16 | int blue = (int) Math.round(255 * white * (1 - yellow)); 17 | System.out.println("red = " + red); 18 | System.out.println("green = " + green); 19 | System.out.println("blue = " + blue); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Week 1/GreatCircle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/GreatCircle.class -------------------------------------------------------------------------------- /Week 1/GreatCircle.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class GreatCircle { 8 | public static void main(String[] args) { 9 | double x1 = Double.parseDouble(args[0]); 10 | double y1 = Double.parseDouble(args[1]); 11 | double x2 = Double.parseDouble(args[2]); 12 | double y2 = Double.parseDouble(args[3]); 13 | double xr1 = Math.toRadians(x1); 14 | double yr1 = Math.toRadians(y1); 15 | double xr2 = Math.toRadians(x2); 16 | double yr2 = Math.toRadians(y2); 17 | double inparens1 = ((xr2 - xr1) / 2); 18 | double cosx = (Math.cos(xr1) * Math.cos(xr2)); 19 | double inparens2 = ((yr2 - yr1) / 2); 20 | double sinsq1 = (Math.sin(inparens1) * Math.sin(inparens1)); 21 | double sinsq2 = (Math.sin(inparens2) * Math.sin(inparens2)); 22 | double sqrt = Math.sqrt(sinsq1 + (cosx * sinsq2)); 23 | double radius = 6371.0; 24 | double distance = (2 * radius * Math.asin(sqrt)); 25 | System.out.println(distance + " kilometers"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Week 1/HelloGoodbye.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/HelloGoodbye.class -------------------------------------------------------------------------------- /Week 1/HelloGoodbye.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class HelloGoodbye { 8 | public static void main(String[] args) { 9 | System.out.println("Hello " + args[0] + " and " + args[1] + "."); 10 | System.out.println("Goodbye " + args[1] + " and " + args[0] + "."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Week 1/HelloWorld.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/HelloWorld.class -------------------------------------------------------------------------------- /Week 1/HelloWorld.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class HelloWorld { 8 | public static void main(String[] args) { 9 | System.out.println("Hello, World"); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Week 1/Optional Enrichment/ThreeSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/Optional Enrichment/ThreeSort.class -------------------------------------------------------------------------------- /Week 1/Optional Enrichment/UniformRandomNumbers.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/Optional Enrichment/UniformRandomNumbers.class -------------------------------------------------------------------------------- /Week 1/Quiz 1 - Basic Programming Concepts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/Quiz 1 - Basic Programming Concepts.png -------------------------------------------------------------------------------- /Week 1/RightTriangle.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 1/RightTriangle.class -------------------------------------------------------------------------------- /Week 1/RightTriangle.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class RightTriangle { 8 | public static void main(String[] args) { 9 | int first = Integer.parseInt(args[0]); 10 | int second = Integer.parseInt(args[1]); 11 | int third = Integer.parseInt(args[2]); 12 | boolean isPositive; 13 | isPositive = (first > 0) && (second > 0) && (third >= 0); 14 | boolean correct; 15 | correct = isPositive && (first * first + second * second == third * third 16 | || first * first + third * third == second * second 17 | || third * third + second * second == first * first); 18 | System.out.println(correct); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Week 10/Bar.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | import java.util.Arrays; 8 | 9 | public class Bar implements Comparable { 10 | private final String name, category; 11 | private final int value; 12 | 13 | // Creates a new bar. 14 | public Bar(String name, int value, String category) { 15 | if (name == null || value < 0 || category == null) throw new IllegalArgumentException(); 16 | this.name = name; 17 | this.value = value; 18 | this.category = category; 19 | 20 | } 21 | 22 | // Returns the name of this bar. 23 | public String getName() { 24 | return this.name; 25 | } 26 | 27 | // Returns the value of this bar. 28 | public int getValue() { 29 | return this.value; 30 | } 31 | 32 | // Returns the category of this bar. 33 | public String getCategory() { 34 | return this.category; 35 | } 36 | 37 | // Compare two bars by value. 38 | public int compareTo(Bar that) { 39 | if (that == null) throw new NullPointerException(); 40 | return Integer.compare(this.value, that.value); 41 | } 42 | 43 | public static void main(String[] args) { 44 | // create an array of 10 bars 45 | Bar[] bars = new Bar[10]; 46 | bars[0] = new Bar("Beijing", 22674, "East Asia"); 47 | bars[1] = new Bar("Cairo", 19850, "Middle East"); 48 | bars[2] = new Bar("Delhi", 27890, "South Asia"); 49 | bars[3] = new Bar("Dhaka", 19633, "South Asia"); 50 | bars[4] = new Bar("Mexico City", 21520, "Latin America"); 51 | bars[5] = new Bar("Mumbai", 22120, "South Asia"); 52 | bars[6] = new Bar("Osaka", 20409, "East Asia"); 53 | bars[7] = new Bar("São Paulo", 21698, "Latin America"); 54 | bars[8] = new Bar("Shanghai", 25779, "East Asia"); 55 | bars[9] = new Bar("Tokyo", 38194, "East Asia"); 56 | 57 | // sort in ascending order by weight 58 | Arrays.sort(bars); 59 | 60 | for (int i = 0; i < bars.length; i++) { 61 | StdOut.println( 62 | bars[i].getName() + " (" + bars[i].getCategory() + "): " + bars[i].getValue()); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /Week 10/BarChart.java: -------------------------------------------------------------------------------- 1 | import java.awt.Color; 2 | import java.awt.Font; 3 | import java.util.ArrayList; 4 | import java.util.TreeMap; 5 | 6 | /** 7 | * The {@code BarChart} class represents a library for drawing static bar chart. 8 | * It supports adding a bar (with a specified name, value, and category) and 9 | * drawing all of the bars to the screen using standard draw. 10 | * The bars are drawn horizontally (in the order in which they are added from 11 | * top to bottom) and colored according to the category. 12 | * The name and value of the bar and drawn with the bar. 13 | * 14 | * @author Kevin Wayne 15 | * 16 | */ 17 | public class BarChart { 18 | 19 | // color palette for bars 20 | private static final Color[] COLORS = initColors(); 21 | 22 | private final String title; // bar chart title 23 | private final String xAxisLabel; // x-axis label 24 | private final String dataSource; // data source 25 | private String caption; // caption 26 | private TreeMap colorOf; // map category to color 27 | private ArrayList names; // list of bar names 28 | private ArrayList values; // list of bar values 29 | private ArrayList colors; // list of bar colors 30 | private boolean isSetMaxValue = false; 31 | private int maxValue = 0; 32 | 33 | /** 34 | * Creates a new bar chart with the given title, x-axis label, and data source. 35 | * 36 | * @param title the title 37 | * @param xAxisLabel the x-axis label 38 | * @param dataSource the source of the data 39 | */ 40 | public BarChart(String title, String xAxisLabel, String dataSource) { 41 | if (title == null) throw new IllegalArgumentException("name is null"); 42 | if (xAxisLabel == null) throw new IllegalArgumentException("x-axis label is null"); 43 | if (dataSource == null) throw new IllegalArgumentException("data source is null"); 44 | this.title = title; 45 | this.xAxisLabel = xAxisLabel; 46 | this.dataSource = dataSource; 47 | colorOf = new TreeMap(); 48 | reset(); 49 | } 50 | 51 | // initialize the colors 52 | private static Color[] initColors() { 53 | 54 | // 12 colors from http://colorbrewer2.org/#type=qualitative&scheme=Set3&n=12 55 | String[] hex12 = { 56 | "#80b1d3", "#fdb462", "#b3de69", "#fccde5", 57 | "#8dd3c7", "#ffffb3", "#bebada", "#fb8072", 58 | "#d9d9d9", "#bc80bd", "#ccebc5", "#ffed6f" 59 | }; 60 | 61 | // 20 colors from https://vega.github.io/vega/docs/schemes/ 62 | // replaced #d62728 with #d64c4c 63 | String[] hex20 = { 64 | "#aec7e8", "#c5b0d5", "#c49c94", "#dbdb8d", "#17becf", 65 | "#9edae5", "#f7b6d2", "#c7c7c7", "#1f77b4", "#ff7f0e", 66 | "#ffbb78", "#98df8a", "#d64c4c", "#2ca02c", "#9467bd", 67 | "#8c564b", "#ff9896", "#e377c2", "#7f7f7f", "#bcbd22", 68 | }; 69 | 70 | // use 20 colors 71 | Color[] colors = new Color[hex20.length]; 72 | for (int i = 0; i < hex20.length; i++) 73 | colors[i] = Color.decode(hex20[i]); 74 | return colors; 75 | } 76 | 77 | /** 78 | * Sets the maximum x-value of this bar chart (instead of having it set automatially). 79 | * This method is useful if you know that the values stay within a given range. 80 | * 81 | * @param maxValue the maximum value 82 | */ 83 | public void setMaxValue(int maxValue) { 84 | if (maxValue <= 0) throw new IllegalArgumentException("maximum value must be positive"); 85 | this.isSetMaxValue = true; 86 | this.maxValue = maxValue; 87 | } 88 | 89 | /** 90 | * Sets the caption of this bar chart. 91 | * The caption is drawn in the lower-right part of the window. 92 | * 93 | * @param caption the caption 94 | */ 95 | public void setCaption(String caption) { 96 | if (caption == null) throw new IllegalArgumentException("caption is null"); 97 | this.caption = caption; 98 | } 99 | 100 | /** 101 | * Adds a bar to the bar chart. 102 | * The length of a bar is proportional to its value. 103 | * The bars are drawn from top to bottom in the order they are added. 104 | * All bars from the same category are drawn with the same color. 105 | * 106 | * @param name the name of the bar 107 | * @param value the value of the bar 108 | * @param category the category of bar 109 | */ 110 | public void add(String name, int value, String category) { 111 | if (name == null) throw new IllegalArgumentException("name is null"); 112 | if (category == null) throw new IllegalArgumentException("category is null"); 113 | if (value <= 0) throw new IllegalArgumentException("value must be positive"); 114 | 115 | if (!colorOf.containsKey(category)) { 116 | colorOf.put(category, COLORS[colorOf.size() % COLORS.length]); 117 | } 118 | Color color = colorOf.get(category); 119 | names.add(name); 120 | values.add(value); 121 | colors.add(color); 122 | } 123 | 124 | /** 125 | * Removes all of the bars from this bar chart (but keep the color scheme). 126 | * This method is convenient when drawing an animated bar chart. 127 | */ 128 | public void reset() { 129 | names = new ArrayList(); 130 | values = new ArrayList(); 131 | colors = new ArrayList(); 132 | caption = ""; 133 | } 134 | 135 | // compute units (multiple of 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, ...) 136 | // so that between 4 and 8 axes labels 137 | private static int getUnits(double xmax) { 138 | int units = 1; 139 | while (Math.floor(xmax / units) >= 8) { 140 | // hack to identify 20, 200, 2000, ... 141 | if (units % 9 == 2) units = units * 5 / 2; 142 | else units = units * 2; 143 | } 144 | return units; 145 | } 146 | 147 | /** 148 | * Draws this bar chart to standard draw. 149 | */ 150 | public void draw() { 151 | // nothing to draw 152 | if (names.isEmpty()) return; 153 | 154 | // leave room for at least 8 bars 155 | int numberOfBars = Math.max(8, names.size()); 156 | 157 | // set the scale of the coordinate axes 158 | double xmax = Double.NEGATIVE_INFINITY; 159 | for (int value : values) { 160 | if (value > xmax) xmax = value; 161 | } 162 | if (isSetMaxValue) xmax = maxValue; 163 | 164 | StdDraw.setXscale(-0.01 * xmax, 1.2 * xmax); 165 | StdDraw.setYscale(-0.01 * numberOfBars, numberOfBars * 1.25); 166 | 167 | // draw title 168 | StdDraw.setPenColor(StdDraw.BLACK); 169 | StdDraw.setFont(new Font("SansSerif", Font.BOLD, 24)); 170 | StdDraw.text(0.6 * xmax, numberOfBars * 1.2, title); 171 | 172 | // draw x-axis label 173 | StdDraw.setPenColor(StdDraw.GRAY); 174 | StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 16)); 175 | StdDraw.textLeft(0, numberOfBars * 1.10, xAxisLabel); 176 | 177 | // draw axes 178 | int units = getUnits(xmax); 179 | StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 12)); 180 | for (int unit = 0; unit <= xmax; unit += units) { 181 | StdDraw.setPenColor(StdDraw.GRAY); 182 | StdDraw.text(unit, numberOfBars * 1.02, String.format("%,d", unit)); 183 | StdDraw.setPenColor(new Color(230, 230, 230)); 184 | StdDraw.line(unit, 0.1, unit, numberOfBars * 1.0); 185 | } 186 | 187 | // draw caption 188 | StdDraw.setPenColor(StdDraw.LIGHT_GRAY); 189 | if (caption.length() <= 4) StdDraw.setFont(new Font("SansSerif", Font.BOLD, 100)); 190 | else if (caption.length() <= 8) StdDraw.setFont(new Font("SansSerif", Font.BOLD, 60)); 191 | else StdDraw.setFont(new Font("SansSerif", Font.BOLD, 40)); 192 | StdDraw.textRight(1.15 * xmax, 0.2 * numberOfBars, caption); 193 | 194 | // draw data source acknowledgment 195 | StdDraw.setPenColor(StdDraw.LIGHT_GRAY); 196 | StdDraw.setFont(new Font("SansSerif", Font.PLAIN, 14)); 197 | StdDraw.textRight(1.14 * xmax, 0.1 * numberOfBars, dataSource); 198 | 199 | // draw bars 200 | for (int i = 0; i < names.size(); i++) { 201 | String name = names.get(i); 202 | int value = values.get(i); 203 | Color color = colors.get(i); 204 | StdDraw.setPenColor(color); 205 | StdDraw.filledRectangle(0.5 * value, numberOfBars - i - 0.5, 0.5 * value, 0.4); 206 | StdDraw.setPenColor(StdDraw.BLACK); 207 | int fontSize = (int) Math.ceil(14 * 10.0 / numberOfBars); 208 | StdDraw.setFont(new Font("SansSerif", Font.BOLD, fontSize)); 209 | StdDraw.textRight(value - 0.01 * xmax, numberOfBars - i - 0.5, name); 210 | StdDraw.setFont(new Font("SansSerif", Font.PLAIN, fontSize)); 211 | StdDraw.setPenColor(StdDraw.DARK_GRAY); 212 | StdDraw.textLeft(value + 0.01 * xmax, numberOfBars - i - 0.5, String.format("%,d", value)); 213 | } 214 | } 215 | 216 | // sample client 217 | public static void main(String[] args) { 218 | // create the bar chart 219 | String title = "The 10 most populous cities"; 220 | String xAxis = "Population (thousands)"; 221 | String source = "Source: United Nations"; 222 | BarChart chart = new BarChart(title, xAxis, source); 223 | chart.setCaption("2018"); 224 | 225 | // add the bars to the bar chart 226 | chart.add("Tokyo", 38194, "East Asia"); 227 | chart.add("Delhi", 27890, "South Asia"); 228 | chart.add("Shanghai", 25779, "East Asia"); 229 | chart.add("Beijing", 22674, "East Asia"); 230 | chart.add("Mumbai", 22120, "South Asia"); 231 | chart.add("São Paulo", 21698, "Latin America"); 232 | chart.add("Mexico City", 21520, "Latin America"); 233 | chart.add("Osaka", 20409, "East Asia"); 234 | chart.add("Cairo", 19850, "Middle East"); 235 | chart.add("Dhaka", 19633, "South Asia"); 236 | 237 | // draw the bar chart 238 | StdDraw.setCanvasSize(1000, 700); 239 | StdDraw.enableDoubleBuffering(); 240 | chart.draw(); 241 | StdDraw.show(); 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /Week 10/BarChartRacer.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | import java.util.Arrays; 8 | 9 | public class BarChartRacer { 10 | public static void main(String[] args) { 11 | StdDraw.setCanvasSize(1000, 700); 12 | StdDraw.enableDoubleBuffering(); 13 | 14 | String fileName = args[0]; 15 | int k = Integer.parseInt(args[1]); 16 | In in = new In(fileName); 17 | String title = in.readLine(); 18 | String xAxis = in.readLine(); 19 | String source = in.readLine(); 20 | in.readLine(); 21 | 22 | BarChart chart = new BarChart(title, xAxis, source); 23 | while (in.hasNextLine()) { 24 | int n = Integer.parseInt(in.readLine()); 25 | Bar[] bars = new Bar[n]; 26 | String year = ""; 27 | for (int i = 0; i < n; i++) { 28 | String record = in.readLine(); 29 | String[] recordarr = record.split(","); 30 | year = recordarr[0]; 31 | String name = recordarr[1]; 32 | int value = Integer.parseInt(recordarr[3]); 33 | String category = recordarr[4]; 34 | bars[i] = new Bar(name, value, category); 35 | } 36 | Arrays.sort(bars); 37 | chart.setCaption(year); 38 | for (int i = bars.length - 1; i > bars.length - 1 - k; i--) { 39 | chart.add(bars[i].getName(), bars[i].getValue(), bars[i].getCategory()); 40 | } 41 | StdDraw.clear(); 42 | chart.draw(); 43 | StdDraw.show(); 44 | StdDraw.pause(100); 45 | chart.reset(); 46 | in.readLine(); 47 | } 48 | chart.reset(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Week 10/Quiz 10 - Programming Languages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 10/Quiz 10 - Programming Languages.png -------------------------------------------------------------------------------- /Week 2/BandMatrix.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class BandMatrix { 8 | public static void main(String[] args) { 9 | int n = Integer.parseInt(args[0]); 10 | int width = Integer.parseInt(args[1]); 11 | for (int i = 0; i < n; i++) { // i is the row no. 12 | for (int j = 0; j < n; j++) { // j is the col no. 13 | if (Math.abs(j - i) > width) System.out.print("0 "); 14 | else System.out.print("* "); 15 | } 16 | System.out.println(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Week 2/GeneralizedHarmonic.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class GeneralizedHarmonic { 8 | public static void main(String[] args) { 9 | int n = Integer.parseInt(args[0]); 10 | int r = Integer.parseInt(args[1]); 11 | double harmonic = 0; 12 | for (int i = 1; i <= n; i++) { 13 | harmonic += 1.0 / Math.pow(i, r); 14 | } 15 | System.out.println(harmonic); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Week 2/Quiz 2 - Conditionals and Loops.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 2/Quiz 2 - Conditionals and Loops.png -------------------------------------------------------------------------------- /Week 2/RandomWalker.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class RandomWalker { 8 | public static void main(String[] args) { 9 | int r = Integer.parseInt(args[0]); 10 | int x = 0; 11 | int y = 0; 12 | int i = 0; 13 | System.out.println("(0, 0)"); 14 | while (Math.abs(x) + Math.abs(y) != r) { 15 | double prob1 = Math.random(); 16 | if (prob1 < 0.25) x++; 17 | else if (prob1 < 0.5) x--; 18 | else if (prob1 < 0.75) y++; 19 | else y--; 20 | System.out.println("(" + x + ", " + y + ")"); 21 | i++; 22 | } 23 | System.out.println("steps = " + i); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Week 2/RandomWalkers.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class RandomWalkers { 8 | public static void main(String[] args) { 9 | int r = Integer.parseInt(args[0]); 10 | int trials = Integer.parseInt(args[1]); 11 | double n = trials; 12 | int sum = 0; 13 | for (int j = 0; j < trials; j++) { 14 | int x = 0; 15 | int y = 0; 16 | int i = 0; 17 | while (Math.abs(x) + Math.abs(y) != r) { 18 | double prob1 = Math.random(); 19 | if (prob1 < 0.25) x++; 20 | else if (prob1 < 0.5) x--; 21 | else if (prob1 < 0.75) y++; 22 | else y--; 23 | i++; 24 | } 25 | sum += i; 26 | } 27 | double dsum = sum; 28 | double avg = dsum / n; 29 | System.out.println("average number of steps = " + avg); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Week 3/Birthday.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Birthday { 8 | public static void main(String[] args) { 9 | int n = Integer.parseInt(args[0]); // n is the no. of days 10 | int trials = Integer.parseInt(args[1]); 11 | double[] countarr = new double[n + 2]; 12 | for (int i = 0; i < trials; i++) { 13 | boolean found = false; 14 | boolean[] twin = new boolean[n]; 15 | int count = 0; 16 | while (!found) { 17 | double birthday = n * Math.random(); 18 | int bday = (int) birthday; 19 | if (twin[bday]) { 20 | found = true; 21 | countarr[count] += 1.0; 22 | } 23 | else { 24 | twin[bday] = true; 25 | count++; 26 | } 27 | } 28 | 29 | } 30 | double frac = 0.0; 31 | int i = 0; 32 | while (frac < 0.5) { 33 | double dtrials = trials; 34 | frac += countarr[i] / dtrials; 35 | System.out.print(i + 1 + "\t" + (int) countarr[i] + "\t" + frac); 36 | System.out.println(); 37 | i++; 38 | } 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /Week 3/DiscreteDistribution.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class DiscreteDistribution { 8 | public static void main(String[] args) { 9 | int m = Integer.parseInt(args[0]); 10 | int sum = 0; 11 | int[] s = new int[args.length + 1]; 12 | for (int i = 1; i < args.length; i++) { 13 | sum += Integer.parseInt(args[i]); 14 | } 15 | // System.out.println("sum is " + sum); 16 | s[0] = 0; 17 | for (int i = 1; i < args.length; i++) { 18 | s[i] = Integer.parseInt(args[i]) + s[i - 1]; 19 | } 20 | s[args.length] = s[args.length - 1] + 1; 21 | for (int i = 0; i < m; i++) { 22 | double rand = sum * Math.random(); 23 | int randi = (int) rand; 24 | // System.out.println("random number is " + randi); 25 | for (int j = 0; j < args.length; j++) { 26 | if (randi >= s[j] && randi < s[j + 1]) { 27 | System.out.print(j + 1 + " "); 28 | break; 29 | } 30 | } 31 | // System.out.println("random number is " + randi); 32 | // System.out.print(randi + " "); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Week 3/Minesweeper.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Minesweeper { 8 | public static void main(String[] args) { 9 | int m = Integer.parseInt(args[0]); 10 | int n = Integer.parseInt(args[1]); 11 | int k = Integer.parseInt(args[2]); 12 | int[][] mine = new int[m + 2][n + 2]; 13 | int[][] minenum = new int[m + 2][n + 2]; 14 | int landmines = 0; 15 | while (landmines < k) { 16 | double rand = Math.random() * m * n; 17 | double randx = rand / n; 18 | int randxd = (int) randx; 19 | double randy = rand % n; 20 | int randyd = (int) randy; 21 | if (mine[randxd + 1][randyd + 1] != 1) { 22 | mine[randxd + 1][randyd + 1] = 1; 23 | landmines++; 24 | } 25 | } 26 | for (int i = 0; i < m; i++) { 27 | for (int j = 0; j < n; j++) { 28 | if (mine[i + 1][j + 1] 29 | == 0) { // (1, 1) = (0, 1) + (1, 0) + (1, 2) + (2, 1) + (0, 0) + (2, 2) + (2, 0) + (0, 2) 30 | minenum[i + 1][j + 1] = mine[i][j + 1] + mine[i + 1][j] + mine[i + 1][j 31 | + 2] + mine[i + 2][j + 1] + mine[i][j] + mine[i + 2][j + 2] + mine[i 32 | + 2][j] + mine[i][j + 2]; 33 | } 34 | else minenum[i + 1][j + 1] = 1; 35 | } 36 | } 37 | for (int i = 0; i < m; i++) { 38 | for (int j = 0; j < n; j++) { 39 | if (mine[i + 1][j + 1] == 1) System.out.print("* "); 40 | else System.out.print(minenum[i + 1][j + 1] + " "); 41 | } 42 | System.out.println(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Week 3/Quiz 3 - Arrays.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 3/Quiz 3 - Arrays.png -------------------------------------------------------------------------------- /Week 3/ThueMorse.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class ThueMorse { 8 | public static void main(String[] args) { 9 | int n = Integer.parseInt(args[0]); 10 | int[] seq = new int[n]; 11 | seq[0] = 0; 12 | for (int i = 1; i < n; i++) { 13 | if (i % 2 == 0) seq[i] = seq[i / 2]; 14 | else seq[i] = 1 - seq[i - 1]; 15 | } 16 | for (int i = 0; i < n; i++) { 17 | for (int j = 0; j < n; j++) { 18 | if (seq[i] == seq[j]) System.out.print("+ "); 19 | else System.out.print("- "); 20 | } 21 | System.out.println(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Week 4/Checkerboard.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Checkerboard { 8 | public static void main(String[] args) { 9 | int n = Integer.parseInt(args[0]); 10 | StdDraw.setScale(0, n); 11 | for (int i = 0; i < n; i++) { 12 | for (int j = 0; j < n; j++) { 13 | if ((i + j) % 2 == 0) { 14 | StdDraw.setPenColor(StdDraw.BLUE); 15 | } 16 | else { 17 | StdDraw.setPenColor(StdDraw.LIGHT_GRAY); 18 | } 19 | StdDraw.filledSquare(i + 0.5, j + 0.5, 0.5); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Week 4/Quiz 4 - Input and Output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 4/Quiz 4 - Input and Output.png -------------------------------------------------------------------------------- /Week 4/ShannonEntropy.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class ShannonEntropy { 8 | public static void main(String[] args) { 9 | int m = Integer.parseInt(args[0]); 10 | int[] arr = new int[m]; 11 | double count = 0.0; 12 | double entropy = 0.0; 13 | while (!StdIn.isEmpty()) { 14 | int k = StdIn.readInt(); 15 | arr[k - 1] += 1; 16 | count++; 17 | } 18 | for (int i = 0; i < m; i++) { 19 | if (arr[i] != 0) { 20 | double prop = arr[i] / count; 21 | entropy -= prop * (Math.log(prop) / Math.log(2)); 22 | } 23 | } 24 | StdOut.printf("%.4f\n", entropy); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Week 4/WorldMap.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class WorldMap { 8 | public static void main(String[] args) { 9 | int width = StdIn.readInt(); 10 | int height = StdIn.readInt(); 11 | StdDraw.setCanvasSize(width, height); 12 | StdDraw.setXscale(0.0, width); 13 | StdDraw.setYscale(0.0, height); 14 | while (!StdIn.isEmpty()) { 15 | String name = StdIn.readString(); 16 | int vertices = StdIn.readInt(); 17 | double[] xCoord = new double[vertices]; 18 | double[] yCoord = new double[vertices]; 19 | for (int i = 0; i < vertices; i++) { 20 | xCoord[i] = StdIn.readDouble(); 21 | yCoord[i] = StdIn.readDouble(); 22 | } 23 | StdDraw.polygon(xCoord, yCoord); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Week 5/ActivationFunction.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class ActivationFunction { 8 | public static double heaviside(double x) { 9 | if (Double.isNaN(x)) return Double.NaN; 10 | if (x < 0.0) return 0.0; 11 | else if (x == 0.0) return 0.5; 12 | else return 1.0; 13 | } 14 | 15 | public static double sigmoid(double x) { 16 | if (Double.isNaN(x)) return Double.NaN; 17 | return 1.0 / (1.0 + Math.exp(-x)); 18 | } 19 | 20 | public static double tanh(double x) { 21 | if (Double.isNaN(x)) return Double.NaN; 22 | if (x >= 20) return 1.0; 23 | else if (x <= -20) return -1.0; 24 | else return (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)); 25 | } 26 | 27 | public static double softsign(double x) { 28 | if (Double.isNaN(x)) return Double.NaN; 29 | else if (x == Double.POSITIVE_INFINITY) return 1.0; 30 | else if (x == Double.NEGATIVE_INFINITY) return -1.0; 31 | return (x / (1.0 + Math.abs(x))); 32 | } 33 | 34 | public static double sqnl(double x) { 35 | if (Double.isNaN(x)) return Double.NaN; 36 | if (x <= -2.0) return -1; 37 | else if (x < 0.0) return (x + x * x / 4.0); 38 | else if (x < 2.0) return (x - x * x / 4.0); 39 | else return 1.0; 40 | } 41 | 42 | public static void main(String[] args) { 43 | double x = Double.parseDouble(args[0]); 44 | System.out.println("heaviside(" + x + ") = " + heaviside(x)); 45 | System.out.println("sigmoid(" + x + ") = " + sigmoid(x)); 46 | System.out.println("tanh(" + x + ") = " + tanh(x)); 47 | System.out.println("softsign(" + x + ") = " + softsign(x)); 48 | System.out.println("sqnl(" + x + ") = " + sqnl(x)); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Week 5/AudioCollage.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class AudioCollage { 8 | public static double[] amplify(double[] a, double alpha) { 9 | double[] b = new double[a.length]; 10 | for (int i = 0; i < a.length; i++) { 11 | b[i] = a[i] * alpha; 12 | } 13 | return b; 14 | } 15 | 16 | public static double[] reverse(double[] a) { 17 | double[] b = new double[a.length]; 18 | for (int i = 0; i < a.length; i++) { 19 | b[a.length - i - 1] = a[i]; 20 | } 21 | return b; 22 | } 23 | 24 | public static double[] merge(double[] a, double[] b) { 25 | double[] c = new double[a.length + b.length]; 26 | for (int i = 0; i < a.length; i++) { 27 | c[i] = a[i]; 28 | } 29 | for (int i = 0; i < b.length; i++) { 30 | c[i + a.length] = b[i]; 31 | } 32 | return c; 33 | } 34 | 35 | public static double[] mix(double[] a, double[] b) { 36 | if (a.length == b.length) { 37 | double[] c = new double[a.length]; 38 | for (int i = 0; i < a.length; i++) { 39 | c[i] = a[i] + b[i]; 40 | } 41 | return c; 42 | } 43 | else if (a.length < b.length) { 44 | double[] c = new double[b.length]; 45 | double[] d = new double[b.length]; 46 | for (int i = 0; i < a.length; i++) { 47 | c[i] = a[i]; 48 | } 49 | for (int i = 0; i < b.length; i++) { 50 | d[i] = c[i] + b[i]; 51 | } 52 | return d; 53 | } 54 | else { 55 | double[] c = new double[a.length]; 56 | double[] d = new double[a.length]; 57 | for (int i = 0; i < b.length; i++) { 58 | c[i] = b[i]; 59 | } 60 | for (int i = 0; i < a.length; i++) { 61 | d[i] = a[i] + c[i]; 62 | } 63 | return d; 64 | } 65 | } 66 | 67 | public static double[] changeSpeed(double[] a, double alpha) { 68 | double samples = (a.length / alpha); 69 | int samp = (int) samples; 70 | double[] b = new double[samp]; 71 | for (int i = 0; i < samp; i++) { 72 | b[i] = a[(int) (i * alpha)]; 73 | } 74 | return b; 75 | } 76 | 77 | public static void main(String[] args) { 78 | double[] sample1 = StdAudio.read("cow.wav"); 79 | double[] sample2 = StdAudio.read("silence.wav"); 80 | double[] sample3 = StdAudio.read("piano.wav"); 81 | double[] sample4 = StdAudio.read("harp.wav"); 82 | double[] sample5 = StdAudio.read("chimes.wav"); 83 | double[] edit1 = amplify(sample1, 0.5); 84 | double[] edit2 = reverse(sample3); 85 | double[] edit3 = merge(edit1, sample4); 86 | double[] edit4 = changeSpeed(sample5, 1.2); 87 | double[] edit5 = mix(edit2, edit4); 88 | double[] edit6 = merge(edit3, edit5); 89 | double[] edit7 = merge(edit6, sample2); 90 | StdAudio.play(edit7); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /Week 5/Divisors.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Divisors { 8 | public static int gcd(int a, int b) { 9 | if (a == 0 && b == 0) return 0; 10 | else if (b == 0) return Math.abs(a); 11 | int absa = Math.abs(a); 12 | int absb = Math.abs(b); 13 | while (absa % absb != 0) { 14 | int placeholder = absa; 15 | absa = absb; 16 | absb = placeholder % absb; 17 | } 18 | return absb; 19 | } 20 | 21 | public static int lcm(int a, int b) { 22 | if (a == 0 || b == 0) return 0; 23 | else { 24 | int absa = Math.abs(a); 25 | int absb = Math.abs(b); 26 | return (absa / gcd(a, b) * absb); 27 | } 28 | 29 | } 30 | 31 | public static boolean areRelativelyPrime(int a, int b) { 32 | return (gcd(a, b) == 1); 33 | } 34 | 35 | public static int totient(int n) { 36 | if (n <= 0) return 0; 37 | int count = 0; 38 | for (int i = 1; i <= n; i++) { 39 | if (areRelativelyPrime(n, i)) count++; 40 | } 41 | return count; 42 | } 43 | 44 | public static void main(String[] args) { 45 | int a = Integer.parseInt(args[0]); 46 | int b = Integer.parseInt(args[1]); 47 | System.out.println("gcd(" + a + ", " + b + ") = " + gcd(a, b)); 48 | System.out.println("lcm(" + a + ", " + b + ") = " + lcm(a, b)); 49 | System.out 50 | .println("areRelativelyPrime(" + a + ", " + b + ") = " + areRelativelyPrime(a, b)); 51 | System.out.println("totient(" + a + ") = " + totient(a)); 52 | System.out.println("totient(" + b + ") = " + totient(b)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Week 5/Quiz 5 - Functions and Libraries.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 5/Quiz 5 - Functions and Libraries.png -------------------------------------------------------------------------------- /Week 6/Quiz 6 - Recursion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 6/Quiz 6 - Recursion.png -------------------------------------------------------------------------------- /Week 6/RecursiveSquares.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class RecursiveSquares { 8 | public static void drawSquare(double x, double y, double length) { 9 | StdDraw.setPenColor(StdDraw.LIGHT_GRAY); 10 | StdDraw.filledSquare(x, y, 0.5 * length); 11 | StdDraw.setPenColor(StdDraw.BLACK); 12 | StdDraw.square(x, y, 0.5 * length); 13 | } 14 | 15 | public static void draw(int n, double x, double y, double length) { 16 | if (n == 0) return; 17 | draw(n - 1, x - length / 2, y + length / 2, length / 2); 18 | draw(n - 1, x + length / 2, y + length / 2, length / 2); 19 | drawSquare(x, y, length); 20 | draw(n - 1, x - length / 2, y - length / 2, length / 2); 21 | draw(n - 1, x + length / 2, y - length / 2, length / 2); 22 | } 23 | 24 | public static void main(String[] args) { 25 | int n = Integer.parseInt(args[0]); 26 | draw(n, 0.5, 0.5, 0.5); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Week 6/RevesPuzzle.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class RevesPuzzle { 8 | private static void hanoi(int n, int k, String from, String temp, String to) { 9 | if (n == 0) return; 10 | hanoi(n - 1, k, from, to, temp); 11 | StdOut.println("Move disc " + (n + k) + " from " + from + " to " + to); 12 | hanoi(n - 1, k, temp, from, to); 13 | } 14 | 15 | private static void reves(int n, String from, String temp, String temp2, String to) { 16 | int k = (int) Math.round(n + 1 - Math.sqrt(2 * n + 1)); 17 | if (k == 0) { 18 | StdOut.println("Move disc " + 1 + " from " + from + " to " + to); 19 | return; 20 | } 21 | reves(k, from, to, temp2, temp); 22 | hanoi(n - k, k, from, temp2, to); 23 | reves(k, temp, from, temp2, to); 24 | } 25 | 26 | public static void main(String[] args) { 27 | int n = Integer.parseInt(args[0]); 28 | reves(n, "A", "B", "C", "D"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Week 6/TrinomialBrute.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class TrinomialBrute { 8 | public static long trinomial(int n, int k) { 9 | if (n == 0 && k == 0) return 1; 10 | if (k < -n || k > n) return 0; 11 | return trinomial(n - 1, k - 1) + trinomial(n - 1, k) + trinomial(n - 1, k + 1); 12 | } 13 | 14 | public static void main(String[] args) { 15 | int n = Integer.parseInt(args[0]); 16 | int k = Integer.parseInt(args[1]); 17 | StdOut.println(trinomial(n, k)); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Week 6/TrinomialDP.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class TrinomialDP { 8 | 9 | public static long trinomial(int n, int k) { 10 | n = Math.abs(n); 11 | k = Math.abs(k); 12 | if (k > n) return 0; 13 | if (n == 0 && k == 0) return 1; 14 | long[][] dp = new long[n + 2][n + 2]; 15 | dp[0][0] = 1; 16 | for (int i = 1; i <= n; i++) { 17 | for (int j = 0; j <= i; j++) { 18 | if (j == 0) dp[i][j] = dp[i - 1][j] + 2 * dp[i - 1][j + 1]; 19 | else dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] + dp[i - 1][j + 1]; 20 | } 21 | } 22 | return dp[n][k]; 23 | } 24 | 25 | public static void main(String[] args) { 26 | int n = Integer.parseInt(args[0]); 27 | int k = Integer.parseInt(args[1]); 28 | StdOut.println(trinomial(n, k)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Week 7/Inversions.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Inversions { 8 | public static long count(int[] a) { 9 | long num = 0; 10 | for (int i = 0; i < a.length; i++) { 11 | for (int j = i + 1; j < a.length; j++) { 12 | if (a[j] < a[i]) num++; 13 | } 14 | } 15 | return num; 16 | } 17 | 18 | public static int[] generate(int n, long k) { 19 | int[] arr = new int[n]; 20 | int counter = 1; 21 | long newk = k; 22 | if (k == ((long) n) * (n - 1) / 2) { 23 | for (int i = 0; i < n; i++) { 24 | arr[i] = n - i - 1; 25 | } 26 | return arr; 27 | } 28 | while (newk >= ((long) n) - counter) { 29 | arr[counter - 1] = n - counter; 30 | newk = newk - n + counter; 31 | counter++; 32 | } 33 | int index = n - (int) newk - 1; 34 | arr[index] = n - counter; 35 | for (int i = counter - 1; i < index; i++) { 36 | arr[i] = i - counter + 1; 37 | } 38 | for (int i = index + 1; i < n; i++) { 39 | arr[i] = i - counter; 40 | } 41 | return arr; 42 | } 43 | 44 | public static void main(String[] args) { 45 | int n = Integer.parseInt(args[0]); 46 | long k = Long.parseLong(args[1]); 47 | int[] arr = generate(n, k); 48 | for (int i = 0; i < n; i++) { 49 | StdOut.print(arr[i] + " "); 50 | } 51 | StdOut.println(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Week 7/MaximumSquareSubmatrix.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class MaximumSquareSubmatrix { 8 | public static int size(int[][] a) { 9 | int largest = 0; 10 | int[][] dp = new int[a.length + 1][a.length + 1]; 11 | for (int i = 1; i <= a.length; i++) { 12 | for (int j = 1; j <= a.length; j++) { 13 | if (a[i - 1][j - 1] == 1) { 14 | int min1 = Math.min(dp[i][j - 1], dp[i - 1][j]); 15 | dp[i][j] = Math.min(min1, dp[i - 1][j - 1]) + 1; 16 | } 17 | if (dp[i][j] > largest) largest = dp[i][j]; 18 | } 19 | } 20 | return largest; 21 | } 22 | 23 | public static void main(String[] args) { 24 | int n = StdIn.readInt(); 25 | int[][] a = new int[n][n]; 26 | while (!StdIn.isEmpty()) { 27 | for (int i = 0; i < n; i++) { 28 | for (int j = 0; j < n; j++) { 29 | a[i][j] = StdIn.readInt(); 30 | } 31 | } 32 | } 33 | 34 | StdOut.println(size(a)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Week 7/Quiz 7 - Performance.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 7/Quiz 7 - Performance.png -------------------------------------------------------------------------------- /Week 7/Ramanujan.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Ramanujan { 8 | public static boolean isRamanujan(long n) { 9 | int count = 0; 10 | int satisfied = 0; 11 | for (long i = 1; i < Math.cbrt(n); i++) { 12 | double b = Math.cbrt(n - i * i * i); 13 | if (Math.floor(b) == b) { 14 | if (count == 0) { 15 | satisfied = (int) b; 16 | count++; 17 | } 18 | else if (i != satisfied) count++; 19 | if (count == 2) return true; 20 | } 21 | } 22 | return false; 23 | } 24 | 25 | public static void main(String[] args) { 26 | long n = Long.parseLong(args[0]); 27 | StdOut.println(isRamanujan(n)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Week 8/Huntingtons.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Huntingtons { 8 | public static int maxRepeats(String dna) { 9 | int num = 0; 10 | int max = 0; 11 | int i = 0; 12 | while (i < dna.length() - 2) { 13 | String codon = dna.substring(i, i + 3); 14 | if (codon.equals("CAG")) { 15 | i += 3; 16 | num++; 17 | if (num > max) max = num; 18 | } 19 | else { 20 | i++; 21 | num = 0; 22 | } 23 | } 24 | return max; 25 | 26 | } 27 | 28 | public static String removeWhitespace(String s) { 29 | String s2 = s.replace("\n", ""); 30 | String s3 = s2.replace("\t", ""); 31 | String s4 = s3.replace(" ", ""); 32 | return s4; 33 | } 34 | 35 | public static String diagnose(int maxRepeats) { 36 | if (maxRepeats < 10 || maxRepeats > 180) return "not human"; 37 | else if (maxRepeats < 36) return "normal"; 38 | else if (maxRepeats < 40) return "high risk"; 39 | else return "Huntington's"; 40 | } 41 | 42 | public static void main(String[] args) { 43 | String name = args[0]; 44 | In in = new In(name); 45 | String s = in.readAll(); 46 | String dna = removeWhitespace(s); 47 | int repeats = maxRepeats(dna); 48 | StdOut.println("max repeats = " + repeats); 49 | StdOut.println(diagnose(repeats)); 50 | 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Week 8/KernelFilter.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | import java.awt.Color; 8 | 9 | public class KernelFilter { 10 | private static Picture kernel(Picture picture, double[][] weights) { 11 | int w = picture.width(); 12 | int h = picture.height(); 13 | Picture target = new Picture(w, h); 14 | double rnew = 0.0; 15 | double gnew = 0.0; 16 | double bnew = 0.0; 17 | for (int col = 0; col < w; col++) { 18 | for (int row = 0; row < h; row++) { 19 | for (int i = -1; i < 2; i++) { 20 | for (int j = -1; j < 2; j++) { 21 | Color color = picture.get((w + col + i) % w, (h + row + j) % h); 22 | int r = color.getRed(); 23 | int g = color.getGreen(); 24 | int b = color.getBlue(); 25 | rnew += r * weights[i + 1][j + 1]; 26 | gnew += g * weights[i + 1][j + 1]; 27 | bnew += b * weights[i + 1][j + 1]; 28 | } 29 | } 30 | int R = (int) Math.round(rnew); 31 | int G = (int) Math.round(gnew); 32 | int B = (int) Math.round(bnew); 33 | if (R > 255) R = 255; 34 | if (G > 255) G = 255; 35 | if (B > 255) B = 255; 36 | if (R < 0) R = 0; 37 | if (G < 0) G = 0; 38 | if (B < 0) B = 0; 39 | Color newcolor = new Color(R, G, B); 40 | target.set(col, row, newcolor); 41 | rnew = 0.0; 42 | gnew = 0.0; 43 | bnew = 0.0; 44 | } 45 | } 46 | return target; 47 | } 48 | 49 | public static Picture identity(Picture picture) { 50 | return picture; 51 | } 52 | 53 | public static Picture gaussian(Picture picture) { 54 | double[][] filter = new double[3][3]; 55 | filter[0][0] = 1.0 / 16.0; 56 | filter[1][0] = 2.0 / 16.0; 57 | filter[2][0] = 1.0 / 16.0; 58 | filter[0][1] = 2.0 / 16.0; 59 | filter[1][1] = 4.0 / 16.0; 60 | filter[2][1] = 2.0 / 16.0; 61 | filter[0][2] = 1.0 / 16.0; 62 | filter[1][2] = 2.0 / 16.0; 63 | filter[2][2] = 1.0 / 16.0; 64 | return kernel(picture, filter); 65 | } 66 | 67 | public static Picture sharpen(Picture picture) { 68 | double[][] filter = new double[3][3]; 69 | filter[0][0] = 0; 70 | filter[1][0] = -1; 71 | filter[2][0] = 0; 72 | filter[0][1] = -1; 73 | filter[1][1] = 5; 74 | filter[2][1] = -1; 75 | filter[0][2] = 0; 76 | filter[1][2] = -1; 77 | filter[2][2] = 0; 78 | return kernel(picture, filter); 79 | } 80 | 81 | public static Picture laplacian(Picture picture) { 82 | double[][] filter = new double[3][3]; 83 | filter[0][0] = -1; 84 | filter[1][0] = -1; 85 | filter[2][0] = -1; 86 | filter[0][1] = -1; 87 | filter[1][1] = 8; 88 | filter[2][1] = -1; 89 | filter[0][2] = -1; 90 | filter[1][2] = -1; 91 | filter[2][2] = -1; 92 | return kernel(picture, filter); 93 | } 94 | 95 | public static Picture emboss(Picture picture) { 96 | double[][] filter = new double[3][3]; 97 | filter[0][0] = -2; 98 | filter[1][0] = -1; 99 | filter[2][0] = 0; 100 | filter[0][1] = -1; 101 | filter[1][1] = 1; 102 | filter[2][1] = 1; 103 | filter[0][2] = 0; 104 | filter[1][2] = 1; 105 | filter[2][2] = 2; 106 | return kernel(picture, filter); 107 | } 108 | 109 | public static Picture motionBlur(Picture picture) { 110 | double[][] weights = new double[9][9]; 111 | for (int i = 0; i < 9; i++) { 112 | weights[i][i] = 1.0 / 9.0; 113 | } 114 | int w = picture.width(); 115 | int h = picture.height(); 116 | Picture target = new Picture(w, h); 117 | double rnew = 0.0; 118 | double gnew = 0.0; 119 | double bnew = 0.0; 120 | for (int col = 0; col < w; col++) { 121 | for (int row = 0; row < h; row++) { 122 | for (int i = -4; i < 5; i++) { 123 | for (int j = -4; j < 5; j++) { 124 | Color color = picture.get((w + col + i) % w, (h + row + j) % h); 125 | int r = color.getRed(); 126 | int g = color.getGreen(); 127 | int b = color.getBlue(); 128 | rnew += r * weights[i + 4][j + 4]; 129 | gnew += g * weights[i + 4][j + 4]; 130 | bnew += b * weights[i + 4][j + 4]; 131 | } 132 | } 133 | int R = (int) Math.round(rnew); 134 | int G = (int) Math.round(gnew); 135 | int B = (int) Math.round(bnew); 136 | if (R > 255) R = 255; 137 | if (G > 255) G = 255; 138 | if (B > 255) B = 255; 139 | if (R < 0) R = 0; 140 | if (G < 0) G = 0; 141 | if (B < 0) B = 0; 142 | Color newcolor = new Color(R, G, B); 143 | target.set(col, row, newcolor); 144 | rnew = 0.0; 145 | gnew = 0.0; 146 | bnew = 0.0; 147 | } 148 | } 149 | return target; 150 | } 151 | 152 | public static void main(String[] args) { 153 | Picture pic = new Picture(args[0]); 154 | Picture id = identity(pic); 155 | id.show(); 156 | 157 | Picture gaussian = gaussian(pic); 158 | gaussian.show(); 159 | 160 | Picture sharpen = sharpen(pic); 161 | sharpen.show(); 162 | 163 | Picture laplacian = laplacian(pic); 164 | laplacian.show(); 165 | 166 | Picture emboss = emboss(pic); 167 | emboss.show(); 168 | 169 | Picture motionBlur = motionBlur(pic); 170 | motionBlur.show(); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /Week 8/Quiz 8 - Abstract Data Types.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 8/Quiz 8 - Abstract Data Types.png -------------------------------------------------------------------------------- /Week 9/Clock.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class Clock { 8 | private static final int MINUTES_PER_HOUR = 60; 9 | private static final int HOURS_PER_DAY = 24; 10 | private int hour, min; 11 | 12 | // Creates a clock whose initial time is h hours and m minutes. 13 | public Clock(int h, int m) { 14 | hour = h; 15 | min = m; 16 | if (hour < 0 || hour >= HOURS_PER_DAY || min < 0 || min >= MINUTES_PER_HOUR) 17 | throw new IllegalArgumentException(); 18 | } 19 | 20 | // Creates a clock whose initial time is specified as a string, using the format HH:MM. 21 | public Clock(String s) { 22 | if (!s.contains(":")) throw new IllegalArgumentException(); 23 | int i = s.indexOf(':'); 24 | String shour = s.substring(0, i); 25 | String smin = s.substring(i + 1); 26 | if (shour.length() != 2 || smin.length() != 2) throw new IllegalArgumentException(); 27 | hour = Integer.parseInt(shour); 28 | min = Integer.parseInt(smin); 29 | if (hour < 0 || hour >= HOURS_PER_DAY || min < 0 || min >= MINUTES_PER_HOUR) 30 | throw new IllegalArgumentException(); 31 | } 32 | 33 | // Returns a string representation of this clock, using the format HH:MM. 34 | public String toString() { 35 | String shour = Integer.toString(hour); 36 | String smin = Integer.toString(min); 37 | if (shour.length() == 1) shour = "0" + shour; 38 | if (smin.length() == 1) smin = "0" + smin; 39 | return shour + ":" + smin; 40 | } 41 | 42 | // Is the time on this clock earlier than the time on that one? 43 | public boolean isEarlierThan(Clock that) { 44 | return (hour < that.hour) || (hour == that.hour && min < that.min); 45 | } 46 | 47 | // Adds 1 minute to the time on this clock. 48 | public void tic() { 49 | if (min != MINUTES_PER_HOUR - 1) min++; 50 | else if (hour == HOURS_PER_DAY - 1) { 51 | hour = 0; 52 | min = 0; 53 | } 54 | else { 55 | hour++; 56 | min = 0; 57 | } 58 | } 59 | 60 | // Adds Δ minutes to the time on this clock. 61 | public void toc(int delta) { 62 | if (delta < 0) throw new IllegalArgumentException(); 63 | int minRepresentation = hour * MINUTES_PER_HOUR + min; 64 | minRepresentation += delta; 65 | int newHour = minRepresentation / MINUTES_PER_HOUR; 66 | int newMin = minRepresentation - MINUTES_PER_HOUR * newHour; 67 | hour = newHour % HOURS_PER_DAY; 68 | min = newMin % MINUTES_PER_HOUR; 69 | } 70 | 71 | public static void main(String[] args) { 72 | Clock userTime = new Clock(23, 55); 73 | Clock otherTime = new Clock("08:45"); 74 | StdOut.println(userTime.toString()); 75 | userTime.tic(); 76 | StdOut.println(userTime.toString()); 77 | userTime.toc(15); 78 | StdOut.println(userTime.toString()); 79 | StdOut.println(userTime.isEarlierThan(otherTime)); 80 | StdOut.println(otherTime.toString()); 81 | otherTime.toc(1441); 82 | StdOut.println(otherTime.toString()); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Week 9/ColorHSB.java: -------------------------------------------------------------------------------- 1 | /* ***************************************************************************** 2 | * Name: Ada Lovelace 3 | * Coursera User ID: 123456 4 | * Last modified: October 16, 1842 5 | **************************************************************************** */ 6 | 7 | public class ColorHSB { 8 | private static final int ANGLE = 360; 9 | private final int hue, sat, bright; 10 | 11 | public ColorHSB(int h, int s, int b) { 12 | hue = h; 13 | sat = s; 14 | bright = b; 15 | if (hue < 0 || hue >= ANGLE) 16 | throw new IllegalArgumentException("the hue must be between 0 and 359"); 17 | if (sat < 0 || sat > 100) 18 | throw new IllegalArgumentException("the saturation must be between 0 and 100"); 19 | if (bright < 0 || bright > 100) 20 | throw new IllegalArgumentException("the brightness must be between 0 and 100"); 21 | 22 | } 23 | 24 | // Returns a string representation of this color, using the format (h, s, b). 25 | public String toString() { 26 | return "(" + hue + ", " + sat + ", " + bright + ")"; 27 | } 28 | 29 | // Is this color a shade of gray? 30 | public boolean isGrayscale() { 31 | return (sat == 0 || bright == 0); 32 | } 33 | 34 | // Returns the squared distance between the two colors. 35 | public int distanceSquaredTo(ColorHSB that) { 36 | if (that == null) throw new IllegalArgumentException("please input a color"); 37 | int h1 = that.hue; 38 | int s1 = that.sat; 39 | int b1 = that.bright; 40 | return Math.min((h1 - hue) * (h1 - hue), 41 | (ANGLE - Math.abs(h1 - hue)) * (ANGLE - Math.abs(h1 - hue))) 42 | + (s1 - sat) * (s1 43 | - sat) + (b1 - bright) * (b1 - bright); 44 | } 45 | 46 | public static void main(String[] args) { 47 | int h = Integer.parseInt(args[0]); 48 | int s = Integer.parseInt(args[1]); 49 | int b = Integer.parseInt(args[2]); 50 | ColorHSB color = new ColorHSB(h, s, b); 51 | ColorHSB bestColor = color; 52 | int minDist = ANGLE * ANGLE * ANGLE; 53 | String cbest = ""; 54 | while (!StdIn.isEmpty()) { 55 | String name = StdIn.readString(); 56 | int h2 = StdIn.readInt(); 57 | int s2 = StdIn.readInt(); 58 | int b2 = StdIn.readInt(); 59 | ColorHSB color2 = new ColorHSB(h2, s2, b2); 60 | if (color.distanceSquaredTo(color2) < minDist) { 61 | minDist = color.distanceSquaredTo(color2); 62 | bestColor = color2; 63 | cbest = name; 64 | } 65 | } 66 | StdOut.println(cbest + " " + bestColor.toString()); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Week 9/Quiz 9 - Creating Data Types.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liuhh02/Computer-Science-Programming-with-a-Purpose/0b8d40a8c553414917e4d721ea728e423b3fe442/Week 9/Quiz 9 - Creating Data Types.png --------------------------------------------------------------------------------