├── .gitignore ├── README.md ├── hw ├── hw1 │ ├── Nuke2.java │ ├── OpenCommercial.java │ └── readme.txt ├── hw2 │ ├── Date.java │ └── readme.txt ├── hw3 │ ├── Homework3.java │ ├── SList.java │ ├── SListNode.java │ ├── TestHelper.java │ └── readme.txt ├── hw4 │ ├── GRADER │ ├── list │ │ ├── DList.java │ │ ├── DListNode.java │ │ ├── LockDList.java │ │ └── LockDListNode.java │ └── readme.txt ├── hw5 │ ├── Set.java │ ├── list │ │ ├── DList.java │ │ ├── DListNode.java │ │ ├── InvalidNodeException.java │ │ ├── List.java │ │ ├── ListNode.java │ │ ├── SList.java │ │ └── SListNode.java │ └── readme.txt ├── hw6 │ ├── Homework6Test.java │ ├── SimpleBoard.java │ ├── dict │ │ ├── Dictionary.java │ │ ├── Entry.java │ │ └── HashTableChained.java │ ├── list │ │ ├── DList.java │ │ ├── DListNode.java │ │ ├── InvalidNodeException.java │ │ ├── List.java │ │ ├── ListNode.java │ │ ├── SList.java │ │ └── SListNode.java │ └── readme.txt ├── hw7 │ ├── dict │ │ ├── IntDictionary.java │ │ ├── Tree234.java │ │ └── Tree234Node.java │ └── readme.txt ├── hw8 │ ├── GRADER │ ├── ListSorts.java │ ├── Timer.java │ ├── list │ │ ├── LinkedQueue.java │ │ ├── Queue.java │ │ ├── QueueEmptyException.java │ │ └── SListNode.java │ └── readme.txt └── hw9 │ ├── Maze.java │ ├── readme.txt │ └── set │ └── DisjointSets.java ├── lab ├── lab1 │ ├── Names.java │ ├── readme.txt │ └── roster.txt ├── lab10 │ ├── readme.txt │ └── tree │ │ ├── InvalidNodeException.java │ │ ├── SibTree.java │ │ ├── SibTreeNode.java │ │ ├── Tree.java │ │ └── TreeNode.java ├── lab11 │ ├── dict │ │ ├── BinaryTree.java │ │ ├── BinaryTreeNode.java │ │ ├── Dictionary.java │ │ └── Entry.java │ └── readme.txt ├── lab12 │ ├── Sort.java │ ├── SortPerf.java │ ├── Timer.java │ ├── YourSort.java │ ├── best.dat │ ├── insert.dat │ ├── merge.dat │ ├── quick.dat │ ├── readme.txt │ ├── runrace │ └── select.dat ├── lab13 │ ├── UDGraph.java │ ├── list │ │ ├── LinkedQueue.java │ │ ├── Queue.java │ │ ├── QueueEmptyException.java │ │ └── SListNode.java │ └── readme.txt ├── lab2 │ ├── Fraction.java │ └── readme.txt ├── lab3 │ ├── SList.java │ ├── SListNode.java │ ├── TestHelper.java │ └── readme.txt ├── lab4 │ ├── DList1.java │ ├── DList2.java │ ├── DListNode1.java │ ├── DListNode2.java │ ├── readme.txt │ └── things2remember.txt ├── lab5 │ ├── answers.txt │ ├── q1 │ │ ├── X.java │ │ ├── Y.java │ │ └── test.java │ ├── q2 │ │ ├── jInterface.java │ │ ├── jSubclass.java │ │ └── jSuperclass.java │ ├── q3 │ │ ├── jInterface.java │ │ ├── jSubclass.java │ │ └── jSuperclass.java │ ├── q4 │ │ ├── jSubclass.java │ │ └── jSuperclass.java │ └── readme.txt ├── lab6 │ ├── AccountData.java │ ├── BadAccountException.java │ ├── BadTransactionException.java │ ├── BankApp.java │ ├── GRADER │ ├── VirtualTeller.java │ ├── readme.txt │ └── sortedlist │ │ ├── Keyable.java │ │ ├── ListEnum.java │ │ ├── ListNode.java │ │ └── SortedList.java ├── lab7 │ └── readme.txt ├── lab8 │ ├── DebugMe.java │ ├── ListNode.java │ └── readme.txt └── lab9 │ └── readme.txt └── projects └── pj1 ├── DList.java ├── DListNode.java ├── Ocean.java ├── Record.java ├── RunLengthEncoding.java ├── SimText.java ├── Simulation.java ├── Test.class ├── Test1.class ├── Test2.class ├── Test3.class ├── Test4.class ├── Test4.java ├── readme.txt └── things2remember.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | .[a-zA-Z_]* 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | java_cs61b 2 | ========== 3 | 4 | self study java, through cs61b (http://www.cs.berkeley.edu/~jrs/61b/) 5 | -------------------------------------------------------------------------------- /hw/hw1/Nuke2.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class Nuke2 { 4 | public static void main(String[] arg) throws Exception { 5 | BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); 6 | String input = bf.readLine(); 7 | String output = input.substring(0,1)+input.substring(2); 8 | System.out.println(output); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /hw/hw1/OpenCommercial.java: -------------------------------------------------------------------------------- 1 | /* OpenCommercial.java */ 2 | 3 | import java.net.*; 4 | import java.io.*; 5 | 6 | /** A class that provides a main function to read five lines of a commercial 7 | * Web page and print them in reverse order, given the name of a company. 8 | */ 9 | 10 | class OpenCommercial { 11 | 12 | /** Prompts the user for the name X of a company (a single string), opens 13 | * the Web site corresponding to www.X.com, and prints the first five lines 14 | * of the Web page in reverse order. 15 | * @param arg is not used. 16 | * @exception Exception thrown if there are any problems parsing the 17 | * user's input or opening the connection. 18 | */ 19 | public static void main(String[] arg) throws Exception { 20 | 21 | BufferedReader keyboard; 22 | String inputLine; 23 | 24 | keyboard = new BufferedReader(new InputStreamReader(System.in)); 25 | 26 | System.out.print("Please enter the name of a company (without spaces): "); 27 | System.out.flush(); /* Make sure the line is printed immediately. */ 28 | inputLine = keyboard.readLine(); 29 | 30 | /* Replace this comment with your solution. */ 31 | //URL u = new URL("http://www."+inputLine+".com"); 32 | // Try using the full url instead 33 | URL u= new URL(inputLine); 34 | BufferedReader uBf=new BufferedReader(new InputStreamReader(u.openStream())); 35 | 36 | // use a String array to make it print reversely 37 | String urlLines[]; 38 | int size=10; 39 | urlLines=new String[size]; 40 | for(int i=0;i=0;i--) 45 | { 46 | System.out.println(urlLines[i]); 47 | } 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /hw/hw1/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Homework 1 2 | Due 5:30pm Friday, February 1, 2013 3 | 4 | This homework assignment is meant to make sure you can write, compile, and run 5 | simple Java programs. This is an individual assignment; you may not share 6 | code with other students. You will need to know how to compile and run Java 7 | programs, as described in Lab 1. 8 | 9 | Copy the Homework 1 directory by starting from your home directory and typing 10 | the following: 11 | cp -r ~cs61b/hw/hw1 . 12 | cd hw1 13 | 14 | Problem 1 15 | --------- 16 | Write a program that reads a String from the keyboard. The program should then 17 | construct a URL for http://www.X.com/, replacing X with the String read in, and 18 | print the first five lines of the Web page at that URL in REVERSE ORDER; i.e., 19 | the fifth, fourth, third, second, and first lines. 20 | 21 | We've already created a skeleton for you in the file OpenCommercial.java; you 22 | just need to fill it in. Use the println method to print each of the five 23 | lines, so that there's a carriage return at the end of each line. 24 | 25 | To receive credit for this problem, you must follow these directions exactly: 26 | 27 | 1) Your solution must be in a file called OpenCommercial.java . 28 | 2) Do not edit any of the lines before the line that says 29 | "Replace this comment with your solution." 30 | 3) Your program must print only five lines from the given home page, 31 | and must print them in reverse order. Do not add any extraneous 32 | println statements. Do not modify the lines before printing them. 33 | The program skeleton we've given you prints a prompt before reading 34 | the String; don't change this prompt. Your program must produce 35 | EXACTLY the same output as our solution, because we will be using an 36 | automatic grading program dumber than a microwave oven. 37 | 38 | Before you submit your solution, be sure to try compiling your program ON THE 39 | LAB MACHINES with "javac -g OpenCommercial.java", and be sure to try running 40 | your program ON THE LAB MACHINES using "java OpenCommercial". If you are 41 | working from home, be aware that there might be slight differences between your 42 | Java installation and ours, so you should always test your code on the lab 43 | machines just before you submit it. No partial credit will be given for 44 | programs that don't produce a portion of a Web page. 45 | 46 | 47 | Problem 2 48 | --------- 49 | Write a program called "Nuke2.java" containing a class called Nuke2 whose main 50 | method reads a string from the keyboard and prints the same string, with its 51 | second character removed. (That's character number 1, since Java numbers 52 | characters in a string starting from zero.) In other words, after you run 53 | "java Nuke2", if you type in the string "skin", the program will print "sin". 54 | 55 | (Note: your program might crash with an error message if you type in a string 56 | containing fewer than two characters. That's okay; your program only needs to 57 | work correctly on strings at least two characters long.) 58 | 59 | To receive credit for this problem, you must follow these directions exactly: 60 | 61 | 1) Your solution must be in a file called Nuke2.java, and the main 62 | program must be in a class called Nuke2. 63 | 2) Your program must read just one string, then print the same string 64 | with the second character omitted, then exit. Do not print anything 65 | else. In particular, DO NOT PRINT A PROMPT. 66 | 67 | Again, be certain that your program compiles and runs correctly on the lab 68 | machines before you submit it! The automatic grader is not charitable. 69 | Did I mention that you should NOT PRINT A PROMPT? 70 | 71 | Submitting your solution 72 | ------------------------ 73 | Warning: the submit command probably won't work until Thursday, and might not 74 | work up to 24 hours after you login to a lab machine for the first time. 75 | 76 | Warning: make sure your code _compiles_ and _runs_ on the _lab_machines_ right 77 | before you submit it. Every semester, we get dozens of submissions that don't 78 | even compile. Don't make "a tiny last-minute change" and assume your code 79 | still compiles. Don't assume because the code works on your PC that it will 80 | work in the lab. You will not receive sympathy for code that "almost" works. 81 | 82 | Change (cd) to your hw1 directory, which should contain OpenCommercial.java and 83 | Nuke2.java. Type "submit hw1". 84 | 85 | If you only manage to do one of the problems before the deadline, you'll have 86 | to create an empty file with the name of the other program so that "submit hw1" 87 | will work. 88 | 89 | After submitting, if you realize one of your programs is flawed, you may fix 90 | it and submit again. You will have to resubmit both files, even if you only 91 | change one. You may submit as often as you like. Only the last version you 92 | submit before the deadline will be graded. 93 | 94 | This will be the standard procedure for submitting future homeworks and 95 | projects as well. 96 | -------------------------------------------------------------------------------- /hw/hw3/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | /** 4 | * SListNode is a class used internally by the SList class. An SList object 5 | * is a singly-linked list, and an SListNode is a node of a singly-linked 6 | * list. Each SListNode has two references: one to an object, and one to 7 | * the next node in the list. 8 | * 9 | * @author Kathy Yelick and Jonathan Shewchuk 10 | */ 11 | 12 | class SListNode { 13 | Object item; 14 | SListNode next; 15 | 16 | 17 | /** 18 | * SListNode() (with two parameters) constructs a list node referencing the 19 | * item "obj", whose next list node is to be "next". 20 | */ 21 | 22 | SListNode(Object obj, SListNode next) { 23 | item = obj; 24 | this.next = next; 25 | } 26 | 27 | /** 28 | * SListNode() (with one parameter) constructs a list node referencing the 29 | * item "obj". 30 | */ 31 | 32 | SListNode(Object obj) { 33 | this(obj, null); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /hw/hw3/TestHelper.java: -------------------------------------------------------------------------------- 1 | /* TestHelper.java */ 2 | 3 | /** 4 | * The purpose of this class is to provide a shorthand for writing and testing 5 | * invariants in any program. 6 | **/ 7 | 8 | public class TestHelper { 9 | 10 | /** 11 | * verify() checks an invariant and prints an error message if it fails. 12 | * If invariant is true, this method does nothing. If invariant is false, 13 | * the message is printed, followed by a dump of the program stack. 14 | * 15 | * @param invariant the condition to be verified 16 | * @param message the error message to be printed if the invariant fails to 17 | * hold true. 18 | **/ 19 | 20 | static void verify(boolean invariant, String message) { 21 | if (!invariant) { 22 | System.out.println("*** ERROR: " + message); 23 | Thread.dumpStack(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /hw/hw3/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Homework 3 2 | Due 5:30pm Friday, February 15, 2013 3 | 4 | This homework assignment is designed to give you practice working with arrays, 5 | linked lists, and nested loops. It will also give you practice for the similar 6 | but harder run-length encoding computations in Project 1. This is an 7 | individual assignment; you may not share code with other students. 8 | 9 | Copy the Homework 3 directory by doing the following, starting from your home 10 | directory: 11 | 12 | cp -r ~cs61b/hw/hw3 . 13 | cd hw3 14 | 15 | Your task is to write two methods for removing successive duplicate items from 16 | lists, and one method for adding them. The smoosh() method operates on lists 17 | represented as arrays, and the squish() method and twin() method operate on 18 | singly-linked lists. 19 | 20 | The Homework3 class includes test code for all three methods, as well as a 21 | skeleton for the smoosh() method. The SList class from Lab 3 is also present, 22 | and here includes skeletons for the squish() method and the twin() method. 23 | 24 | You can test all three methods by compiling and running Homework3.java. As 25 | usual, you are welcome to add test cases to the main() method or change main() 26 | as you please; we will not test main(). However, you cannot change the 27 | interface of the public methods and classes, because our autograder will use 28 | them. So you might want to keep the main() test code around--if you 29 | accidentally change a prototype, the test code will catch it. 30 | 31 | You may NOT use Java's built-in data structure libraries, like java.util.Vector 32 | or java.util.LinkedList, in this homework (or any future homework, except where 33 | otherwise specified). All data structure implementations should be your own or 34 | those taken from lectures/labs/homeworks. 35 | 36 | Part I (5 points) 37 | ------------------ 38 | Fill in the smoosh() method in the Homework3 class so that it performs as 39 | indicated in the comment. Your solution should not use linked lists, nor 40 | should it use your squish() method. 41 | 42 | /** 43 | * smoosh() takes an array of ints. On completion the array contains 44 | * the same numbers, but wherever the array had two or more consecutive 45 | * duplicate numbers, they are replaced by one copy of the number. Hence, 46 | * after smoosh() is done, no two consecutive numbers in the array are the 47 | * same. 48 | * 49 | * Any unused elements at the end of the array are set to -1. 50 | * 51 | * For example, if the input array is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], 52 | * it reads [ 0 1 0 3 1 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 ] after smoosh() 53 | * completes. 54 | * 55 | * @param ints the input array. 56 | **/ 57 | 58 | private static void smoosh(int[] ints) { 59 | // Fill in your solution here. (Ours is fourteen lines long, not counting 60 | // blank lines or lines already present in this file.) 61 | } 62 | 63 | Part II (3 points) 64 | ------------------- 65 | Fill in the squish() method in the SList class so that it performs as indicated 66 | in the comment. Your solution should not use arrays, nor should it use your 67 | smoosh() method. Do not change the prototype of the SList constructor or the 68 | insertEnd method; our test software will call them. 69 | 70 | /** 71 | * squish() takes this list and, wherever two or more consecutive items are 72 | * equals(), it removes duplicate nodes so that only one consecutive copy 73 | * remains. Hence, no two consecutive items in this list are equals() upon 74 | * completion of the procedure. 75 | * 76 | * After squish() executes, the list may well be shorter than when squish() 77 | * began. No extra items are added to make up for those removed. 78 | * 79 | * For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the 80 | * output list is [ 0 1 0 3 1 0 ]. 81 | * 82 | * IMPORTANT: Be sure you use the equals() method, and not the "==" 83 | * operator, to compare items. 84 | **/ 85 | 86 | public void squish() { 87 | // Fill in your solution here. (Ours is eleven lines long.) 88 | } 89 | 90 | Part III (2 points) 91 | -------------------- 92 | Fill in the twin() method in the SList class so that it performs as indicated 93 | in the comment. Your solution should not use arrays. 94 | 95 | /** 96 | * twin() takes this list and doubles its length by replacing each node 97 | * with two consecutive nodes referencing the same item. 98 | * 99 | * For example, if the input list is [ 3 7 4 2 2 ], the 100 | * output list is [ 3 3 7 7 4 4 2 2 2 2 ]. 101 | * 102 | * IMPORTANT: Do not try to make new copies of the items themselves. 103 | * Make new SListNodes, but just copy the references to the items. 104 | **/ 105 | 106 | public void twin() { 107 | // Fill in your solution here. (Ours is seven lines long.) 108 | } 109 | 110 | Submitting your solution 111 | ------------------------ 112 | Change (cd) to your hw3 directory, which should contain Homework3.java, 113 | SList.java, SListNode.java, TestHelper.java, and any other files needed to run 114 | your methods. Make sure your homework compiles and runs on the _lab_ machines 115 | just before you submit. 116 | 117 | From your hw3 directory, type "submit hw3". After submitting, if you realize 118 | your solution is flawed, you may fix it and submit again. You may submit as 119 | often as you like. Only the last version you submit before the deadline will 120 | be graded. 121 | -------------------------------------------------------------------------------- /hw/hw4/GRADER: -------------------------------------------------------------------------------- 1 | It would be tring to create a DListNode not even in the DList and call 2 | insertAfter(), insertBefore(), prev(), next(), remove(); 3 | This will corrupt the size field; 4 | Also the whole list 5 | ============================================================ 6 | How to resolve? 7 | From this website 8 | (http://gotfu.wordpress.com/2012/01/23/berkeley-cs61b-homework-4/) 9 | One way would be add an extra field in DListNode to record which list this node 10 | belongs to; 11 | -------------------------------------------------------------------------------- /hw/hw4/list/DListNode.java: -------------------------------------------------------------------------------- 1 | /* DListNode.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * A DListNode is a node in a DList (doubly-linked list). 7 | */ 8 | 9 | public class DListNode { 10 | 11 | /** 12 | * item references the item stored in the current node. 13 | * prev references the previous node in the DList. 14 | * next references the next node in the DList. 15 | * 16 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 17 | */ 18 | 19 | public Object item; 20 | protected DListNode prev; 21 | protected DListNode next; 22 | 23 | /** 24 | * DListNode() constructor. 25 | * @param i the item to store in the node. 26 | * @param p the node previous to this node. 27 | * @param n the node following this node. 28 | */ 29 | DListNode(Object i, DListNode p, DListNode n) { 30 | item = i; 31 | prev = p; 32 | next = n; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /hw/hw4/list/LockDList.java: -------------------------------------------------------------------------------- 1 | package list; 2 | 3 | public class LockDList extends DList { 4 | 5 | /** 6 | * Overide newNode function 7 | */ 8 | protected DListNode newNode(Object item, DListNode prev, DListNode next) { 9 | return new LockDListNode(item, prev, next); 10 | } 11 | 12 | public void lockNode(DListNode node) { 13 | if(node instanceof LockDListNode) { 14 | ((LockDListNode)node).locked = true; 15 | } 16 | } 17 | 18 | /** 19 | * Overide remove function 20 | */ 21 | public void remove(DListNode node) { 22 | if((node!=null)&&(node instanceof LockDListNode) && !((LockDListNode)node).locked) { 23 | super.remove(node); 24 | } 25 | } 26 | public static void main(String[] argv) { 27 | System.out.println("testing"); 28 | LockDList lst = new LockDList(); 29 | System.out.println("length :"+lst.length()); 30 | System.out.println("is empty? "+lst.isEmpty()); 31 | System.out.println("Testing empty: " + lst); 32 | lst.insertFront(3); 33 | System.out.println("Testing insert front"+lst); 34 | lst.insertBack(55.55); 35 | System.out.println("Testing insert back"+ lst); 36 | lst.insertFront(1000); 37 | System.out.println("Testing insert front with 1000"+lst); 38 | System.out.println("Testing front "+lst.front().item); 39 | System.out.println("Testing back() "+lst.back().item); 40 | // get node with 3 41 | System.out.println("Testing next(), should be 3: "+lst.next(lst.head.next).item); 42 | DListNode midNode=lst.next(lst.head.next); 43 | // test insertAfter and insertBefore 44 | lst.insertBefore("hello",midNode); 45 | System.out.println("Testing insertBefore(): "+lst); 46 | lst.insertAfter("what-ever",midNode); 47 | System.out.println("Testing insertAfter(): "+lst); 48 | // print length 49 | System.out.println("Length :"+lst.length()); 50 | System.out.println("is empty?"+lst.isEmpty()); 51 | 52 | // try remove head 53 | System.out.println("Trying to remove head"); 54 | lst.remove(lst.prev(lst.front())); 55 | System.out.println(lst); 56 | 57 | // testing prev 58 | System.out.println("Testing prev(), should be hello:"+lst.prev(midNode).item); 59 | // testing lock 60 | lst.lockNode(lst.back()); 61 | // testing remove 62 | for(int i=0; i<6;i++) { 63 | lst.remove(lst.head.next); 64 | System.out.println(lst+ "length is "+lst.length()); 65 | } 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /hw/hw4/list/LockDListNode.java: -------------------------------------------------------------------------------- 1 | // By Ryan (Weiran) Zhao 2 | // Sat,Jun 15th 2013 02:24:04 PM EDT 3 | package list; 4 | 5 | public class LockDListNode extends DListNode { 6 | protected boolean locked; 7 | public LockDListNode(Object i, DListNode p, DListNode n) { 8 | super(i,p,n); 9 | locked=false; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /hw/hw5/list/DListNode.java: -------------------------------------------------------------------------------- 1 | /* DListNode.java */ 2 | // Modified by Ryan (Weiran) Zhao 3 | // Tue,Jun 18th 2013 02:04:28 PM EDT 4 | 5 | package list; 6 | 7 | /** 8 | * A DListNode is a mutable node in a DList (doubly-linked list). 9 | **/ 10 | 11 | public class DListNode extends ListNode { 12 | 13 | /** 14 | * (inherited) item references the item stored in the current node. 15 | * (inherited) myList references the List that contains this node. 16 | * prev references the previous node in the DList. 17 | * next references the next node in the DList. 18 | * 19 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 20 | **/ 21 | 22 | protected DListNode prev; 23 | protected DListNode next; 24 | 25 | /** 26 | * DListNode() constructor. 27 | * @param i the item to store in the node. 28 | * @param l the list this node is in. 29 | * @param p the node previous to this node. 30 | * @param n the node following this node. 31 | */ 32 | DListNode(Object i, DList l, DListNode p, DListNode n) { 33 | item = i; 34 | myList = l; 35 | prev = p; 36 | next = n; 37 | } 38 | 39 | /** 40 | * isValidNode returns true if this node is valid; false otherwise. 41 | * An invalid node is represented by a `myList' field with the value null. 42 | * Sentinel nodes are invalid, and nodes that don't belong to a list are 43 | * also invalid. 44 | * 45 | * @return true if this node is valid; false otherwise. 46 | * 47 | * Performance: runs in O(1) time. 48 | */ 49 | public boolean isValidNode() { 50 | return myList != null; 51 | } 52 | 53 | /** 54 | * next() returns the node following this node. If this node is invalid, 55 | * throws an exception. 56 | * 57 | * @return the node following this node. 58 | * @exception InvalidNodeException if this node is not valid. 59 | * 60 | * Performance: runs in O(1) time. 61 | */ 62 | public ListNode next() throws InvalidNodeException { 63 | if (!isValidNode()) { 64 | throw new InvalidNodeException("next() called on invalid node"); 65 | } 66 | return next; 67 | } 68 | 69 | /** 70 | * prev() returns the node preceding this node. If this node is invalid, 71 | * throws an exception. 72 | * 73 | * @param node the node whose predecessor is sought. 74 | * @return the node preceding this node. 75 | * @exception InvalidNodeException if this node is not valid. 76 | * 77 | * Performance: runs in O(1) time. 78 | */ 79 | public ListNode prev() throws InvalidNodeException { 80 | if (!isValidNode()) { 81 | throw new InvalidNodeException("prev() called on invalid node"); 82 | } 83 | return prev; 84 | } 85 | 86 | /** 87 | * insertAfter() inserts an item immediately following this node. If this 88 | * node is invalid, throws an exception. 89 | * 90 | * @param item the item to be inserted. 91 | * @exception InvalidNodeException if this node is not valid. 92 | * 93 | * Performance: runs in O(1) time. 94 | */ 95 | public void insertAfter(Object item) throws InvalidNodeException { 96 | if (!isValidNode()) { 97 | throw new InvalidNodeException("insertAfter() called on invalid node"); 98 | } 99 | // Your solution here. Will look something like your Homework 4 solution, 100 | // but changes are necessary. For instance, there is no need to check if 101 | // "this" is null. Remember that this node's "myList" field tells you 102 | // what DList it's in. You should use myList.newNode() to create the 103 | // new node. 104 | else { 105 | DListNode tmp = ((DList) myList).newNode(item, (DList) myList, this, this.next); 106 | this.next.prev=tmp; 107 | this.next=tmp; 108 | this.myList.size+=1; 109 | } 110 | } 111 | 112 | /** 113 | * insertBefore() inserts an item immediately preceding this node. If this 114 | * node is invalid, throws an exception. 115 | * 116 | * @param item the item to be inserted. 117 | * @exception InvalidNodeException if this node is not valid. 118 | * 119 | * Performance: runs in O(1) time. 120 | */ 121 | public void insertBefore(Object item) throws InvalidNodeException { 122 | if (!isValidNode()) { 123 | throw new InvalidNodeException("insertBefore() called on invalid node"); 124 | } 125 | // Your solution here. Will look something like your Homework 4 solution, 126 | // but changes are necessary. For instance, there is no need to check if 127 | // "this" is null. Remember that this node's "myList" field tells you 128 | // what DList it's in. You should use myList.newNode() to create the 129 | // new node. 130 | else { 131 | DListNode tmp = ((DList)myList).newNode(item, (DList)myList,this.prev,this); 132 | this.prev.next=tmp; 133 | this.prev=tmp; 134 | this.myList.size+=1; 135 | } 136 | } 137 | 138 | /** 139 | * remove() removes this node from its DList. If this node is invalid, 140 | * throws an exception. 141 | * 142 | * @exception InvalidNodeException if this node is not valid. 143 | * 144 | * Performance: runs in O(1) time. 145 | */ 146 | public void remove() throws InvalidNodeException { 147 | if (!isValidNode()) { 148 | throw new InvalidNodeException("remove() called on invalid node"); 149 | } 150 | // Your solution here. Will look something like your Homework 4 solution, 151 | // but changes are necessary. For instance, there is no need to check if 152 | // "this" is null. Remember that this node's "myList" field tells you 153 | // what DList it's in. 154 | else { 155 | this.prev.next=this.next; 156 | this.next.prev=this.prev; 157 | this.myList.size-=1; 158 | 159 | // Make this node an invalid node, so it cannot be used to corrupt myList. 160 | myList = null; 161 | // Set other references to null to improve garbage collection. 162 | next = null; 163 | prev = null; 164 | } 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /hw/hw5/list/InvalidNodeException.java: -------------------------------------------------------------------------------- 1 | /* InvalidNodeException.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * Implements an Exception that signals an attempt to use an invalid ListNode. 7 | */ 8 | 9 | public class InvalidNodeException extends Exception { 10 | protected InvalidNodeException() { 11 | super(); 12 | } 13 | 14 | protected InvalidNodeException(String s) { 15 | super(s); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /hw/hw5/list/List.java: -------------------------------------------------------------------------------- 1 | /* List.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * A List is a mutable list ADT. No implementation is provided. 7 | * 8 | * DO NOT CHANGE THIS FILE. 9 | **/ 10 | 11 | public abstract class List { 12 | 13 | /** 14 | * size is the number of items in the list. 15 | **/ 16 | 17 | protected int size; 18 | 19 | /** 20 | * isEmpty() returns true if this List is empty, false otherwise. 21 | * 22 | * @return true if this List is empty, false otherwise. 23 | * 24 | * Performance: runs in O(1) time. 25 | **/ 26 | public boolean isEmpty() { 27 | return size == 0; 28 | } 29 | 30 | /** 31 | * length() returns the length of this List. 32 | * 33 | * @return the length of this List. 34 | * 35 | * Performance: runs in O(1) time. 36 | **/ 37 | public int length() { 38 | return size; 39 | } 40 | 41 | /** 42 | * insertFront() inserts an item at the front of this List. 43 | * 44 | * @param item is the item to be inserted. 45 | **/ 46 | public abstract void insertFront(Object item); 47 | 48 | /** 49 | * insertBack() inserts an item at the back of this List. 50 | * 51 | * @param item is the item to be inserted. 52 | **/ 53 | public abstract void insertBack(Object item); 54 | 55 | /** 56 | * front() returns the node at the front of this List. If the List is 57 | * empty, return an "invalid" node--a node with the property that any 58 | * attempt to use it will cause an exception. 59 | * 60 | * @return a ListNode at the front of this List. 61 | */ 62 | public abstract ListNode front(); 63 | 64 | /** 65 | * back() returns the node at the back of this List. If the List is 66 | * empty, return an "invalid" node--a node with the property that any 67 | * attempt to use it will cause an exception. 68 | * 69 | * @return a ListNode at the back of this List. 70 | */ 71 | public abstract ListNode back(); 72 | 73 | /** 74 | * toString() returns a String representation of this List. 75 | * 76 | * @return a String representation of this List. 77 | */ 78 | public abstract String toString(); 79 | 80 | } 81 | -------------------------------------------------------------------------------- /hw/hw5/list/ListNode.java: -------------------------------------------------------------------------------- 1 | /* ListNode.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * A ListNode is a mutable node in a list. No implementation is provided. 7 | * 8 | * DO NOT CHANGE THIS FILE. 9 | **/ 10 | 11 | public abstract class ListNode { 12 | 13 | /** 14 | * item references the item stored in the current node. 15 | * myList references the List that contains this node. 16 | * 17 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 18 | */ 19 | 20 | protected Object item; 21 | protected List myList; 22 | 23 | /** 24 | * isValidNode returns true if this node is valid; false otherwise. 25 | * By default, an invalid node is one that doesn't belong to a list (myList 26 | * is null), but subclasses can override this definition. 27 | * 28 | * @return true if this node is valid; false otherwise. 29 | * 30 | * Performance: runs in O(1) time. 31 | */ 32 | public boolean isValidNode() { 33 | return myList != null; 34 | } 35 | 36 | /** 37 | * item() returns this node's item. If this node is invalid, 38 | * throws an exception. 39 | * 40 | * @return the item stored in this node. 41 | * 42 | * Performance: runs in O(1) time. 43 | */ 44 | public Object item() throws InvalidNodeException { 45 | if (!isValidNode()) { 46 | throw new InvalidNodeException(); 47 | } 48 | return item; 49 | } 50 | 51 | /** 52 | * setItem() sets this node's item to "item". If this node is invalid, 53 | * throws an exception. 54 | * 55 | * Performance: runs in O(1) time. 56 | */ 57 | public void setItem(Object item) throws InvalidNodeException { 58 | if (!isValidNode()) { 59 | throw new InvalidNodeException(); 60 | } 61 | this.item = item; 62 | } 63 | 64 | /** 65 | * next() returns the node following this node. If this node is invalid, 66 | * throws an exception. 67 | * 68 | * @return the node following this node. 69 | * @exception InvalidNodeException if this node is not valid. 70 | */ 71 | public abstract ListNode next() throws InvalidNodeException; 72 | 73 | /** 74 | * prev() returns the node preceding this node. If this node is invalid, 75 | * throws an exception. 76 | * 77 | * @param node the node whose predecessor is sought. 78 | * @return the node preceding this node. 79 | * @exception InvalidNodeException if this node is not valid. 80 | */ 81 | public abstract ListNode prev() throws InvalidNodeException; 82 | 83 | /** 84 | * insertAfter() inserts an item immediately following this node. If this 85 | * node is invalid, throws an exception. 86 | * 87 | * @param item the item to be inserted. 88 | * @exception InvalidNodeException if this node is not valid. 89 | */ 90 | public abstract void insertAfter(Object item) throws InvalidNodeException; 91 | 92 | /** 93 | * insertBefore() inserts an item immediately preceding this node. If this 94 | * node is invalid, throws an exception. 95 | * 96 | * @param item the item to be inserted. 97 | * @exception InvalidNodeException if this node is not valid. 98 | */ 99 | public abstract void insertBefore(Object item) throws InvalidNodeException; 100 | 101 | /** 102 | * remove() removes this node from its List. If this node is invalid, 103 | * throws an exception. 104 | * 105 | * @exception InvalidNodeException if this node is not valid. 106 | */ 107 | public abstract void remove() throws InvalidNodeException; 108 | 109 | } 110 | -------------------------------------------------------------------------------- /hw/hw5/list/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * An SListNode is a mutable node in an SList (singly-linked list). 7 | **/ 8 | 9 | public class SListNode extends ListNode { 10 | 11 | /** 12 | * (inherited) item references the item stored in the current node. 13 | * (inherited) myList references the List that contains this node. 14 | * next references the next node in the SList. 15 | * 16 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 17 | **/ 18 | 19 | protected SListNode next; 20 | 21 | /** 22 | * SListNode() constructor. 23 | * @param i the item to store in the node. 24 | * @param l the list this node is in. 25 | * @param n the node following this node. 26 | */ 27 | SListNode(Object i, SList l, SListNode n) { 28 | item = i; 29 | myList = l; 30 | next = n; 31 | } 32 | 33 | /** 34 | * next() returns the node following this node. If this node is invalid, 35 | * throws an exception. 36 | * 37 | * @return the node following this node. 38 | * @exception InvalidNodeException if this node is not valid. 39 | * 40 | * Performance: runs in O(1) time. 41 | */ 42 | public ListNode next() throws InvalidNodeException { 43 | if (!isValidNode()) { 44 | throw new InvalidNodeException("next() called on invalid node"); 45 | } 46 | if (next == null) { 47 | // Create an invalid node. 48 | SListNode node = ((SList) myList).newNode(null, null); 49 | node.myList = null; 50 | return node; 51 | } else { 52 | return next; 53 | } 54 | } 55 | 56 | /** 57 | * prev() returns the node preceding this node. If this node is invalid, 58 | * throws an exception. 59 | * 60 | * @param node the node whose predecessor is sought. 61 | * @return the node preceding this node. 62 | * @exception InvalidNodeException if this node is not valid. 63 | * 64 | * Performance: runs in O(this.size) time. 65 | */ 66 | public ListNode prev() throws InvalidNodeException { 67 | if (!isValidNode()) { 68 | throw new InvalidNodeException("prev() called on invalid node"); 69 | } 70 | SListNode prev = ((SList) myList).head; 71 | if (prev == this) { 72 | // Create an invalid node. 73 | prev = ((SList) myList).newNode(null, null); 74 | prev.myList = null; 75 | } else { 76 | while (prev.next != this) { 77 | prev = prev.next; 78 | } 79 | } 80 | return prev; 81 | } 82 | 83 | /** 84 | * insertAfter() inserts an item immediately following this node. If this 85 | * node is invalid, throws an exception. 86 | * 87 | * @param item the item to be inserted. 88 | * @exception InvalidNodeException if this node is not valid. 89 | * 90 | * Performance: runs in O(1) time. 91 | */ 92 | public void insertAfter(Object item) throws InvalidNodeException { 93 | if (!isValidNode()) { 94 | throw new InvalidNodeException("insertAfter() called on invalid node"); 95 | } 96 | SListNode newNode = ((SList) myList).newNode(item, next); 97 | if (next == null) { 98 | ((SList) myList).tail = newNode; 99 | } 100 | next = newNode; 101 | myList.size++; 102 | } 103 | 104 | /** 105 | * insertBefore() inserts an item immediately preceding this node. If this 106 | * node is invalid, throws an exception. 107 | * 108 | * @param item the item to be inserted. 109 | * @exception InvalidNodeException if this node is not valid. 110 | * 111 | * Performance: runs in O(this.size) time. 112 | */ 113 | public void insertBefore(Object item) throws InvalidNodeException { 114 | if (!isValidNode()) { 115 | throw new InvalidNodeException("insertBefore() called on invalid node"); 116 | } 117 | SListNode newNode = ((SList) myList).newNode(item, this); 118 | if (this == ((SList) myList).head) { 119 | ((SList) myList).head = newNode; 120 | } else { 121 | SListNode prev = (SListNode) prev(); 122 | prev.next = newNode; 123 | } 124 | myList.size++; 125 | } 126 | 127 | /** 128 | * remove() removes this node from its SList. If this node is invalid, 129 | * throws an exception. 130 | * 131 | * @exception InvalidNodeException if this node is not valid. 132 | * 133 | * Performance: runs in O(this.size) time. 134 | */ 135 | public void remove() throws InvalidNodeException { 136 | if (!isValidNode()) { 137 | throw new InvalidNodeException("remove() called on invalid node"); 138 | } 139 | if (this == ((SList) myList).head) { 140 | ((SList) myList).head = next; 141 | if (next == null) { 142 | ((SList) myList).tail = null; 143 | } 144 | } else { 145 | SListNode prev = (SListNode) prev(); 146 | prev.next = next; 147 | if (next == null) { 148 | ((SList) myList).tail = prev; 149 | } 150 | } 151 | myList.size--; 152 | 153 | // Make this node an invalid node, so it cannot be used to corrupt myList. 154 | myList = null; 155 | // Set other reference to null to improve garbage collection. 156 | next = null; 157 | } 158 | 159 | } 160 | -------------------------------------------------------------------------------- /hw/hw6/Homework6Test.java: -------------------------------------------------------------------------------- 1 | /* Homework6Test.java */ 2 | 3 | import dict.*; 4 | 5 | /** 6 | * Initializes a hash table, then stocks it with random SimpleBoards. 7 | **/ 8 | 9 | public class Homework6Test { 10 | 11 | /** 12 | * Generates a random 8 x 8 SimpleBoard. 13 | **/ 14 | 15 | private static SimpleBoard randomBoard() { 16 | SimpleBoard board = new SimpleBoard(); 17 | for (int y = 0; y < 8; y++) { 18 | for (int x = 0; x < 8; x++) { 19 | double fval = Math.random() * 12; 20 | int value = (int) fval; 21 | board.setElementAt(x, y, value); 22 | } 23 | } 24 | return board; 25 | } 26 | 27 | /** 28 | * Empties the given table, then inserts "numBoards" boards into the table. 29 | * @param table is the hash table to be initialized. 30 | * @param numBoards is the number of random boards to place in the table. 31 | **/ 32 | 33 | public static void initTable(HashTableChained table, int numBoards) { 34 | table.makeEmpty(); 35 | for (int i = 0; i < numBoards; i++) { 36 | table.insert(randomBoard(), new Integer(i)); 37 | } 38 | } 39 | 40 | /** 41 | * Creates a hash table and stores a certain number of SimpleBoards in it. 42 | * The number is 100 by default, but you can specify any number at the 43 | * command line. For example: 44 | * 45 | * java Homework6Test 12000 46 | **/ 47 | 48 | public static void main(String[] args) { 49 | int numBoards; 50 | 51 | if (args.length == 0) { 52 | numBoards = 100; 53 | } else { 54 | numBoards = Integer.parseInt(args[0]); 55 | } 56 | HashTableChained table = new HashTableChained(numBoards); 57 | initTable(table, numBoards); 58 | 59 | // To test your hash function, add a method to your HashTableChained class 60 | // that counts the number of collisions--or better yet, also prints 61 | // a histograph of the number of entries in each bucket. Call this method 62 | // from here. 63 | System.out.println("Report collisions: "+table.collisions()+"/"+numBoards); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /hw/hw6/SimpleBoard.java: -------------------------------------------------------------------------------- 1 | /* SimpleBoard.java */ 2 | 3 | /** 4 | * Simple class that implements an 8x8 game board with three possible values 5 | * for each cell: 0, 1 or 2. 6 | * 7 | * DO NOT CHANGE ANY PROTOTYPES IN THIS FILE. 8 | **/ 9 | 10 | public class SimpleBoard { 11 | private final static int DIMENSION = 8; 12 | private int[][] grid; 13 | 14 | /** 15 | * Invariants: 16 | * (1) grid.length == DIMENSION. 17 | * (2) for all 0 <= i < DIMENSION, grid[i].length == DIMENSION. 18 | * (3) for all 0 <= i, j < DIMENSION, grid[i][j] >= 0 and grid[i][j] <= 2. 19 | **/ 20 | 21 | /** 22 | * Construct a new board in which all cells are zero. 23 | */ 24 | 25 | public SimpleBoard() { 26 | grid = new int[DIMENSION][DIMENSION]; 27 | } 28 | 29 | /** 30 | * Set the cell (x, y) in the board to the given value mod 3. 31 | * @param value to which the element should be set (normally 0, 1, or 2). 32 | * @param x is the x-index. 33 | * @param y is the y-index. 34 | * @exception ArrayIndexOutOfBoundsException is thrown if an invalid index 35 | * is given. 36 | **/ 37 | 38 | public void setElementAt(int x, int y, int value) { 39 | grid[x][y] = value % 3; 40 | if (grid[x][y] < 0) { 41 | grid[x][y] = grid[x][y] + 3; 42 | } 43 | } 44 | 45 | /** 46 | * Get the valued stored in cell (x, y). 47 | * @param x is the x-index. 48 | * @param y is the y-index. 49 | * @return the stored value (between 0 and 2). 50 | * @exception ArrayIndexOutOfBoundsException is thrown if an invalid index 51 | * is given. 52 | */ 53 | 54 | public int elementAt(int x, int y) { 55 | return grid[x][y]; 56 | } 57 | 58 | /** 59 | * Returns true if "this" SimpleBoard and "board" have identical values in 60 | * every cell. 61 | * @param board is the second SimpleBoard. 62 | * @return true if the boards are equal, false otherwise. 63 | */ 64 | 65 | public boolean equals(Object board) { 66 | if(board instanceof SimpleBoard) { 67 | for(int i=0; i 1) { 64 | s = s + " "; 65 | } 66 | if (keys > 1) { 67 | s = s + key2; 68 | if (child3 != null) { 69 | s = s + "(" + child3.toString() + ")"; 70 | } else if (keys > 2) { 71 | s = s + " "; 72 | } 73 | } 74 | if (keys > 2) { 75 | s = s + key3; 76 | if (child4 != null) { 77 | s = s + "(" + child4.toString() + ")"; 78 | } 79 | } 80 | return s; 81 | } 82 | 83 | /** 84 | * printSubtree() recursively prints this Tree234Node and its descendants as 85 | * a tree (albeit sideways). 86 | * 87 | * You're welcome to change this method if you like. It won't be tested. 88 | **/ 89 | public void printSubtree(int spaces) { 90 | if (child4 != null) { 91 | child4.printSubtree(spaces + 5); 92 | } 93 | if (keys == 3) { 94 | for (int i = 0; i < spaces; i++) { 95 | System.out.print(" "); 96 | } 97 | System.out.println(key3); 98 | } 99 | 100 | if (child3 != null) { 101 | child3.printSubtree(spaces + 5); 102 | } 103 | if (keys > 1) { 104 | for (int i = 0; i < spaces; i++) { 105 | System.out.print(" "); 106 | } 107 | System.out.println(key2); 108 | } 109 | 110 | if (child2 != null) { 111 | child2.printSubtree(spaces + 5); 112 | } 113 | for (int i = 0; i < spaces; i++) { 114 | System.out.print(" "); 115 | } 116 | System.out.println(key1); 117 | 118 | if (child1 != null) { 119 | child1.printSubtree(spaces + 5); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /hw/hw7/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Homework 7 2 | Due 5:30pm Friday, April 12, 2013 3 | 4 | This homework will give you practice with 2-3-4 trees. This is an individual 5 | assignment; you may not share code with other students. 6 | 7 | Copy the Homework 7 directory by doing the following, starting from your home 8 | directory. 9 | 10 | cp -r ~cs61b/hw/hw7 . 11 | 12 | Your task is to implement the insertion operation of a 2-3-4 tree, in the file 13 | Tree234.java (in the dict package). For simplicity, the tree stores only keys; 14 | no element is associated with each key. Furthermore, the keys are ints. 15 | 16 | The central two operations have the following prototypes. 17 | 18 | public boolean find(int key); 19 | public void insert(int key); 20 | 21 | find() returns true if the specified key is in the tree, and false otherwise. 22 | find() is already implemented for you; inspecting the code will help you 23 | understand the data structure better. insert() inserts its parameter "key" 24 | into the tree. Please implement the top-down insertion algorithm described in 25 | the Lecture 27 notes, and not the bottom-up insertion algorithm described by 26 | Goodrich and Tamassia. 27 | 28 | Because there is no object associated with each key, there is no reason to 29 | store duplicate keys. Hence, if a key is found to already be in the tree, 30 | don't insert another copy. 31 | 32 | A toString() method is also provided for 2-3-4 trees, and is useful for 33 | testing. Do not change it; the autograder will use it to check your trees. 34 | 35 | There's also a printTree() method, which prints a 2-3-4 tree in an easier-to- 36 | read, but more space-consuming, tree-shaped manner (albeit sideways). This 37 | method will not be tested, and you may change it to your liking. 38 | 39 | The Tree234Node class represents a node in a 2-3-4 tree, and has the following 40 | fields. 41 | 42 | int keys; 43 | int key1; 44 | int key2; 45 | int key3; 46 | Tree234Node parent; 47 | Tree234Node child1; 48 | Tree234Node child2; 49 | Tree234Node child3; 50 | Tree234Node child4; 51 | 52 | The "keys" field is the number of keys stored in the node, and must be 1, 2, or 53 | 3. The fields "key1", "key2", and "key3" are filled in (in order) with the int 54 | keys stored in the node. If keys == 1, the value of key2 doesn't matter. If 55 | keys < 3, the value of key3 doesn't matter. 56 | 57 | The "parent" field is the node's parent. The fields "child1" through "child4" 58 | are the node's children, and are filled in in order from child1 to child4. All 59 | four of these references must be set to null in a leaf node. If keys == 1, 60 | child3 should be null, and if keys < 3, the value of child4 should be null. 61 | 62 | You may not change any of these invariants regarding how a Tree234Node is 63 | represented, but you may add fields and helper methods to the Tree234 and 64 | Tree234Node classes if it helps. However, make sure that the toString() 65 | methods and the find() method work correctly in their unmodified forms. 66 | Do not change toString() or find(). 67 | 68 | Test code is provided in the main method of the Tree234 class. To compile, 69 | change (cd) to your hw7 directory and type "javac -g dict/*.java". To run, 70 | type "java dict.Tree234". The test code does not test whether you correctly 71 | update the tree's "size" field; you'll have to test that yourself. 72 | 73 | Submitting your solution 74 | ------------------------ 75 | Change (cd) to your hw7 directory, which should contain the dict directory. 76 | The dict directory should contain Tree234.java and Tree234Node.java. You're 77 | not allowed to change IntDictionary.java, so you can't submit it. Make sure 78 | your homework compiles and runs on the _lab_ machines just before you submit. 79 | 80 | From your hw7 directory, type "submit hw7". (Note that "submit" will not work 81 | if you are inside the dict directory!) After submitting, if you realize your 82 | solution is flawed, you may fix it and submit again. You may submit as often 83 | as you like. Only the last version you submit before the deadline will be 84 | graded. 85 | -------------------------------------------------------------------------------- /hw/hw8/GRADER: -------------------------------------------------------------------------------- 1 | GRADER file for Homework 8 2 | 3 | Your Name: 4 | Your Login: 5 | 6 | Part III. Running time comparisons 7 | 8 | List size mergesort quicksort 9 | 10 0 0 10 | 100 1 1 11 | 1,000 11 3 12 | 10,000 32 21 13 | 100,000 164 141 14 | 15 | Part IV. 16 | 17 | Is mergesort stable? 18 | Why or why not? 19 | ============================================================ 20 | In my implementation, it is not stable; but can be made stable by adding 21 | extra code (approximate 10 lines) 22 | 23 | Is quicksort stable? 24 | Why or why not? 25 | ============================================================ 26 | It is stable, because I 'scan' the 'queue' from left to right when 27 | partitioning 28 | -------------------------------------------------------------------------------- /hw/hw8/Timer.java: -------------------------------------------------------------------------------- 1 | /* Timer.java */ 2 | 3 | /** 4 | * Implements a simple stopwatch/timer class based on wall-clock time. 5 | **/ 6 | 7 | /** 8 | * RUNNING() == true <==> start() called with no corresponding 9 | * call to stop() 10 | * 11 | * All times are given in units of msec. 12 | **/ 13 | public class Timer { 14 | 15 | private boolean running; 16 | private long tStart; 17 | private long tFinish; 18 | private long tAccum; 19 | 20 | /** 21 | * Initializes Timer to 0 msec 22 | **/ 23 | public Timer() { 24 | reset(); 25 | } 26 | 27 | /** 28 | * Starts the timer. Accumulates time across multiple calls to start. 29 | **/ 30 | public void start() { 31 | running = true; 32 | tStart = System.currentTimeMillis(); 33 | tFinish = tStart; 34 | } 35 | 36 | /** 37 | * Stops the timer. returns the time elapsed since the last matching call 38 | * to start(), or zero if no such matching call was made. 39 | **/ 40 | public long stop() { 41 | tFinish = System.currentTimeMillis(); 42 | if (running) { 43 | running = false; 44 | 45 | long diff = tFinish - tStart; 46 | tAccum += diff; 47 | return diff; 48 | } 49 | return 0; 50 | } 51 | 52 | /** 53 | * if RUNNING() ==> returns the time since last call to start() 54 | * if !RUNNING() ==> returns total elapsed time 55 | **/ 56 | public long elapsed() { 57 | if (running) { 58 | return System.currentTimeMillis() - tStart; 59 | } 60 | 61 | return tAccum; 62 | } 63 | 64 | /** 65 | * Stops timing, if currently RUNNING(); resets 66 | * accumulated time to 0. 67 | */ 68 | public void reset() { 69 | running = false; 70 | tStart = 0; 71 | tFinish = 0; 72 | tAccum = 0; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /hw/hw8/list/LinkedQueue.java: -------------------------------------------------------------------------------- 1 | /* LinkedQueue.java */ 2 | 3 | package list; 4 | 5 | public class LinkedQueue implements Queue { 6 | 7 | private SListNode head; 8 | private SListNode tail; 9 | private int size; 10 | 11 | /** 12 | * LinkedQueue() constructs an empty queue. 13 | **/ 14 | public LinkedQueue() { 15 | size = 0; 16 | head = null; 17 | tail = null; 18 | } 19 | 20 | /** 21 | * size() returns the size of this Queue. 22 | * @return the size of this Queue. 23 | * Performance: runs in O(1) time. 24 | **/ 25 | public int size() { 26 | return size; 27 | } 28 | 29 | /** 30 | * isEmpty() returns true if this Queue is empty, false otherwise. 31 | * @return true if this Queue is empty, false otherwise. 32 | * Performance: runs in O(1) time. 33 | **/ 34 | public boolean isEmpty() { 35 | return size == 0; 36 | } 37 | 38 | /** 39 | * enqueue() inserts an object at the end of the Queue. 40 | * @param item the item to be enqueued. 41 | **/ 42 | public void enqueue(Object item) { 43 | if (head == null) { 44 | head = new SListNode(item); 45 | tail = head; 46 | } else { 47 | tail.next = new SListNode(item); 48 | tail = tail.next; 49 | } 50 | size++; 51 | } 52 | 53 | /** 54 | * dequeue() removes and returns the object at the front of the Queue. 55 | * @return the item dequeued. 56 | * @throws a QueueEmptyException if the Queue is empty. 57 | **/ 58 | public Object dequeue() throws QueueEmptyException { 59 | if (head == null) { 60 | throw new QueueEmptyException(); 61 | } else { 62 | Object o = head.item; 63 | head = head.next; 64 | size--; 65 | if (size == 0) { 66 | tail = null; 67 | } 68 | return o; 69 | } 70 | } 71 | 72 | /** 73 | * front() returns the object at the front of the Queue. 74 | * @return the item at the front of the Queue. 75 | * @throws a QueueEmptyException if the Queue is empty. 76 | **/ 77 | public Object front() throws QueueEmptyException { 78 | if (head == null) { 79 | throw new QueueEmptyException(); 80 | } else { 81 | return head.item; 82 | } 83 | } 84 | 85 | /** 86 | * 87 | * nth() returns the nth item in this LinkedQueue. 88 | * Items in the queue are numbered from 1. 89 | * @param n the number of the item to return. 90 | */ 91 | public Object nth(int n) { 92 | SListNode node = head; 93 | for (; n > 1; n--) { 94 | node = node.next; 95 | } 96 | return node.item; 97 | } 98 | 99 | /** 100 | * append() appends the contents of q onto the end of this LinkedQueue. 101 | * On completion, q is empty. 102 | * @param q the LinkedQueue whose contents should be appended onto this 103 | * LinkedQueue. 104 | **/ 105 | public void append(LinkedQueue q) { 106 | if (head == null) { 107 | head = q.head; 108 | } else { 109 | tail.next = q.head; 110 | } 111 | if (q.head != null) { 112 | tail = q.tail; 113 | } 114 | size = size + q.size; 115 | q.head = null; 116 | q.tail = null; 117 | q.size = 0; 118 | } 119 | 120 | /** 121 | * toString() converts this queue to a String. 122 | **/ 123 | public String toString() { 124 | String out = "[ "; 125 | try { 126 | for (int i = 0; i < size(); i++) { 127 | out = out + front() + " "; 128 | enqueue(dequeue()); 129 | } 130 | } catch (QueueEmptyException uf) { 131 | System.err.println("Error: attempt to dequeue from empty queue."); 132 | } 133 | return out + "]"; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /hw/hw8/list/Queue.java: -------------------------------------------------------------------------------- 1 | /* Queue.java */ 2 | 3 | package list; 4 | 5 | public interface Queue { 6 | 7 | /** 8 | * size() returns the size of this Queue. 9 | * @return the size of this Queue. 10 | * Performance: runs in O(1) time. 11 | **/ 12 | public int size(); 13 | 14 | /** 15 | * isEmpty() returns true if this Queue is empty, false otherwise. 16 | * @return true if this Queue is empty, false otherwise. 17 | * Performance: runs in O(1) time. 18 | **/ 19 | public boolean isEmpty(); 20 | 21 | /** 22 | * enqueue() inserts an object at the end of the Queue. 23 | * @param item the item to be enqueued. 24 | **/ 25 | public void enqueue(Object item); 26 | 27 | /** 28 | * dequeue() removes and returns the object at the front of the Queue. 29 | * @return the item dequeued. 30 | * @throws a QueueEmptyException if the Queue is empty. 31 | **/ 32 | public Object dequeue() throws QueueEmptyException; 33 | 34 | /** 35 | * front() returns the object at the front of the Queue. 36 | * @return the item at the front of the Queue. 37 | * @throws a QueueEmptyException if the Queue is empty. 38 | **/ 39 | public Object front() throws QueueEmptyException; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /hw/hw8/list/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | /* QueueEmptyException.java */ 2 | 3 | package list; 4 | 5 | public class QueueEmptyException extends Exception { 6 | 7 | public QueueEmptyException() { 8 | super(); 9 | } 10 | 11 | public QueueEmptyException(String s) { 12 | super(s); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /hw/hw8/list/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * SListNode is a class used internally by the SList class. An SList object 7 | * is a singly-linked list, and an SListNode is a node of a singly-linked 8 | * list. Each SListNode has two references: one to an object, and one to 9 | * the next node in the list. 10 | */ 11 | 12 | class SListNode { 13 | Object item; 14 | SListNode next; 15 | 16 | /** 17 | * SListNode() (with one parameter) constructs a list node referencing the 18 | * item "obj". 19 | */ 20 | 21 | SListNode(Object obj) { 22 | item = obj; 23 | next = null; 24 | } 25 | 26 | /** 27 | * SListNode() (with two parameters) constructs a list node referencing the 28 | * item "obj", whose next list node is to be "next". 29 | */ 30 | 31 | SListNode(Object obj, SListNode next) { 32 | item = obj; 33 | this.next = next; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /hw/hw9/set/DisjointSets.java: -------------------------------------------------------------------------------- 1 | /* DisjointSets.java */ 2 | 3 | package set; 4 | 5 | /** 6 | * A disjoint sets ADT. Performs union-by-size and path compression. 7 | * Implemented using arrays. There is no error checking whatsoever. 8 | * By adding your own error-checking, you might save yourself a lot of time 9 | * finding bugs in your application code for Project 3 and Homework 9. 10 | * Without error-checking, expect bad things to happen if you try to unite 11 | * two elements that are not roots of their respective sets, or are not 12 | * distinct. 13 | * 14 | * Elements are represented by ints, numbered from zero. 15 | **/ 16 | 17 | public class DisjointSets { 18 | 19 | private int[] array; 20 | 21 | /** 22 | * Construct a disjoint sets object. 23 | * 24 | * @param numElements the initial number of elements--also the initial 25 | * number of disjoint sets, since every element is initially in its own set. 26 | **/ 27 | public DisjointSets(int numElements) { 28 | array = new int [numElements]; 29 | for (int i = 0; i < array.length; i++) { 30 | array[i] = -1; 31 | } 32 | } 33 | 34 | /** 35 | * union() unites two disjoint sets into a single set. A union-by-size 36 | * heuristic is used to choose the new root. This method will corrupt 37 | * the data structure if root1 and root2 are not roots of their respective 38 | * sets, or if they're identical. 39 | * 40 | * @param root1 the root of the first set. 41 | * @param root2 the root of the other set. 42 | * Modified by: Ryan (Weiran) Zhao 43 | * do find before union 2 sets, also forbid joining one set with itself 44 | **/ 45 | public void union(int root1, int root2) { 46 | root1 = find(root1); 47 | root2 = find(root2); 48 | if(root1 == root2) { 49 | System.err.println("trying to union set with itself"); 50 | return; 51 | } 52 | if (array[root2] < array[root1]) { // root2 has larger tree 53 | array[root2] += array[root1]; // update # of items in root2's tree 54 | array[root1] = root2; // make root2 new root 55 | } else { // root1 has equal or larger tree 56 | array[root1] += array[root2]; // update # of items in root1's tree 57 | array[root2] = root1; // make root1 new root 58 | } 59 | } 60 | 61 | /** 62 | * find() finds the (int) name of the set containing a given element. 63 | * Performs path compression along the way. 64 | * 65 | * @param x the element sought. 66 | * @return the set containing x. 67 | **/ 68 | public int find(int x) { 69 | if (array[x] < 0) { 70 | return x; // x is the root of the tree; return it 71 | } else { 72 | // Find out who the root is; compress path by making the root x's parent. 73 | array[x] = find(array[x]); 74 | return array[x]; // Return the root 75 | } 76 | } 77 | 78 | /** 79 | * main() is test code. All the find()s on the same output line should be 80 | * identical. 81 | **/ 82 | public static void main(String[] args) { 83 | int NumElements = 128; 84 | int NumInSameSet = 16; 85 | 86 | DisjointSets s = new DisjointSets(NumElements); 87 | int set1, set2; 88 | 89 | for (int k = 1; k < NumInSameSet; k *= 2) { 90 | for (int j = 0; j + k < NumElements; j += 2 * k) { 91 | set1 = s.find(j); 92 | set2 = s.find(j + k); 93 | s.union(set1, set2); 94 | } 95 | } 96 | 97 | for (int i = 0; i < NumElements; i++) { 98 | System.out.print(s.find(i) + "*"); 99 | if (i % NumInSameSet == NumInSameSet - 1) { 100 | System.out.println(); 101 | } 102 | } 103 | System.out.println(); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /lab/lab1/Names.java: -------------------------------------------------------------------------------- 1 | /* Names.java */ 2 | 3 | import java.io.*; 4 | 5 | /** The Names class provides a single function, main, that will 6 | * perform various manipulations of the name John Fitzgerald Kennedy. 7 | * This is a modification of the program on page 43 of Arnow and Weiss. 8 | */ 9 | 10 | class Names { 11 | 12 | /** Performs various string operations on the name John Fitzgerald Kennedy. 13 | * @param arg is not used. 14 | */ 15 | public static void main(String arg[]) { 16 | String first = "John"; 17 | String middle = "Fitzgerald"; 18 | String last = "Kennedy"; 19 | String initials; 20 | String firstInit, middleInit, lastInit; 21 | 22 | firstInit = first.substring(0,1); 23 | middleInit = middle.substring(0,1); 24 | lastInit = last.substring(0,1); 25 | initials = firstInit.concat(middleInit); 26 | initials = initials.concat(lastInit); 27 | 28 | System.out.println(); 29 | System.out.println(first + " " + middle + " " + last + " "); 30 | System.out.println(initials); 31 | System.out.println(last + ", " + first + " " + middle); 32 | System.out.println(last + ", " + first + " " + middleInit +"."); 33 | System.out.println(first.toUpperCase() + " " + last.toUpperCase()); 34 | 35 | System.out.println(first + " equals john is " + first.equals("john")); 36 | System.out.println(first + " equals john (ignoring case) is " 37 | + first.equalsIgnoreCase("john")); 38 | System.out.println("The character at index 3 in " + middle + " is " + 39 | middle.substring(3,4)); 40 | System.out.println("The index of \"gerald\" within " + middle + " is " + 41 | middle.indexOf("gerald")); 42 | System.out.println("The index of \"gerald\" within " + last + " is " + 43 | last.indexOf("gerald")); 44 | 45 | System.out.println(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /lab/lab1/roster.txt: -------------------------------------------------------------------------------- 1 | AI DAVID TA-WEI 2 | ARELLANO VICTOR MANUEL JR 3 | AYTAC JON M 4 | BAYER DAVID LAWRENCE 5 | CHAN EDWARD CHEUK-FAN 6 | CHAN JEFFREY SIU-YUEN 7 | CHE TAMMY 8 | CHEN HUA 9 | CHEN JIALAN 10 | CHEN WELDON B 11 | CHEN YING-HANG 12 | CHENG GARY T 13 | CHENG LI WEI 14 | CHEUNG JIA-HAW JUSTIN 15 | CHIU YI KAN 16 | CHOI CHUL KYU 17 | CHOI VALERIE SUNAH 18 | CHONG ERIC W T 19 | CHOW TSECHEUNG 20 | CLERKLEY CORNELIUS EUGENE 21 | CU JASON ALEXANDER 22 | DAVIES MATTHEW B 23 | ENG LAWRENCE PATRICK 24 | ETUK NTIEDO 25 | FAN JIUN 26 | FIEBELKORN JOERN 27 | FIKES STEPHEN RANDLOPH 28 | GILL REGAN FRANCES 29 | GLORIA ADOLFO RUDY 30 | HASHEMI HOUMAN 31 | HAWKES THOMAS NATHANIEL 32 | HSIAO WALTER 33 | HUANG CATHERINE 34 | HUANG CLARK M 35 | HUNG RICHARD TSUWEN 36 | HURWITZ CAROL 37 | INTARAPANICH APICHART 38 | JALILVAND FARHAD 39 | JOSHI KALPANA 40 | JUE JEFFREY PEARCE 41 | KAN ANDREW K 42 | KHAN HAROON 43 | KIL DONGHYEOK 44 | KIM CHRISTINE JUNG 45 | KIM JAE HO 46 | KING HARVEY H 47 | KOSOKO YETUNDE FOLASHADE 48 | KUIK FUEI SEN 49 | KUSNADI ALI 50 | LAM CON HAO 51 | LAW SAMANTHA PUI SZE 52 | LE DIEP-VU ANH 53 | LEE CHANG-KEUN 54 | LEE KIN PONG 55 | LIM YU KEE 56 | LIN CARL SHIHR 57 | LIN PATRICIA YA-CHI 58 | LIU YU-WEI JAMES 59 | LOWRY JOHN ALEXANDER 60 | LY CANDACE KHENH 61 | MARTIN ALEISTAIR GILES 62 | MCDAID MICHAEL F 63 | MONROE ANTHONY STEPHEN 64 | MORENO TIMOTHY JASON 65 | NG DARREN 66 | NG ERIC MAN-HO 67 | NG MAN YAM ANDY 68 | NGUYEN TRI HUU LUONG 69 | NGUYEN TRIET MINH 70 | NOH SAXON SEOL 71 | PADILLA JULIO V 72 | PAGONIS DIMITRI 73 | PARK CHI HOON 74 | PRACHAYAAMORN NATH 75 | REN JIMMY PEI-YUAN 76 | ROSE PAUL ANTHONY 77 | SHEPPY ALFREDO DALE 78 | SHIH CATHY PEIWEN 79 | SON JOON WON 80 | SONG XIANGJUN 81 | SUN LIHUA 82 | SUN YULAH SHIH 83 | TATE STEVEN WAYNE 84 | THOMPSON HOWARD KNUT 85 | TSAI SUNG-HO 86 | TSU WILLIAM PUN-SIN 87 | TUGI ZELEALEM ASSEFA 88 | VERMETTE JOSHUA PAUL 89 | VINCENT BRENT ALLEN 90 | WANG ANTHONY LOUNG-HAU 91 | WIDARMA AGUSTINUS T 92 | WONG HOK FUNG 93 | XA LILY LAI KIN 94 | YAN DONG 95 | YAZDI REZA FANI 96 | YEUNG MING KONG 97 | YOON JOSEPH S 98 | YOON WON HEE 99 | -------------------------------------------------------------------------------- /lab/lab10/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 10 2 | April 9-10, 2013 3 | 4 | Goal: to give you experience with general trees and encapsulation. The trees 5 | we use in this lab use the SibTree data structure described in Lecture 24 6 | (which you should review now), and are encapsulated in the same manner as the 7 | Homework 5 lists (whose design was the subject of Lecture 19). SibTrees are 8 | designed to ensure that the SibTree and SibTreeNode invariants (which are 9 | written out in their respective files) cannot be violated. 10 | 11 | Please make sure you have a partner for this lab. 12 | 13 | Copy the Lab 10 directory by doing the following, starting from your home 14 | directory. 15 | 16 | cp -r ~cs61b/lab/lab10 . 17 | 18 | All the code is in the tree package. You can compile it from your lab10 19 | directory with "javac -g tree/*.java". Extensive test code is provided and 20 | can be run with "java tree.SibTree". 21 | 22 | Familiarize yourself with the fields and methods of the SibTree and SibTreeNode 23 | classes. SibTree has two fields, one inherited from the Tree abstract class. 24 | 25 | int size; // The number of SibTreeNodes in the SibTree. 26 | SibTreeNode root; // The node that serves as the root of the tree. 27 | 28 | SibTreeNode has six fields, two inherited from the TreeNode abstract class. 29 | 30 | Object item; // Item stored at this SibTreeNode. 31 | boolean valid; // True if and only if this is a valid node. 32 | SibTree myTree; // The SibTree that contains this node. 33 | SibTreeNode parent; // This node's parent. 34 | SibTreeNode firstChild; // This node's first (leftmost) child. 35 | SibTreeNode nextSibling; // This node's next sibling to the right. 36 | 37 | As with the Homework 5 lists, the Tree class defines certain nodes to be 38 | invalid. In constrast to the Homework 5 lists, valid and invalid nodes are 39 | distinguished solely through the state of the "valid" field. When a TreeNode 40 | is removed from a tree, it becomes invalid. Methods like parent(), child(), 41 | and nextSibling() return an invalid node (never null!) if no such node exists. 42 | You may create an invalid node by calling the zero-parameter SibTreeNode() 43 | constructor. You may test whether a node n is valid by calling 44 | n.isValidNode(). 45 | 46 | Every valid SibTreeNode is in some tree, specified by the "myTree" field. 47 | 48 | Your task is to implement the parent(), insertChild(), and removeLeaf() methods 49 | of the SibTreeNode class. After you write each one, you may use the test code 50 | to check your progress. 51 | 52 | Part I: Accessing a Node's Parent (1 point) 53 | -------------------------------------------- 54 | Fill in the body of the parent() method in SibTreeNode.java. parent() returns 55 | the SibTreeNode that is the parent of "this" SibTreeNode. Throw an 56 | InvalidNodeException if "this" node is not valid. If "this" node is the root, 57 | return an invalid node. 58 | 59 | Part II: Inserting New Children (3 points) 60 | ------------------------------------------- 61 | Fill in the body of insertChild(). insertChild() takes two parameters: an 62 | item and an integer c. Create a new child that is the cth child (from the 63 | left) of "this" node, and references the item indicated. Existing children 64 | numbered c or higher are shifted one place to the right to accommodate. If 65 | c < 1, act as if c is 1. If "this" node has fewer than c children, the new 66 | node is the last sibling. Don't forget that SibTrees have a "size" field that 67 | needs to be updated. 68 | 69 | BONUS Part III: Removing a Leaf (1 bonus point) 70 | ------------------------------------------------ 71 | Fill in the body of removeLeaf(), which removes "this" node from the tree if it 72 | is a leaf, and does nothing if it is not a leaf. As always, throw an 73 | InvalidNodeException if "this" node is not valid. Upon completion, "this" node 74 | should be invalid. 75 | 76 | Check-off 77 | --------- 78 | Show your TA or Lab Assistant the code you have written, and run the test 79 | program. You'll receive points for each part that runs without printing any 80 | error messages. You can receive up to 5 points out of 4. 81 | 82 | (Note to TAs: be stringent about the bonus point, and don't give extra time.) 83 | -------------------------------------------------------------------------------- /lab/lab10/tree/InvalidNodeException.java: -------------------------------------------------------------------------------- 1 | /* InvalidNodeException.java */ 2 | 3 | package tree; 4 | 5 | /** 6 | * Implements an Exception that signals an attempt to use an invalid ListNode. 7 | */ 8 | 9 | public class InvalidNodeException extends Exception { 10 | protected InvalidNodeException() { 11 | super(); 12 | } 13 | 14 | protected InvalidNodeException(String s) { 15 | super(s); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /lab/lab10/tree/Tree.java: -------------------------------------------------------------------------------- 1 | /* Tree.java */ 2 | 3 | package tree; 4 | 5 | /** 6 | * A Tree is a mutable ADT for general trees (wherein a node can have any 7 | * number of children). 8 | * @author Jonathan Shewchuk 9 | */ 10 | 11 | public abstract class Tree { 12 | 13 | /** 14 | * size is the number of items in the tree. 15 | **/ 16 | 17 | protected int size; 18 | 19 | /** 20 | * isEmpty() returns true if this Tree is empty, false otherwise. 21 | * 22 | * @return true if this Tree is empty, false otherwise. 23 | * 24 | * Performance: runs in O(1) time. 25 | **/ 26 | public boolean isEmpty() { 27 | return size == 0; 28 | } 29 | 30 | /** 31 | * size() returns the size of this Tree. 32 | * 33 | * @return the size of this Tree. 34 | * 35 | * Performance: runs in O(1) time. 36 | **/ 37 | public int size() { 38 | return size; 39 | } 40 | 41 | /** 42 | * root() returns the root node, if one exists. Returns an invalid node if 43 | * the tree is empty. 44 | */ 45 | public abstract TreeNode root(); 46 | 47 | /** 48 | * insertRoot() inserts a node containing "item" at the root of the tree. 49 | * If a root already exists, it becomes a child of the new node. 50 | */ 51 | public abstract void insertRoot(Object item); 52 | 53 | } 54 | -------------------------------------------------------------------------------- /lab/lab10/tree/TreeNode.java: -------------------------------------------------------------------------------- 1 | /* TreeNode.java */ 2 | 3 | package tree; 4 | 5 | /** 6 | * A TreeNode object is a mutable node in a tree. No implementation is 7 | * provided. 8 | * 9 | * DO NOT CHANGE THIS FILE. 10 | * @author Jonathan Shewchuk 11 | */ 12 | 13 | public abstract class TreeNode { 14 | 15 | /** 16 | * item references the item stored in this node. 17 | * valid is true if and only if this is a valid node in some Tree. 18 | * 19 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 20 | */ 21 | 22 | protected Object item; 23 | protected boolean valid; 24 | 25 | /** 26 | * isValidNode returns true if this node is valid; false otherwise. 27 | * 28 | * @return true if this node is valid; false otherwise. 29 | * 30 | * Performance: runs in O(1) time. 31 | */ 32 | public boolean isValidNode() { 33 | return valid; 34 | } 35 | 36 | /** 37 | * item() returns this node's item. If this node is invalid, 38 | * throws an exception. 39 | * 40 | * @return the item stored in this node. 41 | * 42 | * Performance: runs in O(1) time. 43 | */ 44 | public Object item() throws InvalidNodeException { 45 | if (isValidNode()) { 46 | return item; 47 | } else { 48 | throw new InvalidNodeException(); 49 | } 50 | } 51 | 52 | /** 53 | * setItem() sets this node's item to "item". If this node is invalid, 54 | * throws an exception. 55 | * 56 | * Performance: runs in O(1) time. 57 | */ 58 | public void setItem(Object item) throws InvalidNodeException { 59 | if (isValidNode()) { 60 | this.item = item; 61 | } else { 62 | throw new InvalidNodeException(); 63 | } 64 | } 65 | 66 | /** 67 | * children() returns the number of children of the node at this position. 68 | */ 69 | public abstract int children(); 70 | 71 | /** 72 | * parent() returns the parent TreeNode of this TreeNode. Throws an 73 | * exception if `this' is not a valid node. Returns an invalid TreeNode if 74 | * this node is the root. 75 | */ 76 | public abstract TreeNode parent() throws InvalidNodeException; 77 | 78 | /** 79 | * child() returns the cth child of this TreeNode. Throws an exception if 80 | * `this' is not a valid node. Returns an invalid TreeNode if there is no 81 | * cth child. 82 | */ 83 | public abstract TreeNode child(int c) throws InvalidNodeException; 84 | 85 | /** 86 | * nextSibling() returns the next sibling TreeNode to the right from this 87 | * TreeNode. Throws an exception if `this' is not a valid node. Returns 88 | * an invalid TreeNode if there is no sibling to the right of this node. 89 | */ 90 | public abstract TreeNode nextSibling() throws InvalidNodeException; 91 | 92 | /** 93 | * insertChild() inserts an item as the cth child of this node. Existing 94 | * children numbered c or higher are shifted one place to the right 95 | * to accommodate. If the current node has fewer than c children, 96 | * the new item is inserted as the last child. If c < 1, act as if c is 1. 97 | */ 98 | public abstract void insertChild(Object item, int c) throws 99 | InvalidNodeException; 100 | 101 | /** 102 | * removeLeaf() removes the node at the current position from the tree if 103 | * it is a leaf. Does nothing if `this' has one or more children. Throws 104 | * an exception if `this' is not a valid node. If 'this' has siblings to 105 | * its right, those siblings are all shifted left by one. 106 | */ 107 | public abstract void removeLeaf() throws InvalidNodeException; 108 | 109 | } 110 | -------------------------------------------------------------------------------- /lab/lab11/dict/BinaryTreeNode.java: -------------------------------------------------------------------------------- 1 | /* BinaryTreeNode.java */ 2 | 3 | package dict; 4 | 5 | /** 6 | * BinaryTreeNode represents a node in a binary tree. 7 | * 8 | * DO NOT CHANGE THIS FILE. 9 | **/ 10 | class BinaryTreeNode { 11 | 12 | /** 13 | * entry is the key/value pair stored in this node. 14 | * parent is the parent of this node. 15 | * leftChild and rightChild are the children of this node. 16 | **/ 17 | Entry entry; 18 | BinaryTreeNode parent; 19 | BinaryTreeNode leftChild, rightChild; 20 | 21 | /** Simple constructor that sets the entry. 22 | * The rest of the fields are set to null. */ 23 | BinaryTreeNode(Entry entry) { 24 | this(entry, null, null, null); 25 | } 26 | 27 | /** Simple constructor that sets the entry and parent. 28 | * The rest of the fields are set to null. */ 29 | BinaryTreeNode(Entry entry, BinaryTreeNode parent) { 30 | this(entry, parent, null, null); 31 | } 32 | 33 | /** Simple constructor that sets all of the node's fields. */ 34 | BinaryTreeNode(Entry entry, BinaryTreeNode parent, 35 | BinaryTreeNode left, BinaryTreeNode right) { 36 | this.entry = entry; 37 | this.parent = parent; 38 | leftChild = left; 39 | rightChild = right; 40 | } 41 | 42 | public String toString() { 43 | String s = ""; 44 | 45 | if (leftChild != null) { 46 | s = "(" + leftChild.toString() + ")"; 47 | } 48 | s = s + entry.key().toString() + entry.value(); 49 | if (rightChild != null) { 50 | s = s + "(" + rightChild.toString() + ")"; 51 | } 52 | return s; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /lab/lab11/dict/Dictionary.java: -------------------------------------------------------------------------------- 1 | /* Dictionary.java */ 2 | 3 | package dict; 4 | 5 | /** 6 | * An interface for (unordered) dictionary ADTs. 7 | * 8 | * DO NOT CHANGE THIS FILE. 9 | **/ 10 | 11 | public interface Dictionary { 12 | 13 | /** 14 | * Returns the number of entries stored in the dictionary. Entries with 15 | * the same key (or even the same key and value) each still count as 16 | * a separate entry. 17 | * @return number of entries in the dictionary. 18 | **/ 19 | 20 | public int size(); 21 | 22 | /** 23 | * Tests if the dictionary is empty. 24 | * 25 | * @return true if the dictionary has no entries; false otherwise. 26 | **/ 27 | 28 | public boolean isEmpty(); 29 | 30 | /** 31 | * Create a new Entry object referencing the input key and associated value, 32 | * and insert the entry into the dictionary. Return a reference to the new 33 | * entry. Multiple entries with the same key (or even the same key and 34 | * value) can coexist in the dictionary. 35 | * 36 | * @param key the key by which the entry can be retrieved. 37 | * @param value an arbitrary object. 38 | * @return an entry containing the key and value. 39 | **/ 40 | 41 | public Entry insert(Object key, Object value); 42 | 43 | /** 44 | * Search for an entry with the specified key. If such an entry is found, 45 | * return it; otherwise return null. If several entries have the specified 46 | * key, choose one arbitrarily and return it. 47 | * 48 | * @param key the search key. 49 | * @return an entry containing the key and an associated value, or null if 50 | * no entry contains the specified key. 51 | **/ 52 | 53 | public Entry find(Object key); 54 | 55 | /** 56 | * Remove an entry with the specified key. If such an entry is found, 57 | * remove it from the table and return it; otherwise return null. 58 | * If several entries have the specified key, choose one arbitrarily, then 59 | * remove and return it. 60 | * 61 | * @param key the search key. 62 | * @return an entry containing the key and an associated value, or null if 63 | * no entry contains the specified key. 64 | */ 65 | 66 | public Entry remove(Object key); 67 | 68 | /** 69 | * Remove all entries from the dictionary. 70 | */ 71 | 72 | public void makeEmpty(); 73 | 74 | } 75 | -------------------------------------------------------------------------------- /lab/lab11/dict/Entry.java: -------------------------------------------------------------------------------- 1 | /* Entry.java */ 2 | 3 | package dict; 4 | 5 | /** 6 | * A class for dictionary entries. 7 | * 8 | * DO NOT CHANGE THIS FILE. It is part of the interface of the 9 | * Dictionary ADT. 10 | **/ 11 | 12 | public class Entry { 13 | 14 | protected Object key; 15 | protected Object value; 16 | 17 | public Object key() { 18 | return key; 19 | } 20 | 21 | public Object value() { 22 | return value; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /lab/lab11/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 11 2 | April 16-17, 2013 3 | 4 | Please make sure you have a partner for this lab. 5 | 6 | Copy the Lab 11 directory by doing the following, starting from your home 7 | directory. 8 | 9 | cp -r ~cs61b/lab/lab11 . 10 | 11 | All the code is in the dict package. You can compile it from your lab11 12 | directory with 13 | 14 | javac -g dict/*.java 15 | 16 | Some test code is provided and can be run with 17 | 18 | java dict.BinaryTree 19 | 20 | Familiarize yourself with the fields and methods of the BinaryTree and 21 | BinaryTreeNode classes. BinaryTree is an implementation of the Dictionary 22 | interface (which you also used in Homework 6) as a binary search tree. 23 | Note that BinaryTree uses Comparable objects as keys (since it is an ordered 24 | dictionary), whereas in the Dictionary abstract class, keys are declared as 25 | plain Objects. Thus you will occasionally need to cast Objects to Comparables. 26 | 27 | Part I: Finding an Element in a Binary Search Tree (2 points) 28 | -------------------------------------------------------------- 29 | Complete the implementation of the find() method in dict/BinaryTree.java by 30 | filling in the body of findHelper(). find() takes a key as its single 31 | parameter, and returns an element associated with that key, or null if there is 32 | none. (If there are several elements associated with a key, it doesn't matter 33 | which one is returned.) findHelper() helps by recursively finding and 34 | returning a node that contains the key (or null if no such node exists). 35 | 36 | Take a look at insertHelper() for inspiration. find() should run in O(d) time 37 | on a tree with depth d. 38 | 39 | Part II: Removing an Element with a Given Key (2 points) 40 | --------------------------------------------------------- 41 | Fill in the body of remove() method in BinaryTree.java. remove() takes a key 42 | as its single parameter, and removes one item having that key if the tree 43 | contains one. (If there are several elements associated with a key, it doesn't 44 | matter which one is removed and returned.) remove() returns the same value 45 | that find() returns, but should not call find(). However, remove() SHOULD use 46 | the findHelper() method you wrote for Part I. 47 | 48 | remove() should run in O(d) time if the depth of the tree is d. 49 | 50 | Check-off 51 | --------- 52 | Show your TA or Lab Assistant the code you have written, and run the test 53 | program. You'll receive points for each part that runs correctly. 54 | 55 | 2 points: If find() works correctly. 56 | 1 point: If remove() works for nodes that have no child or one child. 57 | 1 point: If remove() works for nodes that have two children. 58 | -------------------------------------------------------------------------------- /lab/lab12/SortPerf.java: -------------------------------------------------------------------------------- 1 | /* SortPerf.java */ 2 | 3 | import java.util.Random; 4 | import java.io.*; 5 | 6 | class SortPerf { 7 | 8 | private static final long INIT_SEED = 1234567; 9 | 10 | /** 11 | * Times a sorting algorithm on data for arrays of size incN, 2 * incN, ..., 12 | * maxN and writes the timing data to "outFileName". 13 | * 14 | * For an array of each size, sorts the random data numTrials times to 15 | * produce an total running time. 16 | **/ 17 | public static void main(String[] argv) throws IOException { 18 | 19 | String outFileName = ""; 20 | int incN = 0; 21 | int maxN = 0; 22 | int numTrials = 0; 23 | String sortAlg = ""; 24 | if (argv.length != 5) { 25 | printUsage(); 26 | return; 27 | } else try { 28 | sortAlg = argv[0]; 29 | incN = Integer.parseInt(argv[1]); 30 | maxN = Integer.parseInt(argv[2]); 31 | numTrials = Integer.parseInt(argv[3]); 32 | outFileName = argv[4]; 33 | } catch (Exception e) { 34 | printUsage(); 35 | return; 36 | } 37 | PrintWriter timings = new PrintWriter(new FileOutputStream(outFileName)); 38 | timings.println("# Results for " + numTrials + " trials"); 39 | timings.println("# n time (msec)"); 40 | timings.println("# ---------------"); 41 | 42 | timeSort(timings, incN, maxN, numTrials, sortAlg); 43 | timings.close(); 44 | System.out.println("done! results in `" + outFileName + "'"); 45 | } 46 | 47 | /** 48 | * Times a sorting algorithm on data for arrays of size incN, 2 * incN, ..., 49 | * maxN. Performs numTrials trials and computes the total running time. 50 | */ 51 | private static void timeSort(PrintWriter timings, int incN, int maxN, 52 | int numTrials, String sortAlg) { 53 | Timer stopWatch = new Timer(); 54 | for (int n = incN; n <= maxN; n += incN) { 55 | System.out.println("timing n == " + n + " ... "); 56 | stopWatch.reset(); 57 | int[][] data = new int[numTrials + 1][]; 58 | for (int t = 0; t < numTrials + 1; t++) { 59 | data[t] = randomData(n); 60 | } 61 | if (sortAlg.equals("insert")) { 62 | Sort.insertionSort(data[numTrials]); // sort once without counting 63 | stopWatch.start(); 64 | for (int t = 0; t < numTrials; t++) { 65 | Sort.insertionSort(data[t]); 66 | } 67 | stopWatch.stop(); 68 | } else if (sortAlg.equals("select")) { 69 | Sort.selectionSort(data[numTrials]); // sort once without counting 70 | stopWatch.start(); 71 | for(int t = 0; t < numTrials; t++) { 72 | Sort.selectionSort(data[t]); 73 | } 74 | stopWatch.stop(); 75 | } else if (sortAlg.equals("merge")) { 76 | Sort.mergeSort(data[numTrials]); // sort once without counting 77 | stopWatch.start(); 78 | for (int t = 0; t < numTrials; t++) { 79 | Sort.mergeSort(data[t]); 80 | } 81 | stopWatch.stop(); 82 | } else if (sortAlg.equals("quick")) { 83 | Sort.quicksort(data[numTrials]); // sort once without counting 84 | stopWatch.start(); 85 | for(int t = 0; t < numTrials; t++) { 86 | Sort.quicksort(data[t]); 87 | } 88 | stopWatch.stop(); 89 | } else if (sortAlg.equals("best")) { 90 | YourSort.sort(data[numTrials]); // sort once without counting 91 | stopWatch.start(); 92 | for(int t = 0; t < numTrials; t++) { 93 | YourSort.sort(data[t]); 94 | } 95 | stopWatch.stop(); 96 | } else { 97 | printUsage(); 98 | return; 99 | } 100 | long totalTime = stopWatch.elapsed(); 101 | timings.println(n + " " + totalTime); 102 | } 103 | } 104 | 105 | // Prints the contents of A. 106 | private static void printData(int[] A) { 107 | for (int i = 0; i < A.length - 1; i++) { 108 | System.out.print(A[i] + ", "); 109 | } 110 | if (A.length - 1 >= 0) { 111 | System.out.println(A[A.length - 1]); 112 | } 113 | } 114 | 115 | /** 116 | * Assumes n > 0 117 | * Returns an array of `n' randomly selected integers. 118 | **/ 119 | private static int[] randomData(int n) { 120 | 121 | // choose same sequence of random numbers so that 122 | // we can fairly compare our sorting algorithms 123 | 124 | Random randGen = new Random(INIT_SEED); 125 | 126 | int[] newData = new int[n]; 127 | for (int i = 0; i < n; i++) { 128 | newData[i] = randGen.nextInt(); 129 | } 130 | 131 | return newData; 132 | } 133 | 134 | /** Print a message saying how the main method should be called. */ 135 | private static void printUsage() { 136 | System.out.println("Usage:"); 137 | System.out.println(" java SortPerf "); 138 | System.out.println(" sort - one of insert, merge, quick, or best"); 139 | System.out.println(" incr - the initial array size and increment"); 140 | System.out.println(" max - the maximum array size"); 141 | System.out.println(" runs - the number of runs for each size"); 142 | System.out.println(" outfile - is the name of the timing output file"); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /lab/lab12/Timer.java: -------------------------------------------------------------------------------- 1 | /* Timer.java */ 2 | 3 | /** 4 | * Implements a simple stopwatch/timer class based on wall-clock time. 5 | **/ 6 | 7 | /** 8 | * RUNNING() == true <==> start() called with no corresponding 9 | * call to stop() 10 | * 11 | * All times are given in units of msec. 12 | **/ 13 | public class Timer { 14 | 15 | private boolean running; 16 | private long tStart; 17 | private long tFinish; 18 | private long tAccum; 19 | 20 | /** 21 | * Initializes Timer to 0 msec 22 | **/ 23 | public Timer() { 24 | reset(); 25 | } 26 | 27 | /** 28 | * Starts the timer. Accumulates time across multiple calls to start. 29 | **/ 30 | public void start() { 31 | running = true; 32 | tStart = System.currentTimeMillis(); 33 | tFinish = tStart; 34 | } 35 | 36 | /** 37 | * Stops the timer. returns the time elapsed since the last matching call 38 | * to start(), or zero if no such matching call was made. 39 | **/ 40 | public long stop() { 41 | tFinish = System.currentTimeMillis(); 42 | if (running) { 43 | running = false; 44 | 45 | long diff = tFinish - tStart; 46 | tAccum += diff; 47 | return diff; 48 | } 49 | return 0; 50 | } 51 | 52 | /** 53 | * if RUNNING() ==> returns the time since last call to start() 54 | * if !RUNNING() ==> returns total elapsed time 55 | **/ 56 | public long elapsed() { 57 | if (running) { 58 | return System.currentTimeMillis() - tStart; 59 | } 60 | 61 | return tAccum; 62 | } 63 | 64 | /** 65 | * Stops timing, if currently RUNNING(); resets 66 | * accumulated time to 0. 67 | */ 68 | public void reset() { 69 | running = false; 70 | tStart = 0; 71 | tFinish = 0; 72 | tAccum = 0; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /lab/lab12/YourSort.java: -------------------------------------------------------------------------------- 1 | /* YourSort.java */ 2 | 3 | public class YourSort { 4 | 5 | public static void sort(int[] A) { 6 | if(A.length < 65) { 7 | Sort.insertionSort(A); 8 | } else { 9 | Sort.quicksort(A); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /lab/lab12/best.dat: -------------------------------------------------------------------------------- 1 | # Results for 10000 trials 2 | # n time (msec) 3 | # --------------- 4 | 5 4 5 | 10 1 6 | 15 1 7 | 20 3 8 | 25 2 9 | 30 3 10 | 35 8 11 | 40 12 12 | 45 13 13 | 50 15 14 | 55 18 15 | 60 21 16 | 65 41 17 | 70 10 18 | 75 13 19 | 80 12 20 | 85 13 21 | 90 15 22 | 95 15 23 | 100 19 24 | 105 15 25 | 110 19 26 | 115 19 27 | 120 19 28 | 125 21 29 | 130 20 30 | 135 21 31 | 140 23 32 | 145 22 33 | 150 26 34 | 155 26 35 | 160 32 36 | 165 27 37 | 170 29 38 | 175 30 39 | 180 32 40 | 185 36 41 | 190 32 42 | 195 35 43 | 200 38 44 | 205 37 45 | 210 37 46 | 215 40 47 | 220 40 48 | 225 40 49 | 230 44 50 | 235 41 51 | 240 43 52 | 245 46 53 | 250 46 54 | 255 48 55 | 260 45 56 | 265 52 57 | 270 50 58 | 275 49 59 | 280 53 60 | 285 54 61 | 290 53 62 | 295 56 63 | 300 55 64 | -------------------------------------------------------------------------------- /lab/lab12/insert.dat: -------------------------------------------------------------------------------- 1 | # Results for 10000 trials 2 | # n time (msec) 3 | # --------------- 4 | 5 3 5 | 10 2 6 | 15 2 7 | 20 1 8 | 25 4 9 | 30 5 10 | 35 5 11 | 40 7 12 | 45 6 13 | 50 8 14 | 55 9 15 | 60 10 16 | 65 13 17 | 70 17 18 | 75 17 19 | 80 18 20 | 85 19 21 | 90 23 22 | 95 26 23 | 100 28 24 | 105 31 25 | 110 34 26 | 115 37 27 | 120 39 28 | 125 41 29 | 130 44 30 | 135 46 31 | 140 49 32 | 145 53 33 | 150 55 34 | 155 58 35 | 160 63 36 | 165 66 37 | 170 69 38 | 175 74 39 | 180 75 40 | 185 84 41 | 190 83 42 | 195 87 43 | 200 91 44 | 205 95 45 | 210 99 46 | 215 105 47 | 220 109 48 | 225 116 49 | 230 119 50 | 235 127 51 | 240 131 52 | 245 136 53 | 250 140 54 | 255 151 55 | 260 145 56 | 265 153 57 | 270 157 58 | 275 161 59 | 280 167 60 | 285 170 61 | 290 174 62 | 295 186 63 | 300 186 64 | -------------------------------------------------------------------------------- /lab/lab12/merge.dat: -------------------------------------------------------------------------------- 1 | # Results for 10000 trials 2 | # n time (msec) 3 | # --------------- 4 | 5 24 5 | 10 23 6 | 15 36 7 | 20 45 8 | 25 14 9 | 30 9 10 | 35 12 11 | 40 13 12 | 45 13 13 | 50 16 14 | 55 21 15 | 60 20 16 | 65 22 17 | 70 29 18 | 75 25 19 | 80 28 20 | 85 34 21 | 90 35 22 | 95 40 23 | 100 36 24 | 105 44 25 | 110 41 26 | 115 45 27 | 120 47 28 | 125 48 29 | 130 55 30 | 135 53 31 | 140 58 32 | 145 63 33 | 150 60 34 | 155 64 35 | 160 63 36 | 165 73 37 | 170 74 38 | 175 70 39 | 180 74 40 | 185 73 41 | 190 76 42 | 195 89 43 | 200 85 44 | 205 86 45 | 210 91 46 | 215 97 47 | 220 95 48 | 225 95 49 | 230 96 50 | 235 100 51 | 240 99 52 | 245 110 53 | 250 116 54 | 255 108 55 | 260 108 56 | 265 111 57 | 270 117 58 | 275 126 59 | 280 115 60 | 285 125 61 | 290 125 62 | 295 124 63 | 300 138 64 | -------------------------------------------------------------------------------- /lab/lab12/quick.dat: -------------------------------------------------------------------------------- 1 | # Results for 10000 trials 2 | # n time (msec) 3 | # --------------- 4 | 5 24 5 | 10 2 6 | 15 3 7 | 20 5 8 | 25 6 9 | 30 4 10 | 35 4 11 | 40 5 12 | 45 8 13 | 50 7 14 | 55 8 15 | 60 9 16 | 65 9 17 | 70 11 18 | 75 12 19 | 80 12 20 | 85 13 21 | 90 14 22 | 95 16 23 | 100 16 24 | 105 16 25 | 110 18 26 | 115 18 27 | 120 22 28 | 125 20 29 | 130 20 30 | 135 22 31 | 140 24 32 | 145 23 33 | 150 25 34 | 155 27 35 | 160 30 36 | 165 26 37 | 170 29 38 | 175 29 39 | 180 31 40 | 185 36 41 | 190 32 42 | 195 35 43 | 200 37 44 | 205 37 45 | 210 36 46 | 215 38 47 | 220 38 48 | 225 42 49 | 230 43 50 | 235 43 51 | 240 43 52 | 245 46 53 | 250 46 54 | 255 47 55 | 260 46 56 | 265 52 57 | 270 51 58 | 275 51 59 | 280 51 60 | 285 50 61 | 290 55 62 | 295 54 63 | 300 57 64 | -------------------------------------------------------------------------------- /lab/lab12/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 12 2 | April 23-24, 2013 3 | 4 | Goal: This lab wil introduce you to several sorting algorithms and allow you 5 | to compare their running times in practice. 6 | 7 | Copy the Lab 12 directory by starting from your home directory and typing: 8 | 9 | cp -r ~cs61b/lab/lab12 . 10 | 11 | Part I: Identifying Sort Algorithms (1 point) 12 | ---------------------------------------------- 13 | To help build your intuition of how these sorting algorithms work, take a look 14 | at three algorithms in action. Run a web browser and go to the Web page 15 | 16 | http://www.cs.berkeley.edu/~jrs/61b/lab/MysterySort 17 | 18 | Each histogram shown illustrates an array of ints. The height of each bar is 19 | proportional to the integer stored at that position in the array. When you 20 | click on a histogram, an animated algorithm sorts the array. 21 | 22 | The histograms are numbered 1, 2, 3, and 4, each number corresponding to a 23 | different sorting algorithm you have seen in class. Identify each algorithm. 24 | How can you tell which is which? Which is fastest on the random data? What 25 | about the presorted data and the reverse sorted data? 26 | 27 | One of the algorithms is quicksort. Which element does it choose for the pivot 28 | in a partition? (The pivot is not randomly chosen.) How can you tell? 29 | 30 | Part II: Timing Sort Algorithms (2 points) 31 | ------------------------------------------- 32 | Part I gave you a rough idea of the relative speeds of the three sorting 33 | algorithms. For greater accuracy, we will now time several algorithms. 34 | 35 | SortPerf.java runs a sorting algorithm (chosen from a selection of several) on 36 | a randomly generated array of specified size, and outputs the data to a file. 37 | Compile and run SortPerf. 38 | 39 | javac -g SortPerf.java 40 | java SortPerf select 5 175 200 select.dat 41 | 42 | The first argument is the sorting algorithm ("select", "merge", "insert", or 43 | "quick"). The second is both the size of the smallest array to sort and the 44 | increment between array sizes. The third is the size of the largest array to 45 | sort. The fourth is the number of trials for each size of array. Because 46 | timings are easily perturbed by other processes running on the same 47 | workstation, you must run each test for a few hundred trials to get accurate 48 | timings. The last argument is the name of the file in which SortPerf reports 49 | the total running time, in milliseconds, of all trials for each array size. 50 | 51 | The sample command above runs selection sort on arrays of size 5, 10, 15, ..., 52 | 175, each 200 times, placing the timing results in the file select.dat. If you 53 | notice that the timings look a little bumpy, i.e., the running time does not 54 | appear to be strictly increasing with input size, try running SortPerf several 55 | times until you get a fairly smooth set of numbers. When SortPerf is running, 56 | be careful not to touch the mouse or keyboard, as any user input increases the 57 | running time. 58 | 59 | Now run SortPerf for the same sizes using mergesort, insertion sort, and 60 | quicksort. Save these data to different files--say, merge.dat, insert.dat, and 61 | quick.dat. To make this easier, we have also provided a file called runrace, 62 | which you can execute to run all four sorting algorithms. Read runrace to see 63 | how it works. 64 | 65 | Use the program "gnuplot" to plot the timing results. At the prompt in an 66 | xterm (not emacs), type 67 | 68 | gnuplot 69 | 70 | You will see a ">" prompt. Plot the files using a command like 71 | 72 | gnuplot> plot "select.dat" with linesp 1, "merge.dat" with linesp 2, 73 | "insert.dat" with linesp 3, "quick.dat" with linesp 4 74 | 75 | [Type all this on just one line, though.] 76 | 77 | You should observe that the algorithms behave asymptotically as expected, but 78 | it is unclear which algorithm is faster for small array sizes. At what values 79 | of n do you observe cross-overs in execution time between the three sorting 80 | algorithms? To help see these cross-overs better, edit the runrace file to use 81 | the command 82 | 83 | java SortPerf 1 50 1000 .dat 84 | 85 | for each sorting algorithm. This gives a clearer picture of what happens for 86 | array sizes less than 50. Again run the script and plot the results with 87 | gnuplot. 88 | 89 | PART III: Building a Better Sort (1 point) 90 | ------------------------------------------- 91 | Based on your observations in Part II, write a sorting algorithm that works 92 | well on the random data for all sizes of n. It won't be a completely new 93 | sorting algorithm, but should combine the sorting algorithms described here in 94 | a very simple way. Implement your solution in YourSort.java. Run your 95 | algorithm from SortPerf by calling the sorting method "best". Modify runrace 96 | to generate timings for your new algorithm, and plot the results. 97 | 98 | Check-off 99 | --------- 100 | 1 point: What are sorting algorithms 1, 2, and 3 in Part I? How do you know? 101 | How is the pivot element chosen? How do you know? 102 | 3 points: Show the plotted performance of the sorting algorithms. The third 103 | point is for including your algorithm in the plot, and demonstrating 104 | that it's roughly as good as any of the others for any array size. 105 | -------------------------------------------------------------------------------- /lab/lab12/runrace: -------------------------------------------------------------------------------- 1 | #!/bin/csh 2 | 3 | java SortPerf select 5 300 10000 select.dat 4 | java SortPerf insert 5 300 10000 insert.dat 5 | java SortPerf merge 5 300 10000 merge.dat 6 | java SortPerf quick 5 300 10000 quick.dat 7 | java SortPerf best 5 300 10000 best.dat 8 | -------------------------------------------------------------------------------- /lab/lab12/select.dat: -------------------------------------------------------------------------------- 1 | # Results for 10000 trials 2 | # n time (msec) 3 | # --------------- 4 | 5 3 5 | 10 1 6 | 15 3 7 | 20 6 8 | 25 9 9 | 30 13 10 | 35 17 11 | 40 22 12 | 45 28 13 | 50 36 14 | 55 43 15 | 60 50 16 | 65 60 17 | 70 69 18 | 75 80 19 | 80 90 20 | 85 101 21 | 90 114 22 | 95 127 23 | 100 139 24 | 105 155 25 | 110 168 26 | 115 187 27 | 120 203 28 | 125 219 29 | 130 241 30 | 135 256 31 | 140 274 32 | 145 294 33 | 150 320 34 | 155 342 35 | 160 361 36 | 165 385 37 | 170 405 38 | 175 429 39 | 180 456 40 | 185 484 41 | 190 505 42 | 195 537 43 | 200 562 44 | 205 593 45 | 210 631 46 | 215 646 47 | 220 691 48 | 225 714 49 | 230 745 50 | 235 774 51 | 240 810 52 | 245 848 53 | 250 892 54 | 255 911 55 | 260 947 56 | 265 984 57 | 270 1025 58 | 275 1071 59 | 280 1101 60 | 285 1138 61 | 290 1177 62 | 295 1229 63 | 300 1262 64 | -------------------------------------------------------------------------------- /lab/lab13/list/LinkedQueue.java: -------------------------------------------------------------------------------- 1 | /* LinkedQueue.java */ 2 | 3 | package list; 4 | 5 | public class LinkedQueue implements Queue { 6 | 7 | private SListNode head; 8 | private SListNode tail; 9 | private int size; 10 | 11 | /** 12 | * LinkedQueue() constructs an empty queue. 13 | **/ 14 | public LinkedQueue() { 15 | size = 0; 16 | head = null; 17 | tail = null; 18 | } 19 | 20 | /** 21 | * size() returns the size of this Queue. 22 | * @return the size of this Queue. 23 | * Performance: runs in O(1) time. 24 | **/ 25 | public int size() { 26 | return size; 27 | } 28 | 29 | /** 30 | * isEmpty() returns true if this Queue is empty, false otherwise. 31 | * @return true if this Queue is empty, false otherwise. 32 | * Performance: runs in O(1) time. 33 | **/ 34 | public boolean isEmpty() { 35 | return size == 0; 36 | } 37 | 38 | /** 39 | * enqueue() inserts an object at the end of the Queue. 40 | * @param item the item to be enqueued. 41 | **/ 42 | public void enqueue(Object item) { 43 | if (head == null) { 44 | head = new SListNode(item); 45 | tail = head; 46 | } else { 47 | tail.next = new SListNode(item); 48 | tail = tail.next; 49 | } 50 | size++; 51 | } 52 | 53 | /** 54 | * dequeue() removes and returns the object at the front of the Queue. 55 | * @return the item dequeued. 56 | * @throws a QueueEmptyException if the Queue is empty. 57 | **/ 58 | public Object dequeue() throws QueueEmptyException { 59 | if (head == null) { 60 | throw new QueueEmptyException(); 61 | } else { 62 | Object o = head.item; 63 | head = head.next; 64 | size--; 65 | if (size == 0) { 66 | tail = null; 67 | } 68 | return o; 69 | } 70 | } 71 | 72 | /** 73 | * front() returns the object at the front of the Queue. 74 | * @return the item at the front of the Queue. 75 | * @throws a QueueEmptyException if the Queue is empty. 76 | **/ 77 | public Object front() throws QueueEmptyException { 78 | if (head == null) { 79 | throw new QueueEmptyException(); 80 | } else { 81 | return head.item; 82 | } 83 | } 84 | 85 | /** 86 | * 87 | * nth() returns the nth item in this LinkedQueue. 88 | * Items in the queue are numbered from 1. 89 | * @param n the number of the item to return. 90 | */ 91 | public Object nth(int n) { 92 | SListNode node = head; 93 | for (; n > 1; n--) { 94 | node = node.next; 95 | } 96 | return node.item; 97 | } 98 | 99 | /** 100 | * append() appends the contents of q onto the end of this LinkedQueue. 101 | * On completion, q is empty. 102 | * @param q the LinkedQueue whose contents should be appended onto this 103 | * LinkedQueue. 104 | **/ 105 | public void append(LinkedQueue q) { 106 | if (head == null) { 107 | head = q.head; 108 | } else { 109 | tail.next = q.head; 110 | } 111 | if (q.head != null) { 112 | tail = q.tail; 113 | } 114 | size = size + q.size; 115 | q.head = null; 116 | q.tail = null; 117 | q.size = 0; 118 | } 119 | 120 | /** 121 | * toString() converts this queue to a String. 122 | **/ 123 | public String toString() { 124 | String out = "[ "; 125 | try { 126 | for (int i = 0; i < size(); i++) { 127 | out = out + front() + " "; 128 | enqueue(dequeue()); 129 | } 130 | } catch (QueueEmptyException uf) { 131 | System.err.println("Error: attempt to dequeue from empty queue."); 132 | } 133 | return out + "]"; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /lab/lab13/list/Queue.java: -------------------------------------------------------------------------------- 1 | /* Queue.java */ 2 | 3 | package list; 4 | 5 | public interface Queue { 6 | 7 | /** 8 | * size() returns the size of this Queue. 9 | * @return the size of this Queue. 10 | * Performance: runs in O(1) time. 11 | **/ 12 | public int size(); 13 | 14 | /** 15 | * isEmpty() returns true if this Queue is empty, false otherwise. 16 | * @return true if this Queue is empty, false otherwise. 17 | * Performance: runs in O(1) time. 18 | **/ 19 | public boolean isEmpty(); 20 | 21 | /** 22 | * enqueue() inserts an object at the end of the Queue. 23 | * @param item the item to be enqueued. 24 | **/ 25 | public void enqueue(Object item); 26 | 27 | /** 28 | * dequeue() removes and returns the object at the front of the Queue. 29 | * @return the item dequeued. 30 | * @throws a QueueEmptyException if the Queue is empty. 31 | **/ 32 | public Object dequeue() throws QueueEmptyException; 33 | 34 | /** 35 | * front() returns the object at the front of the Queue. 36 | * @return the item at the front of the Queue. 37 | * @throws a QueueEmptyException if the Queue is empty. 38 | **/ 39 | public Object front() throws QueueEmptyException; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /lab/lab13/list/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | /* QueueEmptyException.java */ 2 | 3 | package list; 4 | 5 | public class QueueEmptyException extends Exception { 6 | 7 | public QueueEmptyException() { 8 | super(); 9 | } 10 | 11 | public QueueEmptyException(String s) { 12 | super(s); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /lab/lab13/list/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | package list; 4 | 5 | /** 6 | * SListNode is a class used internally by the SList class. An SList object 7 | * is a singly-linked list, and an SListNode is a node of a singly-linked 8 | * list. Each SListNode has two references: one to an object, and one to 9 | * the next node in the list. 10 | */ 11 | 12 | class SListNode { 13 | Object item; 14 | SListNode next; 15 | 16 | /** 17 | * SListNode() (with one parameter) constructs a list node referencing the 18 | * item "obj". 19 | */ 20 | 21 | SListNode(Object obj) { 22 | item = obj; 23 | next = null; 24 | } 25 | 26 | /** 27 | * SListNode() (with two parameters) constructs a list node referencing the 28 | * item "obj", whose next list node is to be "next". 29 | */ 30 | 31 | SListNode(Object obj, SListNode next) { 32 | item = obj; 33 | this.next = next; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /lab/lab13/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 13 2 | April 30-May 1, 2013 3 | 4 | Goal: to give you experience with an unweighted directed graph represented by 5 | an adjacency matrix. 6 | 7 | Please make sure you have a partner for this lab. 8 | 9 | Copy the Lab 13 directory by doing the following, starting from your home 10 | directory. 11 | 12 | cp -r ~cs61b/lab/lab13 . 13 | 14 | The file UDGraph.java contains code for a class UDGraph, an unweighted directed 15 | graph represented by a boolean adjacency matrix adjMatrix[][]. For simplicity, 16 | vertices are denoted by ints in the range 0...n - 1, where n is the number of 17 | vertices. Each entry adjMatrix[i][j] is true if (i, j) is an edge of the 18 | graph; false otherwise. 19 | 20 | The UDGraph class currently has the following methods. 21 | 22 | UDGraph(int n) Constructs a new UDGraph with n vertices and no edges. 23 | getNumVertices() Returns the number of vertices in the UDGraph. 24 | getNumEdges() Returns the number of edges in the UDGraph. 25 | validVertex(int v) True if v is a valid vertex number (0...n - 1). 26 | hasEdge(int o, int d) True if the graph contains edge (o, d). 27 | addEdge(int o, int d) Adds edge (o, d) to the graph (if not already there). 28 | removeEdge(int o, int d) Removes edge (o, d) from the graph (if there). 29 | toString() Returns a String representation of the UDGraph. 30 | 31 | You are welcome to use these methods and/or manipulate the fields "adjMatrix", 32 | "vertices", and "edges" directly, as you prefer. The addEdge and removeEdge 33 | methods have the advantage that they update the "edges" count correctly (always 34 | checking whether the edge is present in the graph before the update). 35 | 36 | Part I: Finding vertices reachable by length-2 paths (2 points) 37 | ---------------------------------------------------------------- 38 | Fill in the body of the method UDGraph.length2Paths(). This method constructs 39 | and returns a UDGraph with the same number of vertices as "this" UDGraph. The 40 | new graph contains the edge (v, w) if and only if there is a path of length 2 41 | from v to w in "this" graph--in other words, there is some vertex u such that 42 | (v, u) and (u, w) are both edges of "this" graph. 43 | 44 | Note that a length-2 path can start and end at the same vertex: if "this" 45 | graph contains the edges (v, w) and (w, v), then it contains a length-2 path 46 | from v to itself, and the new graph should contain the self-edge 47 | (v, v). Moreover, if "this" graph contains the self-edge (v, v), then 48 | is a length-2 path, so the new graph should contain (v, v). 49 | 50 | If a vertex w can be reached from a vertex v by a length-1 path (one edge) in 51 | "this" graph but _not_ by a length-2 path, the new graph should _not_ contain 52 | (v, w). 53 | 54 | Try to think of the fastest, simplest code for length2Paths(). It's possible 55 | to do it with a relatively simple triply-nested loop. You will have to explain 56 | your algorithm to your TA. If your TA thinks your algorithm is too slow, 57 | you'll be asked to do it again. 58 | 59 | Your solution should not change "this" graph. 60 | 61 | Part II: Finding vertices reachable by length-k paths (2 points) 62 | ---------------------------------------------------------------- 63 | Fill in the body of the method UDGraph.paths(int length). This method creates 64 | and returns a UDGraph with the same number of vertices as "this" UDGraph. The 65 | new graph contains the edge (v, w) if and only if there is a path of length 66 | "length" (the parameter) from v to w in "this" graph. Your method should work 67 | for any "length" of 2 or greater. 68 | 69 | Note that a length-k path is permitted to use an edge multiple times. For 70 | example, is a valid length-5 path. 71 | 72 | Hint: First calculate all the paths of length (k - 1). Once you know these, 73 | it's straightforward to compute all the paths of length k in a manner similar 74 | to what you did for Part I. 75 | 76 | There is test code in UDGraph.main() for both Parts I and II. 77 | 78 | Check-off 79 | --------- 80 | 2 points: Show your TA your code for length2Paths() and explain how you did 81 | it. Run the test code to show that length2Paths() works. 82 | 2 points: Run the test code to show that paths() works. 83 | -------------------------------------------------------------------------------- /lab/lab2/Fraction.java: -------------------------------------------------------------------------------- 1 | /* Fraction.java */ 2 | 3 | import java.io.*; 4 | 5 | /** The Fraction class implements nonnegative fractions (rational numbers). 6 | */ 7 | class Fraction { 8 | 9 | /* private fields within a Fraction. */ 10 | private static int numberOfFractions = 0; 11 | 12 | private int numerator; 13 | private int denominator; 14 | 15 | /** Constructs a Fraction n/d. 16 | * @param n is the numerator. Must be nonnegative. 17 | * @param d is the denominator. Must be positive. 18 | */ 19 | public Fraction(int n, int d) { 20 | if (n < 0) { 21 | System.out.println("Fatal error: Negative numerator."); 22 | System.exit(0); 23 | } 24 | if (d < 1) { 25 | System.out.println("Fatal error: Nonpositive denominator."); 26 | System.exit(0); 27 | } 28 | numberOfFractions++; 29 | numerator = n; 30 | denominator = d; 31 | } 32 | 33 | /** Constructs a Fraction n/1. 34 | * @param n is the numerator. Must be nonnegative. 35 | */ 36 | public Fraction(int n) { 37 | this(n, 1); 38 | } 39 | 40 | /** Constructs a Fraction 0/1. 41 | */ 42 | public Fraction() { 43 | this(0,1); 44 | } 45 | 46 | /** Copies the Fraction "original". 47 | */ 48 | public Fraction(Fraction original) { 49 | this(original.numerator,original.denominator); 50 | } 51 | 52 | /** Converts this Fraction to a string format: "numerator/denominator." 53 | * Fractions should be printed in reduced form (part of your assignment is 54 | * to make this true). 55 | * @return a String representation of this Fraction. 56 | */ 57 | public String toString() { 58 | int thisGcd = gcd(numerator, denominator); 59 | 60 | return (numerator / thisGcd + "/" + denominator / thisGcd); 61 | } 62 | 63 | /** Return the sum of two fractions. 64 | * @param f2 is the Fraction to be added. 65 | * @return the result of adding f2 to this Fraction. 66 | */ 67 | public Fraction add(Fraction f2) { 68 | Fraction r = new Fraction((numerator * f2.denominator) + 69 | (f2.numerator * denominator), 70 | denominator * f2.denominator); 71 | return r; 72 | } 73 | 74 | /** Replaces this Fraction's numerator with a new value. 75 | * @param numerator is the new numerator. Must be nonnegative. 76 | */ 77 | public void changeNumerator(int numerator) { // DO NOT CHANGE THIS SIGNATURE! 78 | // Fix the bug that prevents this method from working correctly. 79 | if (numerator < 0) { 80 | System.out.println("Fatal error: Negative numerator."); 81 | System.exit(0); 82 | } 83 | this.numerator = numerator; 84 | } 85 | 86 | /** Returns the number of Fraction objects in existence. 87 | * @return the number of Fraction objects in existence. 88 | */ 89 | public int fracs() { // DO NOT CHANGE THIS SIGNATURE! 90 | // Fix the bug that prevents this method from working correctly. 91 | return numberOfFractions; 92 | } 93 | 94 | /** Computes the greatest common divisor (gcd) of the two inputs. 95 | * @param x must be nonnegative 96 | * @param y must be nonnegative 97 | * @return the gcd of x and y 98 | */ 99 | static private int gcd(int x, int y) { 100 | /* Replace the following line with your solution. */ 101 | if(y==0) 102 | return x; 103 | else 104 | return gcd(y, x%y); 105 | } 106 | 107 | /** Put the Fraction class through some tests. 108 | * @param argv is not used. 109 | */ 110 | public static void main(String[] argv) { 111 | 112 | /* Test all four contructors and toString. */ 113 | Fraction f0 = new Fraction(); 114 | Fraction f1 = new Fraction(3); 115 | Fraction f2 = new Fraction(12, 20); 116 | Fraction f3 = new Fraction(f2); 117 | 118 | System.out.println("\nTesting constructors and toString():"); 119 | System.out.println("The fraction f0 is " + f0.toString()); 120 | System.out.println("The fraction f1 is " + f1); // toString is implicit. 121 | System.out.println("The fraction f2 is " + f2); 122 | System.out.println("The fraction f3 is " + f3 + ", which should equal f2"); 123 | 124 | /* Test the add method. */ 125 | System.out.println("\nTesting add:"); 126 | 127 | Fraction sumOfTwo = f1.add(f2); // Sum of f1 and f2. 128 | Fraction sumOfThree = f0.add(f1.add(f2)); // Sum of f0, f1, and f2. 129 | 130 | System.out.println("The sum of " + f1 + " and " + f2 + " is " + sumOfTwo); 131 | System.out.println("The sum of " + f0 + ", " + f1 + " and " + f2 + " is " + 132 | sumOfThree); 133 | 134 | /* Test the methods used in Part III. */ 135 | System.out.println("\nTesting changeNumerator and fracs:"); 136 | 137 | f3.changeNumerator(7); 138 | System.out.println("Now f3 is " + f3 + ", which should be 7/20"); 139 | System.out.println("The total number of Fraction objects is " + 140 | f3.fracs()); 141 | 142 | /* Test gcd function (static method). */ 143 | System.out.println("\nTesting gcd:"); 144 | System.out.println("The gcd of 2 and 10 is: " + gcd(2, 10)); 145 | System.out.println("The gcd of 15 and 5 is: " + gcd(15, 5)); 146 | System.out.println("The gcd of 24 and 18 is: " + gcd(24, 18)); 147 | System.out.println("The gcd of 10 and 10 is: " + gcd(10, 10)); 148 | System.out.println("The gcd of 21 and 400 is: " + gcd(21, 400)); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /lab/lab3/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | /** 4 | * SListNode is a class used internally by the SList class. An SList object 5 | * is a singly-linked list, and an SListNode is a node of a singly-linked 6 | * list. Each SListNode has two references: one to an object, and one to 7 | * the next node in the list. 8 | * 9 | * @author Kathy Yelick and Jonathan Shewchuk 10 | */ 11 | 12 | class SListNode { 13 | Object item; 14 | SListNode next; 15 | 16 | /** 17 | * SListNode() (with one parameter) constructs a list node referencing the 18 | * item "obj". 19 | */ 20 | 21 | SListNode(Object obj) { 22 | item = obj; 23 | next = null; 24 | } 25 | 26 | /** 27 | * SListNode() (with two parameters) constructs a list node referencing the 28 | * item "obj", whose next list node is to be "next". 29 | */ 30 | 31 | SListNode(Object obj, SListNode next) { 32 | item = obj; 33 | this.next = next; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /lab/lab3/TestHelper.java: -------------------------------------------------------------------------------- 1 | /* TestHelper.java */ 2 | 3 | /** 4 | * This class is based on code from Arnow/Dexter/Weiss. Its verify() method 5 | * exits with an error message if an invariant fails to hold true. 6 | * 7 | * The purpose of this class is to provide a shorthand for writing and testing 8 | * invariants in any program. 9 | **/ 10 | 11 | public class TestHelper { 12 | 13 | /** 14 | * verify() checks an invariant and prints an error message if it fails. 15 | * If invariant is true, this method does nothing. If invariant is false, 16 | * the message is printed, followed by a dump of the program call stack. 17 | * 18 | * @param invariant the condition to be verified 19 | * @param message the error message to be printed if the invariant fails to 20 | * hold true. 21 | **/ 22 | 23 | static void verify(boolean invariant, String message) { 24 | if (!invariant) { 25 | System.out.println("*** ERROR: " + message); 26 | Thread.dumpStack(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /lab/lab3/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 3 2 | February 12-13, 2013 3 | 4 | Goal: This lab will give you practice with linked lists. 5 | 6 | Copy the Lab 3 directory by starting from your home directory and typing: 7 | cp -r ~cs61b/lab/lab3 . 8 | cd lab3 9 | 10 | Getting Started 11 | --------------- 12 | Please make sure you have a partner for this lab. 13 | 14 | The files in the lab3 directory contain classes to implement a singly-linked 15 | list. The classes include an encapsulated SList and the underlying SListNode 16 | class (which is akin to a Scheme cons cell). Compile SList.java (with 17 | "javac -g SList.java".) Run the resulting test code with 18 | 19 | java SList 20 | 21 | The main() method of SList includes test code, which can be used to help debug 22 | the list code before SLists are used in other programs. 23 | 24 | Items in our SLists are indexed starting from 1, unlike Java arrays. 25 | 26 | Part I: Using SLists (1 point) 27 | ------------------------------- 28 | In the main() method, construct a list that looks like: 29 | [ 6 9 12 ] 30 | and print the resulting list. 31 | 32 | Add more lines to change this list to: 33 | [ 3 6 9 12 15 ] 34 | and print the resulting list. 35 | 36 | Part II: Adding to the End of a SList (3 points) 37 | -------------------------------------------------- 38 | A method called insertEnd() exists, but it runs in linear time, because every 39 | time it is called, it walks down the list to find the end. Without changing 40 | the meaning of this method or any other, modify the representation of a SList 41 | and whatever methods are necessary to make insertEnd() run in constant time. 42 | Your SList class will need to continually maintain a record of the last (tail) 43 | SListNode in an SList, and all SList's methods will have to ensure that this 44 | record stays current. 45 | 46 | Check-off 47 | --------- 48 | Show your TA or Lab Assistant your main() and insertEnd() methods and run the 49 | program. 50 | 51 | 1 point: Show your main() method, and show that it is printing the proper 52 | output for Part I. 53 | 3 points: Show your insertEnd() method, and explain how you got it to work in 54 | constant time. Show that your program still prints the right 55 | output. Which other methods had to be modified? 56 | -------------------------------------------------------------------------------- /lab/lab4/DListNode1.java: -------------------------------------------------------------------------------- 1 | /* DListNode1.java */ 2 | 3 | /** 4 | * A DListNode1 is a node in a DList1 (doubly-linked list). 5 | */ 6 | 7 | public class DListNode1 { 8 | 9 | /** 10 | * item references the item stored in the current node. 11 | * prev references the previous node in the DList. 12 | * next references the next node in the DList. 13 | * 14 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 15 | */ 16 | 17 | public int item; 18 | public DListNode1 prev; 19 | public DListNode1 next; 20 | 21 | /** 22 | * DListNode1() constructor. 23 | */ 24 | DListNode1() { 25 | item = 0; 26 | prev = null; 27 | next = null; 28 | } 29 | 30 | DListNode1(int i) { 31 | item = i; 32 | prev = null; 33 | next = null; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /lab/lab4/DListNode2.java: -------------------------------------------------------------------------------- 1 | /* DListNode2.java */ 2 | 3 | /** 4 | * A DListNode2 is a node in a DList2 (doubly-linked list). 5 | */ 6 | 7 | public class DListNode2 { 8 | 9 | /** 10 | * item references the item stored in the current node. 11 | * prev references the previous node in the DList. 12 | * next references the next node in the DList. 13 | * 14 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 15 | */ 16 | 17 | public int item; 18 | public DListNode2 prev; 19 | public DListNode2 next; 20 | 21 | /** 22 | * DListNode2() constructor. 23 | */ 24 | DListNode2() { 25 | item = 0; 26 | prev = null; 27 | next = null; 28 | } 29 | 30 | DListNode2(int i) { 31 | item = i; 32 | prev = null; 33 | next = null; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /lab/lab4/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 4 2 | February 19-20, 2013 3 | 4 | Goal: This lab will demonstrate how a sentinel node can simplify a 5 | doubly-linked list implementation. 6 | 7 | Copy the Lab 4 directory by starting from your home directory and typing: 8 | 9 | cp -r ~cs61b/lab/lab4 . 10 | cd lab4 11 | 12 | Getting Started 13 | --------------- 14 | Please make sure you have a partner for this lab. 15 | 16 | The files in the lab4 directory contain classes for two different types of 17 | doubly-linked list. The DList1 class does not use a sentinel, whereas the 18 | DList2 class does. The DList1 class is not circularly linked, but the DList2 19 | class is (through the sentinel). Compile DList1.java and DList2.java (using 20 | "javac -g DList1.java DList2.java".) 21 | 22 | Your task is to implement two insertFront() and two removeFront() methods--one 23 | of each for each list class. insertFront() and removeFront() insert or remove 24 | an item at the beginning of a list. Make sure your implementations work for 25 | empty lists, one-node lists, and larger lists. 26 | 27 | The main() methods of DList1 and DList2 include test code, which you can run 28 | with "java DList1" and "java DList2". 29 | 30 | Part I: insertFront in DList1 (1 point) 31 | ---------------------------------------- 32 | Write a method called DList1.insertFront() that inserts an int at the front of 33 | "this" DList1. 34 | 35 | Part II: removeFront in DList1 (1 point) 36 | ----------------------------------------- 37 | Write a method called DList1.removeFront() that removes the first item (and 38 | node) from "this" DList1. 39 | 40 | Part III: insertFront in DList2 (1 point) 41 | ------------------------------------------ 42 | Write a method called DList2.insertFront() that inserts an int at the front of 43 | "this" DList2. Your code should NOT use any "if" statements or conditionals. 44 | 45 | Part IV: removeFront in DList2 (2 points) 46 | ------------------------------------------ 47 | Write a method called DList2.removeFront() that removes the first item (and 48 | non-sentinel node) from "this" DList2. Your code should not require separate 49 | branches for the one-node case and the more-than-one-node case. (You will 50 | need one "if", to handle the zero-node case.) 51 | 52 | Check-off 53 | --------- 54 | Run the DList1 and DList2 test code for your TA or Lab Assistant. 55 | 56 | 1 point: DList1.insertFront(). 57 | 1 point: DList1.removeFront(). 58 | 1 point: DList2.insertFront(). 59 | 1 point: DList2.removeFront(). 60 | -------------------------------------------------------------------------------- /lab/lab4/things2remember.txt: -------------------------------------------------------------------------------- 1 | 1. Double link list with sentinel's code looks cleaner: 2 | for insert: no need to deal with empty list case (never empty) 3 | for remove: no need to take care of size 1, otherwise will have null 4 | pointer violation 5 | 6 | 2. Double link list is trickier to implement: 7 | when insert or remove, draw a general case, NOT boundary case; a.k.a. for 8 | insert (size=1, excluding sentinel), while for delete (size =2, excluding 9 | sentinel). It will work for boundary case like a charm 10 | 11 | It will be important to know which link to break, the rule is not to lose 12 | node when breaking! 13 | 14 | 3. Discussion for size=0 when remove is always needed 15 | -------------------------------------------------------------------------------- /lab/lab5/answers.txt: -------------------------------------------------------------------------------- 1 | Part I: Assignments and Casting (1 point) 2 | ------------------------------------------ 3 | Let Y be a subclass of X, and let y and x be variables of classes Y and X 4 | respectively. From lecture, you know that the assignment "x = y" is valid, but 5 | the assignment "y = (Y) x" requires a cast to compile, and will cause a 6 | run-time error if x references an object that isn't a Y. 7 | 8 | What about arrays of objects? Suppose xa is an array of X's, and ya is an 9 | array of Y's. 10 | (a) At compile-time, can we assign xa to ya, and vice versa? When is a cast 11 | required? 12 | ********************************************* 13 | xa=ya; is OK (all y is x) 14 | ya=xa; is not OK, needs to cast (ya=(Y[])xa); 15 | (b) At run-time, if ya references an array of Y's, can we assign it to xa? 16 | Can we then assign it back from xa to ya? 17 | ********************************************* 18 | Yes, at run-time we can do xa=ya; 19 | Yes, we can assign it back as long as we cast; 20 | (c) If xa references an array of X's (that are not Y's), can we assign it to 21 | ya? Can we then assign it back from ya to xa? Does it make a difference 22 | if the array of type X[] references objects that are all of class Y? Why 23 | do you think this is the case? 24 | ********************************************* 25 | ya=(Y[])xa; will works without compile time error 26 | but it will have ClassCastException if we want to access ya[*]; 27 | 28 | there's no compile error to assign it back; 29 | but there's is run-time error; 30 | 31 | there's no difference, because all y are x; 32 | 33 | Part II: Conflicting Declarations (1 point) 34 | -------------------------------------------- 35 | Suppose a subclass inherits a method implementation from a superclass, and 36 | implements a Java interface (that's the "interface" keyword) that contains 37 | a method with the same name and prototype. 38 | 39 | (a) Will Java compile the result? 40 | ********************************************* 41 | Java will compile this result 42 | (b) What if the method declaration in the interface has a different return 43 | type? 44 | ********************************************* 45 | Java won't compile this result, for incompatible return type; 46 | Because in a class, you can not have 2 function with the same name and 47 | parameters but with different return type! 48 | (c) What if the method declaration in the interface has the same return type, 49 | but a signature with a different parameter type? 50 | ********************************************* 51 | It depends, as long as you implement the method defined in java interface, 52 | there's no problem whether or not you override method in superclass; but if 53 | you leave method in java interface incomplete, it will issue compile time 54 | error; 55 | (d) What if the method declaration in the interface has the same return type, 56 | and the same number of parameters and parameter types, but those 57 | parameters have different names? 58 | ********************************************* 59 | This is OK, will get compiled 60 | 61 | Part III: More Conflicting Declarations (1 point) 62 | -------------------------------------------------- 63 | Suppose a subclass inherits a "public static final" constant from a superclass, 64 | and implements a Java interface that contains a "public static final" constant 65 | with the same name. 66 | 67 | (a) Will Java compile the result? Does it make any difference whether the 68 | constant in the superclass and the constant in the interface have the 69 | same value? 70 | ********************************************* 71 | It will compile regardless of whether the values are same or not; 72 | (b) Write a main() method in the subclass that accesses the constant using the 73 | same name used in the superclass and the Java interface. Will Java 74 | compile the result? Does it make any difference whether the constant in 75 | the superclass and the constant in the interface have the same value? 76 | ********************************************* 77 | Java won't compile whether or not they are the same value 78 | (c) Figure out how to modify your main() method so that it accesses and prints 79 | one of the two conflicting values. (Look to Lecture 9 for clues.) Make 80 | sure your code compiles and runs without errors. 81 | ********************************************* 82 | Need to specify the full name, including interface or superclass's name 83 | 84 | Part IV: Method Overriding (1 point) 85 | ------------------------------------- 86 | Consider a subclass that has a method that overrides a method with the same 87 | prototype in its superclass. 88 | 89 | (a) Define a variable whose static type is the subclass and which references 90 | an object of the subclass. If we cast the variable to the superclass type 91 | before calling the overridden method 92 | 93 | ((Superclass) subclassvariable).method(); 94 | 95 | does Java call the superclass method or the subclass method? 96 | ********************************************* 97 | It will call the subclass method, this is equivalant to: 98 | Superclass sup = (Superclass)subclassvariable; 99 | sup.method(); 100 | (b) Define a variable whose static type is the superclass and which references 101 | an object of the superclass (but not the subclass). If we cast the 102 | variable to the subclass type before calling the method, does Java call 103 | the superclass method or the subclass method? 104 | ********************************************* 105 | Java will compile this but will result in run time error of class cast 106 | exception 107 | (c) Suppose you have an object whose class is the subclass. Can you figure 108 | out a way to call the superclass method on that object without having to 109 | go through the subclass method of the same name? 110 | ********************************************* 111 | Used google! 112 | This is not possible; ortherwise, there's no encapsulation 113 | 114 | -------------------------------------------------------------------------------- /lab/lab5/q1/X.java: -------------------------------------------------------------------------------- 1 | public class X { 2 | public int x; 3 | public X() { 4 | x=5; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /lab/lab5/q1/Y.java: -------------------------------------------------------------------------------- 1 | public class Y extends X { 2 | public int y; 3 | public Y() { 4 | super(); 5 | y=55; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /lab/lab5/q1/test.java: -------------------------------------------------------------------------------- 1 | // test code for lab5 2 | // Written by Ryan (Weiran) Zhao 3 | // Thu,Jun 13th 2013 02:45:10 PM EDT 4 | import java.io.*; 5 | 6 | public class test { 7 | public static void main(String[] argv) { 8 | // for part I 9 | X[] xa= new X[10]; 10 | Y[] ya= new Y[10]; 11 | for(int i=0;i<10;i++) 12 | { 13 | xa[i]=new X(); 14 | ya[i]=new Y(); 15 | } 16 | xa[0] = ya[0]; 17 | System.out.println(xa[0].x); 18 | //System.out.println(ya[0].y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /lab/lab5/q2/jInterface.java: -------------------------------------------------------------------------------- 1 | public interface jInterface { 2 | public void test(int a); 3 | } 4 | 5 | -------------------------------------------------------------------------------- /lab/lab5/q2/jSubclass.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class jSubclass extends jSuperclass implements jInterface { 3 | public void test(int a) { 4 | System.out.println("in subclass"); 5 | } 6 | 7 | 8 | public void test(double a, int b) { 9 | return; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /lab/lab5/q2/jSuperclass.java: -------------------------------------------------------------------------------- 1 | public class jSuperclass { 2 | public void test(double a, int b) { 3 | return ; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /lab/lab5/q3/jInterface.java: -------------------------------------------------------------------------------- 1 | public interface jInterface { 2 | public static final int val = 2; 3 | } 4 | 5 | -------------------------------------------------------------------------------- /lab/lab5/q3/jSubclass.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class jSubclass extends jSuperclass implements jInterface { 3 | public static void main(String[] argv) { 4 | System.out.println(jSuperclass.val); 5 | System.out.println(jInterface.val); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /lab/lab5/q3/jSuperclass.java: -------------------------------------------------------------------------------- 1 | public class jSuperclass { 2 | public static final int val=1; 3 | } 4 | -------------------------------------------------------------------------------- /lab/lab5/q4/jSubclass.java: -------------------------------------------------------------------------------- 1 | public class jSubclass extends jSuperclass { 2 | public void print() { 3 | System.out.println("in subclass"); 4 | } 5 | public static void main(String[] argv) { 6 | jSuperclass sup = new jSubclass(); 7 | ((jSubclass)sup).print(); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /lab/lab5/q4/jSuperclass.java: -------------------------------------------------------------------------------- 1 | public class jSuperclass { 2 | public void print() { 3 | System.out.println("In superclass"); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /lab/lab5/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 5 2 | February 26-27, 2013 3 | 4 | Goal: This lab will give you practice writing code that uses inheritance and 5 | Java interfaces. 6 | 7 | Please make sure you have a partner for this lab. 8 | 9 | No code is provided with this lab. Write code to experimentally resolve the 10 | following questions about Java. You will need to show your code to the TA or 11 | lab assistant. 12 | 13 | Part I: Assignments and Casting (1 point) 14 | ------------------------------------------ 15 | Let Y be a subclass of X, and let y and x be variables of classes Y and X 16 | respectively. From lecture, you know that the assignment "x = y" is valid, but 17 | the assignment "y = (Y) x" requires a cast to compile, and will cause a 18 | run-time error if x references an object that isn't a Y. 19 | 20 | What about arrays of objects? Suppose xa is an array of X's, and ya is an 21 | array of Y's. 22 | 23 | (a) At compile-time, can we assign xa to ya, and vice versa? When is a cast 24 | required? 25 | (b) At run-time, if ya references an array of Y's, can we assign it to xa? 26 | Can we then assign it back from xa to ya? 27 | (c) If xa references an array of X's (that are not Y's), can we assign it to 28 | ya? Can we then assign it back from ya to xa? Does it make a difference 29 | if the array of type X[] references objects that are all of class Y? Why 30 | do you think this is the case? 31 | 32 | Part II: Conflicting Declarations (1 point) 33 | -------------------------------------------- 34 | Suppose a subclass inherits a method implementation from a superclass, and 35 | implements a Java interface (that's the "interface" keyword) that contains 36 | a method with the same name and prototype. 37 | 38 | (a) Will Java compile the result? 39 | (b) What if the method declaration in the interface has a different return 40 | type? 41 | (c) What if the method declaration in the interface has the same return type, 42 | but a signature with a different parameter type? 43 | (d) What if the method declaration in the interface has the same return type, 44 | and the same number of parameters and parameter types, but those 45 | parameters have different names? 46 | 47 | Part III: More Conflicting Declarations (1 point) 48 | -------------------------------------------------- 49 | Suppose a subclass inherits a "public static final" constant from a superclass, 50 | and implements a Java interface that contains a "public static final" constant 51 | with the same name. 52 | 53 | (a) Will Java compile the result? Does it make any difference whether the 54 | constant in the superclass and the constant in the interface have the 55 | same value? 56 | (b) Write a main() method in the subclass that accesses the constant using the 57 | same name used in the superclass and the Java interface. Will Java 58 | compile the result? Does it make any difference whether the constant in 59 | the superclass and the constant in the interface have the same value? 60 | (c) Figure out how to modify your main() method so that it accesses and prints 61 | one of the two conflicting values. (Look to Lecture 9 for clues.) Make 62 | sure your code compiles and runs without errors. 63 | 64 | Part IV: Method Overriding (1 point) 65 | ------------------------------------- 66 | Consider a subclass that has a method that overrides a method with the same 67 | prototype in its superclass. 68 | 69 | (a) Define a variable whose static type is the subclass and which references 70 | an object of the subclass. If we cast the variable to the superclass type 71 | before calling the overridden method 72 | 73 | ((Superclass) subclassvariable).method(); 74 | 75 | does Java call the superclass method or the subclass method? 76 | (b) Define a variable whose static type is the superclass and which references 77 | an object of the superclass (but not the subclass). If we cast the 78 | variable to the subclass type before calling the method, does Java call 79 | the superclass method or the subclass method? 80 | (c) Suppose you have an object whose class is the subclass. Can you figure 81 | out a way to call the superclass method on that object without having to 82 | go through the subclass method of the same name? 83 | 84 | Check-off 85 | --------- 86 | Show your TA or Lab Assistant your code and, in some cases, its output. 87 | 88 | 1 point: Give your answers for Part I. Show the code with which you answered 89 | Part I (c). 90 | 1 point: Give your answers for Part II. 91 | 1 point: Give your answers for Part III. Show _and_run_ the code with which 92 | you answered Part III (c). 93 | 1 point: Give your answers for Part IV. Show the code with which you 94 | answered Part IV (c). 95 | 96 | Because this lab is on the long side, students who complete the first three 97 | parts but don't have time to complete the fourth part will get 4 points if they 98 | promise to figure out the last part later. 99 | -------------------------------------------------------------------------------- /lab/lab6/AccountData.java: -------------------------------------------------------------------------------- 1 | /* AccountData.java */ 2 | 3 | import sortedlist.*; 4 | 5 | /** 6 | * Implements a customer's account profile for the virtual teller machine. 7 | **/ 8 | public class AccountData implements Keyable { 9 | private String name; // Customer name. 10 | private int balance; // Starting balance. 11 | private int number; // Account number. 12 | 13 | /** 14 | * Constructs a new account for customer "newName" with acount number "num" 15 | * and a $0 starting balance. 16 | **/ 17 | public AccountData(String newName, int num) { 18 | name = newName; 19 | number = num; 20 | balance = 0; 21 | } 22 | 23 | /** 24 | * lessThan() returns true if this account's number is less than the 25 | * argument's account number. 26 | **/ 27 | public boolean lessThan(Keyable x) { 28 | return number < ((AccountData) x).number; 29 | } 30 | 31 | /** 32 | * getOwner() returns the name of this account's owner. 33 | **/ 34 | public String getOwner() { 35 | return name; 36 | } 37 | 38 | /** 39 | * toString() returns a String version of this account's number. 40 | **/ 41 | public String toString() { 42 | return "" + number; 43 | } 44 | 45 | 46 | /** 47 | * getBalance() returns the balance of this account. 48 | **/ 49 | public int getBalance() { 50 | return balance; 51 | } 52 | 53 | /** 54 | * withdraw() reduces the balance by the withdrawal amount "amt". 55 | **/ 56 | public void withdraw(int amt) throws BadTransactionException { 57 | if (amt < 0) { 58 | throw new BadTransactionException(" Invalid input value: "+amt); 59 | } else if (amt <= balance) { 60 | balance = balance - amt; 61 | } else { 62 | throw new BadTransactionException("Insufficient funds: " + amt); 63 | } 64 | } 65 | 66 | /** 67 | * deposit() deposits "amt" dollars into this account. 68 | **/ 69 | public void deposit(int amt) throws BadTransactionException { 70 | if (amt >= 0) { 71 | balance = balance + amt; 72 | } else { 73 | throw new BadTransactionException("Tried to deposit less than 0: " + amt); 74 | } 75 | } 76 | 77 | /** 78 | * getNumber() returns this account's number. 79 | **/ 80 | public int getNumber() { 81 | return number; 82 | } 83 | 84 | /** 85 | * getKey() returns this account's account number as the key to use for 86 | * sorting and comparison. 87 | **/ 88 | public int getKey() { 89 | return number; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /lab/lab6/BadAccountException.java: -------------------------------------------------------------------------------- 1 | /* BadAccountException.java */ 2 | 3 | /** 4 | * Implements an exception that should be thrown for nonexistent accounts. 5 | **/ 6 | public class BadAccountException extends Exception { 7 | 8 | public int accountNumber; // The invalid account number. 9 | 10 | /** 11 | * Creates an exception object for nonexistent account "badAcctNumber". 12 | **/ 13 | public BadAccountException(int badAcctNumber) { 14 | super("Invalid account number: " + badAcctNumber); 15 | 16 | accountNumber = badAcctNumber; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /lab/lab6/BadTransactionException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * For bad transaction input, such as negative money to deposit 3 | */ 4 | 5 | public class BadTransactionException extends Exception{ 6 | public BadTransactionException(String problem) { 7 | super(problem); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /lab/lab6/BankApp.java: -------------------------------------------------------------------------------- 1 | /* BankApp.java */ 2 | 3 | import java.io.*; 4 | import sortedlist.*; 5 | 6 | /** 7 | * A bank application. Allows a user to create and manipulate 8 | * banking accounts, using an ATM that is shared by all banking applications. 9 | */ 10 | public class BankApp { 11 | private BufferedReader bReader = 12 | new BufferedReader(new InputStreamReader(System.in)); 13 | private VirtualTeller ATM = new VirtualTeller(); 14 | 15 | public static void main(String[] args) { 16 | greeting(); 17 | usage(); 18 | BankApp bankApp = new BankApp(); 19 | String command=null; 20 | try { 21 | command = bankApp.readLine("--> "); 22 | } catch(IOException e) { 23 | System.err.println(e); 24 | } 25 | while (!command.equals("quit")) { 26 | try { 27 | if (command.equals("open")) { 28 | bankApp.open(); 29 | } else if (command.equals("deposit")) { 30 | bankApp.doDeposit(); 31 | } else if (command.equals("withdraw")) { 32 | bankApp.doWithdraw(); 33 | } else if (command.equals("inquire")) { 34 | bankApp.doInquire(); 35 | } else { 36 | System.err.println("Invalid command: " + command); 37 | usage(); 38 | } 39 | } catch(IOException e) { 40 | System.err.println(e); 41 | } 42 | // for problem II 43 | catch(BadAccountException bad) { 44 | System.err.println(bad); 45 | } 46 | // for problem III 47 | catch(BadTransactionException bad) { 48 | System.err.println(bad); 49 | } 50 | try { 51 | command = bankApp.readLine("--> "); 52 | } catch (IOException e) { 53 | System.err.println(e); 54 | } 55 | } 56 | } 57 | 58 | public BankApp() { 59 | // The field declarations have initializers; 60 | // no initialization is needed here. 61 | } 62 | 63 | /** 64 | * open() prompts the user to create an account and creates one in the ATM. 65 | * @exception IOException if there are problems reading user input. 66 | */ 67 | private void open() throws IOException { 68 | String name = readLine("Enter name: "); 69 | int newNum = ATM.openAccount(name); 70 | 71 | System.out.println(name + ", your new account number is: " + newNum); 72 | System.out.println("Thanks for opening an account with us!"); 73 | } 74 | 75 | /** 76 | * doDeposit() prompts the user for an account number and tries to perform a 77 | * deposit transaction on that account. 78 | * @exception IOException if there are problems reading user input. 79 | */ 80 | private void doDeposit() throws IOException, BadAccountException, BadTransactionException { 81 | // Get account number. 82 | int acctNumber = readInt("Enter account number: "); 83 | int amount = readInt("Enter amount to deposit: "); 84 | 85 | ATM.deposit(acctNumber, amount); 86 | System.out.println("New balance for #" + acctNumber + " is " + 87 | ATM.balanceInquiry(acctNumber)); 88 | } 89 | 90 | /** 91 | * doWithdraw() prompts the user for an account number and tries 92 | * to perform a withdrawal transaction from that account. 93 | * @exception IOException if there are problems reading user input. 94 | */ 95 | private void doWithdraw() throws IOException, BadAccountException, BadTransactionException{ 96 | // Get account number. 97 | int acctNumber = readInt("Enter account number: "); 98 | int amount = readInt("Enter amount to withdraw: "); 99 | 100 | ATM.withdraw(acctNumber, amount); 101 | System.out.println("New balance for #" + acctNumber + " is " + 102 | ATM.balanceInquiry(acctNumber)); 103 | } 104 | 105 | /** 106 | * doInquire() prompts the user for an account number, then attempts to 107 | * discover and print that account's balance. 108 | * @exception IOException if there are problems reading user input. 109 | */ 110 | private void doInquire() throws IOException, BadAccountException { 111 | int acctNumber = readInt("Enter account number: "); 112 | 113 | System.out.println("Balance for #" + acctNumber + " is " + 114 | ATM.balanceInquiry(acctNumber)); 115 | } 116 | 117 | /** 118 | * greeting() displays a greeting message on the screen. 119 | */ 120 | private static void greeting() { 121 | System.out.println("-------------------"); 122 | System.out.println("Welcome to the bank"); 123 | System.out.println("-------------------"); 124 | System.out.println(); 125 | } 126 | 127 | /** 128 | * usage() displays instructions on using the command line arguments. 129 | */ 130 | private static void usage() { 131 | System.out.println("Valid commands are: " + 132 | "open, deposit, withdraw, inquire, quit"); 133 | } 134 | 135 | /** 136 | * readLine() prints the given prompt and returns a string from the 137 | * input stream. 138 | * @param prompt is the string printed to prompt the user. 139 | */ 140 | private String readLine(String prompt) throws IOException { 141 | System.out.print(prompt); 142 | System.out.flush(); 143 | return bReader.readLine(); 144 | } 145 | 146 | /** 147 | * readInt() returns an integer from the input stream after prompting 148 | * the user. 149 | * @param prompt is the string printed to prompt the user. 150 | * @return an int read from the user. 151 | */ 152 | private int readInt(String prompt) throws IOException { 153 | String text = readLine(prompt); 154 | return Integer.valueOf(text).intValue(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /lab/lab6/GRADER: -------------------------------------------------------------------------------- 1 | Part I: Compile It (1 point) 2 | ----------------------------- 3 | Compile BankApp.java and all the classes it depends on. 4 | 5 | javac -g BankApp.java 6 | 7 | Fix the compile-time errors by adding a try/catch statement in the appropriate 8 | place(s). (Don't add a "throws" clause to the offending method; use a 9 | try/catch.) 10 | 11 | Once you have the program up and running, experiment with it to see how it 12 | works. What happens if you try to deposit a negative amount of money? What 13 | happens if you try to deposit to or withdraw from a nonexistent account? 14 | ============================================================ 15 | It will report Errer to user 16 | ============================================================ 17 | 18 | There is a subtle bug in the withdraw operation. What is it? 19 | (Hint: Under what _condition_ can you foil VirtualTeller.withdraw?) 20 | ============================================================ 21 | You can withdraw negative amount of money! 22 | ============================================================ 23 | 24 | Excepting the withdraw bug, the program handles errors correctly, but does so 25 | rather clumsily in the code. For instance, when you try to deposit to a 26 | nonexistent account, two error messages are printed. (Why?) Error-handling is 27 | not done well. 28 | ============================================================ 29 | One threw by findAccount by deposit(acct,amt); 30 | other threw by findAccount called by balanceInquiry(); 31 | ============================================================ 32 | 33 | Part II: Throwing Exceptions (2 points) 34 | ---------------------------------------- 35 | An exception class called BadAccountException has been created for your use; it 36 | should be thrown whenever an account cannot be found. Add the appropriate 37 | "throw" statement to VirtualTeller.java. (You should only need one.) Next, 38 | eliminate all the print statements generated when an account is not found. 39 | Add an appropriate "throws" clause wherever necessary. Be sure to catch the 40 | BadAccountException in main(); errors should not cause the application to halt. 41 | 42 | Is your modified code for VirtualTeller easier to read? Have you eliminated 43 | the problem of double error messages? (If not, you put the "throw" statement 44 | in the wrong place.) 45 | 46 | ============================================================ 47 | problem solved 48 | ============================================================ 49 | 50 | PART III: A New Exception (1 point) 51 | ------------------------------------ 52 | The withdraw method still has a bug, and when you try to deposit an invalid 53 | (e.g. negative) amount, a nonsensical "New balance" statement is printed. 54 | Fix these problems by creating a class "BadTransactionException", and adding 55 | the appropriate "throw" statements and "throws" clauses to VirtualTeller.java. 56 | Again, make sure the exception is caught in main(). Note that you will have to 57 | recompile AccountData explicitly. 58 | ============================================================ 59 | problem solved 60 | ============================================================ 61 | 62 | EXTRA: Slightly different behavior (optional) 63 | ---------------------------------------------- 64 | Observe that when an exception occurs during a transaction, you are prompted 65 | for a new command. Suppose you want slightly different behavior: if an 66 | exception occurs during a command, then the command is automatically repeated 67 | so you don't have to retype it. How can you do this by moving ONE line of code 68 | in BankApp.java? 69 | ============================================================ 70 | Can't figure out a way to do so by ONLY MOVE ONE Line of code 71 | Can do it by moving severals 72 | ============================================================ 73 | -------------------------------------------------------------------------------- /lab/lab6/VirtualTeller.java: -------------------------------------------------------------------------------- 1 | /* VirtualTeller.java */ 2 | 3 | import sortedlist.*; 4 | 5 | /** 6 | * An implementation of a virtual automated teller machine. 7 | **/ 8 | public class VirtualTeller { 9 | private static int nextAccountID = 100; 10 | private SortedList accounts; 11 | 12 | /** 13 | * Constructs a new virtual teller. 14 | **/ 15 | public VirtualTeller() { 16 | accounts = new SortedList(); 17 | } 18 | 19 | /** 20 | * openAccount() creates a new account for the customer "name". 21 | * @param name the customer's name. 22 | * @return the new account's ID number. 23 | **/ 24 | public int openAccount(String name) { 25 | AccountData newData = new AccountData(name, nextAccountID); 26 | accounts.insert(newData); 27 | 28 | nextAccountID++; 29 | return newData.getNumber(); 30 | } 31 | 32 | /** 33 | * withdraw() withdraws "amount" dollars from the account whose number is 34 | * "acct". Assumes that amount >= 0. If "acct" is invalid, no action is 35 | * taken. 36 | * @param acct is an account number. 37 | * @param amount an amount of money. 38 | */ 39 | public void withdraw(int acct, int amount) throws BadAccountException, BadTransactionException{ 40 | AccountData account = findAccount(acct); 41 | account.withdraw(amount); 42 | } 43 | 44 | /** 45 | * deposit() deposits "amount" dollars into the bank account whose number is 46 | * "acct". Assumes that amount >= 0. If "acct" is invalid, no action is 47 | * taken. 48 | * @param acct is an account number. 49 | * @param amount an amount of money. 50 | */ 51 | public void deposit(int acct, int amount) throws BadAccountException, BadTransactionException { 52 | AccountData account = findAccount(acct); 53 | account.deposit(amount); 54 | } 55 | 56 | /** 57 | * balanceInquiry() finds the balance on the account whose number is "acct". 58 | * If "acct" is an invalid number, returns -1. 59 | * @param acct an account number. 60 | * @return the balance, or -1 if the account number is invalid. 61 | */ 62 | public int balanceInquiry(int acct) throws BadAccountException { 63 | AccountData account = findAccount(acct); 64 | return account.getBalance(); 65 | } 66 | 67 | /** 68 | * findAccount() gets the AccountData object associated with account number 69 | * "acct". If "acct" does not refer to a valid account, returns null. 70 | * @param acct is an account number. 71 | * @return the AccountData object associated with the account number. 72 | */ 73 | private AccountData findAccount(int acct) throws BadAccountException { 74 | AccountData account = (AccountData) accounts.find(acct); 75 | // for problem II 76 | if(account==null) { 77 | throw new BadAccountException(acct); 78 | } 79 | return account; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /lab/lab6/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 6 2 | March 5-6, 2013 3 | 4 | Goal: This lab will introduce you to Java's built-in facilities for exception 5 | handling, and show you why they might be a good idea. 6 | 7 | Copy the Lab 6 directory by doing the following, starting from your home 8 | directory. 9 | 10 | cp -r ~cs61b/lab/lab6 . 11 | cd lab6 12 | 13 | In this lab, you will modify a banking application. BankApp is a command-line 14 | driven program that allows you to create and manipulate customer bank accounts. 15 | 16 | Part I: Compile It (1 point) 17 | ----------------------------- 18 | Compile BankApp.java and all the classes it depends on. 19 | 20 | javac -g BankApp.java 21 | 22 | Fix the compile-time errors by adding a try/catch statement in the appropriate 23 | place(s). (Don't add a "throws" clause to the offending method; use a 24 | try/catch.) 25 | 26 | Once you have the program up and running, experiment with it to see how it 27 | works. What happens if you try to deposit a negative amount of money? What 28 | happens if you try to deposit to or withdraw from a nonexistent account? 29 | 30 | There is a subtle bug in the withdraw operation. What is it? 31 | (Hint: Under what _condition_ can you foil VirtualTeller.withdraw?) 32 | 33 | Excepting the withdraw bug, the program handles errors correctly, but does so 34 | rather clumsily in the code. For instance, when you try to deposit to a 35 | nonexistent account, two error messages are printed. (Why?) Error-handling is 36 | not done well. 37 | 38 | Part II: Throwing Exceptions (2 points) 39 | ---------------------------------------- 40 | An exception class called BadAccountException has been created for your use; it 41 | should be thrown whenever an account cannot be found. Add the appropriate 42 | "throw" statement to VirtualTeller.java. (You should only need one.) Next, 43 | eliminate all the print statements generated when an account is not found. 44 | Add an appropriate "throws" clause wherever necessary. Be sure to catch the 45 | BadAccountException in main(); errors should not cause the application to halt. 46 | 47 | Is your modified code for VirtualTeller easier to read? Have you eliminated 48 | the problem of double error messages? (If not, you put the "throw" statement 49 | in the wrong place.) 50 | 51 | PART III: A New Exception (1 point) 52 | ------------------------------------ 53 | The withdraw method still has a bug, and when you try to deposit an invalid 54 | (e.g. negative) amount, a nonsensical "New balance" statement is printed. 55 | Fix these problems by creating a class "BadTransactionException", and adding 56 | the appropriate "throw" statements and "throws" clauses to VirtualTeller.java. 57 | Again, make sure the exception is caught in main(). Note that you will have to 58 | recompile AccountData explicitly. 59 | 60 | EXTRA: Slightly different behavior (optional) 61 | ---------------------------------------------- 62 | Observe that when an exception occurs during a transaction, you are prompted 63 | for a new command. Suppose you want slightly different behavior: if an 64 | exception occurs during a command, then the command is automatically repeated 65 | so you don't have to retype it. How can you do this by moving ONE line of code 66 | in BankApp.java? 67 | 68 | Check-off 69 | --------- 70 | Demonstrate the application for your TA or Lab Assistant. Show him/her the 71 | changes in your code. 72 | 73 | 1 point: Run your program and show that it behaves well if an invalid 74 | command is entered. 75 | 2 points: Show that your program behaves well when you try to deposit to a 76 | nonexistent account. Explain which method you put the "throw" 77 | statement in. 78 | 1 point: Show what happens when you try to deposit or withdraw an invalid 79 | amount. 80 | -------------------------------------------------------------------------------- /lab/lab6/sortedlist/Keyable.java: -------------------------------------------------------------------------------- 1 | /* Keyable.java */ 2 | 3 | package sortedlist; 4 | 5 | public interface Keyable { 6 | public int getKey(); 7 | public boolean lessThan(Keyable x); 8 | } 9 | -------------------------------------------------------------------------------- /lab/lab6/sortedlist/ListEnum.java: -------------------------------------------------------------------------------- 1 | /* ListEnum.java */ 2 | 3 | package sortedlist; 4 | 5 | import java.util.Enumeration; 6 | 7 | /** 8 | * The ListEnum class implements an Enumeration for singly-linked lists. 9 | * ListEnum objects are mutable. 10 | * @author Kathy Yelick 11 | **/ 12 | 13 | public class ListEnum implements Enumeration { 14 | private ListNode trav; 15 | 16 | /** 17 | * Creates a new enumeration for the elements linked with ListNodes 18 | * starting with l. Requires that there are no cycles in the list. 19 | */ 20 | public ListEnum( ListNode l ) { 21 | trav = l; 22 | } 23 | 24 | /** 25 | * Tests if this enumeration contains more elements. 26 | * @return true if this enumeration contains more elements; false otherwise 27 | */ 28 | public boolean hasMoreElements() { 29 | return (trav != null); 30 | } 31 | 32 | /** 33 | * Returns the next element of this enumeration. 34 | * Modifies the enumeration to move the enumeration past the returned 35 | * element of the list. 36 | * @return the next element of this enumeration. 37 | */ 38 | public Object nextElement() { 39 | Object retItem = trav.item; 40 | trav = trav.next; 41 | return retItem; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /lab/lab6/sortedlist/ListNode.java: -------------------------------------------------------------------------------- 1 | /* ListNode.java */ 2 | 3 | package sortedlist; 4 | 5 | /** 6 | * ListNode is a class used internally by the List class. Each node in a 7 | * List is represented as a ListNode, with an item and a reference to the 8 | * next node in the list. 9 | **/ 10 | class ListNode { 11 | Keyable item; 12 | ListNode next; 13 | 14 | /** 15 | * Constructs a ListNode with item obj and next null. 16 | * @param obj will be the item in the node. 17 | **/ 18 | ListNode(Keyable obj) { 19 | item = obj; 20 | next = null; 21 | } 22 | 23 | /** 24 | * Constructs a ListNode with item obj and next n. 25 | * @param obj will be the item in the node. 26 | * @param n will be the next ListNode in the list. 27 | **/ 28 | ListNode(Keyable obj, ListNode n) { 29 | item = obj; 30 | next = n; 31 | } 32 | 33 | /** 34 | * ptrTo() returns a reference to the node at the given position. If 35 | * position < 1 or position > the number of nodes in the list, returns 36 | * null. Assumes the list is acyclic. 37 | * @return a reference to the node at position "position". 38 | */ 39 | public ListNode ptrTo(int position) { 40 | if (position < 1) { 41 | return null; 42 | } else if (position == 1) { 43 | return this; 44 | } else if (next == null) { 45 | return null; 46 | } else { 47 | return next.ptrTo(position - 1); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lab/lab6/sortedlist/SortedList.java: -------------------------------------------------------------------------------- 1 | /* SortedList.java */ 2 | 3 | package sortedlist; 4 | import java.util.Enumeration; 5 | 6 | /** 7 | * The SortedList class is a singly-linked implementation of a linked list in 8 | * sorted order. SortedLists are mutable data structures that can grow at 9 | * either end. 10 | * @author Kathy Yelick, Bob Zasio 11 | **/ 12 | public class SortedList { 13 | private int size; 14 | ListNode head; 15 | 16 | /** 17 | * Construct an empty list 18 | **/ 19 | public SortedList() { 20 | size = 0; 21 | head = null; 22 | } 23 | 24 | /** 25 | * isEmpty() returns true if this list is empty, false otherwise. 26 | * @return true if the list is empty, false otherwise. 27 | **/ 28 | public boolean isEmpty() { 29 | return (size == 0); 30 | } 31 | 32 | /** 33 | * length() returns the length of this list. 34 | * @return the length of the list. 35 | **/ 36 | public int length() { 37 | return size; 38 | } 39 | 40 | /** 41 | * insert() inserts the element x into the proper sorted location. 42 | **/ 43 | public void insert(Keyable x) { 44 | ListNode newnode = new ListNode(x, null); 45 | 46 | if (head == null) { 47 | head = newnode; 48 | } else if (!head.item.lessThan(x)) { 49 | newnode.next = head; 50 | head = newnode; 51 | } else { 52 | ListNode temp = head; 53 | while (temp.next != null) { 54 | if (!temp.next.item.lessThan(x)) { 55 | newnode.next = temp.next; 56 | temp.next = newnode; 57 | temp = temp.next; 58 | break; 59 | } 60 | temp = temp.next; 61 | } 62 | if (temp.next == null) { 63 | temp.next = newnode; 64 | } 65 | } 66 | size++; 67 | } 68 | 69 | /** 70 | * Keyable() returns the element with the given key, or null if none of the 71 | * elements have that key. 72 | **/ 73 | public Keyable find(int key) { 74 | ListNode temp = head; 75 | while (temp != null) { 76 | if (temp.item.getKey() == key) { 77 | return temp.item; 78 | } 79 | temp = temp.next; 80 | } 81 | return null; 82 | } 83 | 84 | /** 85 | * elements() returns an Enumeration of the components of this list. 86 | * @return an Enumeration of the components of this list. 87 | **/ 88 | public Enumeration elements() { 89 | return new ListEnum(head); 90 | } 91 | 92 | /** 93 | * toString() returns a String representation of this list. 94 | * @return a String representation of this list. 95 | **/ 96 | public String toString() { 97 | int i; 98 | Object obj; 99 | String result = "[ "; 100 | 101 | ListNode cur = head; 102 | 103 | while (cur != null) { 104 | obj = cur.item; 105 | result = result + obj.toString() + " "; 106 | cur = cur.next; 107 | } 108 | result = result + "]"; 109 | return result; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /lab/lab7/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 7 2 | March 12-13, 2013 3 | 4 | Show your TA your module design (class, modules, and interfaces) for Project 2. 5 | If your partners are in different labs, they will need to get the project 6 | checked off separately by their TAs as well. You may use the rest of the lab 7 | to work on your project. When your TA is finished with check-offs, you may use 8 | this as an opportunity to ask the TA or lab assistant any questions you have 9 | about the project. 10 | 11 | If you wish to continue working when your lab time ends, please move to another 12 | room (unless yours is the last lab of the day). 13 | 14 | Check-off 15 | --------- 16 | 4 points: Show your TA the complete documentation of the modules and 17 | interfaces for your project. 18 | 19 | This is an all-or-nothing lab; any reasonable attempt will garner 4 points. 20 | -------------------------------------------------------------------------------- /lab/lab8/DebugMe.java: -------------------------------------------------------------------------------- 1 | /* DebugMe.java */ 2 | 3 | /** 4 | * DebugMe is an application for summing a geometric series. 5 | **/ 6 | class DebugMe { 7 | 8 | /** 9 | * main() prints the value of a geometric series. 10 | * @param args is ignored. 11 | **/ 12 | public static void main(String[] args) { 13 | 14 | int N = 3; 15 | ListNode geomSeries = createGeomSeries(1.0/2, N); 16 | double sum = listSum(geomSeries); 17 | 18 | System.out.println("for N = " + N + ",\n"); 19 | System.out.println(" N | 1 |^i"); 20 | System.out.println(" sum |---| = " + sum); 21 | System.out.println(" i=0 | 2 |\n"); 22 | } 23 | 24 | /** 25 | * createGeomSeries() creates a list built from ListNodes in which each item 26 | * is a Double containing one term in the geometric series 27 | * 28 | * N 29 | * sum (r^i). 30 | * i=0 31 | * 32 | * @param r is the base of the geometric series. 33 | * @param N is the maximum exponent of any term in the geometric series. 34 | * N is assumed to be non-negative. 35 | */ 36 | public static ListNode createGeomSeries(double r, int N) { 37 | ListNode newTerm = new ListNode(null, null); 38 | if (N == 0) { 39 | newTerm.item = new Double(1.0); 40 | newTerm.next = null; 41 | } else { 42 | newTerm.next = createGeomSeries(r, N - 1); 43 | newTerm.item = new Double(((Double) newTerm.next.item).doubleValue() * 44 | r); 45 | } 46 | 47 | return newTerm; 48 | } 49 | 50 | 51 | /** 52 | * listSum() computes the sum of terms in a list. 53 | * @param l is linked list represented by ListNodes. Each item in the list 54 | * is assumed to be a Double. 55 | */ 56 | public static double listSum(ListNode l) { 57 | if (l == null) { 58 | return 0.0; 59 | } 60 | 61 | return ((Double) l.item).doubleValue() + listSum(l.next); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /lab/lab8/ListNode.java: -------------------------------------------------------------------------------- 1 | /* ListNode.java */ 2 | 3 | /** 4 | * ListNode is a very simple headless list class, akin to cons cells in 5 | * Scheme. Each ListNode contains an item and a reference to the next node. 6 | **/ 7 | class ListNode { 8 | 9 | public Object item; 10 | public ListNode next; 11 | 12 | /** 13 | * Constructs a ListNode with item i and next node n. 14 | * @param i the item to store in the ListNode. 15 | * @param n the next ListNode following this ListNode. 16 | **/ 17 | ListNode(Object i, ListNode n) { 18 | item = i; 19 | next = n; 20 | } 21 | 22 | public String toString() { 23 | String str= "{ "; 24 | ListNode walker = this; 25 | while(walker!=null) { 26 | str += walker.item+" "; 27 | walker=walker.next; 28 | } 29 | str+="}"; 30 | return str; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /lab/lab9/readme.txt: -------------------------------------------------------------------------------- 1 | CS 61B Lab 9 2 | April 2-3, 2013 3 | 4 | Goal: to practice proving asymptotic (big-Oh) results. The class notes from 5 | Lecture 20 may come in handy; however, we will try to be even more rigorous 6 | here than in lecture. 7 | 8 | Recall the definition of big-Oh: 9 | 10 | |=============================================================================| 11 | | O(f(n)) is the SET of ALL functions T(n) that satisfy: | 12 | | | 13 | | There exist positive constants c and N such that, for all n >= N, | 14 | | T(n) <= c f(n) | 15 | |=============================================================================| 16 | 17 | EXAMPLE 18 | ------- 19 | Formally prove that n^2 + n + 1 is in O(n^2). 20 | 21 | Solution: 22 | Let T(n) = n^2 + n + 1. Let f(n) = n^2. 23 | 24 | Choose c = 3, and N = 1. Then, we know T(n) is in O(n^2) if we can prove 25 | 26 | T(n) <= c f(n), 27 | or equivalently, n^2 + n + 1 <= 3 n^2, for all n >= 1. 28 | 29 | Is this inequality true? Well, for any n >= 1, we know that 1 <= n <= n^2. 30 | Hence, all of the following are true: 31 | 32 | 1 <= n^2 33 | n <= n^2 34 | n^2 = n^2 35 | 36 | Adding the left and right sides of these inequalities together, we have 37 | 38 | n^2 + n + 1 <= 3 n^2, which completes the proof. 39 | 40 | Part I: (1 point) 41 | ------------------ 42 | Formally prove that 2^n + 1 is in O(4^n - 16). 43 | 44 | HINT: You may assert without proof that, for all n >=1, 2^n >= 1. 45 | (You may also assert without proof that 4^n and 2^n are monotonically 46 | increasing, if you find it useful.) 47 | 48 | Part II: (1 point) 49 | ------------------- 50 | Formally prove that if f(n) is in O(g(n)), and g(n) is in O(h(n)), then 51 | f(n) is in O(h(n)). 52 | 53 | NOTE: The values of c and N used to prove that f(n) is in O(g(n)) are 54 | not necessarily the same as the values used to prove that g(n) is in O(h(n)). 55 | Hence, assume that there are positive c', N', c'', and N'' such that 56 | 57 | f(n) <= c' g(n) for all n >= N', and 58 | g(n) <= c'' h(n) for all n >= N''. 59 | 60 | Part III: (2 points) 61 | --------------------- 62 | Formally prove that 0.01 n^2 - 1 is NOT in O(n). 63 | 64 | We need to show that, no matter how large we choose c and N, we will never 65 | obtain the desired inequality. We cannot prove this by picking a specific 66 | value of c and N. Instead, we must study how the two functions behave as 67 | n approaches infinity. 68 | 69 | Let T(n) = 0.01 n^2 - 1, and let f(n) = n. Prove that 70 | 71 | c f(n) 72 | lim ------ = 0, 73 | n->infinity T(n) 74 | 75 | no matter how large we choose c to be. You will need to scale both the 76 | numerator and the denominator by a well-chosen multiplier to get the result. 77 | 78 | Use this result to show that there are no values c, N such that T(n) <= c f(n) 79 | for all n >= N. 80 | 81 | Postscript 82 | ---------- 83 | The functions |cos(n)| and |sin(n)| are interesting, because neither is 84 | dominated by the other. Can you informally suggest why |cos(n)| is not in 85 | O(|sin(n)|), and |sin(n)| is not in O(|cos(n)|)? 86 | 87 | How would you prove that, for all n >=1, 2^n >= 1? (Hint: use calculus.) 88 | -------------------------------------------------------------------------------- /projects/pj1/DList.java: -------------------------------------------------------------------------------- 1 | /* DList.java */ 2 | // Modified by Ryan (Weiran) Zhao 3 | // Tue,Jun 11th 2013 08:30:25 PM EDT 4 | // History 5 | // Thu,Jun 13th 2013 02:33:39 PM EDT: Modified for project 1 6 | 7 | /** 8 | * A DList is a mutable doubly-linked list. Its implementation is 9 | * circularly-linked and employs a sentinel (dummy) node at the head 10 | * of the list. 11 | */ 12 | 13 | public class DList { 14 | 15 | /** 16 | * head references the sentinel node. 17 | * 18 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 19 | */ 20 | 21 | protected DListNode head; 22 | protected long size; 23 | 24 | /* DList invariants: 25 | * 1) head != null. 26 | * 2) For any DListNode x in a DList, x.next != null. 27 | * 3) For any DListNode x in a DList, x.prev != null. 28 | * 4) For any DListNode x in a DList, if x.next == y, then y.prev == x. 29 | * 5) For any DListNode x in a DList, if x.prev == y, then y.next == x. 30 | * 6) size is the number of DListNode2s, NOT COUNTING the sentinel 31 | * (denoted by "head"), that can be accessed from the sentinel by 32 | * a sequence of "next" references. 33 | */ 34 | 35 | /** 36 | * DList() constructor for an empty DList. 37 | */ 38 | public DList() { 39 | // creating sentinel 40 | head = new DListNode(null,null,null); 41 | head.next = head; 42 | head.prev = head; 43 | size = 0; 44 | } 45 | 46 | /** 47 | * insertFront() inserts an item at the front of a DList. 48 | */ 49 | public void insertFront(Object item) { 50 | DListNode tmp= new DListNode(item,head,head.next); 51 | head.next.prev=tmp; 52 | head.next=tmp; 53 | size+=1; 54 | } 55 | 56 | /** 57 | * isertBack() inserts an item at the back of a DList 58 | */ 59 | public void insertBack(Object item) { 60 | DListNode tmp = new DListNode(item,head.prev,head); 61 | head.prev.next=tmp; 62 | head.prev=tmp; 63 | size+=1; 64 | } 65 | 66 | /** 67 | * back() return the last element 68 | */ 69 | public Object back() { 70 | return head.prev.item; 71 | } 72 | 73 | /** 74 | * removeFront() removes the first item (and first non-sentinel node) from 75 | * a DList. If the list is empty, do nothing. 76 | */ 77 | public void removeFront() { 78 | if(size==0) 79 | return; 80 | head.next.next.prev=head; 81 | head.next=head.next.next; 82 | size-=1; 83 | } 84 | 85 | /** 86 | * next(target) returns the node next to 'target' in DList 87 | * we have to trust the user input a node that is in the DList 88 | */ 89 | public DListNode next(DListNode target) { 90 | return target.next; 91 | } 92 | 93 | /** 94 | * insertAfter(DListNode, Object) insert a node after the given node 95 | */ 96 | public void insertAfter(DListNode node, Object item) { 97 | DListNode tmp = new DListNode(item, node, node.next); 98 | node.next.prev=tmp; 99 | node.next=tmp; 100 | size+=1; 101 | } 102 | 103 | /** 104 | * insertBefore(DListNode, Object) insert a node after the given node 105 | */ 106 | public void insertBefore(DListNode node, Object item) { 107 | DListNode tmp = new DListNode(item, node.prev, node); 108 | node.prev.next=tmp; 109 | node.prev=tmp; 110 | size+=1; 111 | } 112 | 113 | /** 114 | * remove(DListNode) removes the node from DList 115 | */ 116 | public void remove(DListNode node) { 117 | node.next.prev=node.prev; 118 | node.prev.next=node.next; 119 | size-=1; 120 | } 121 | 122 | 123 | /** 124 | * toString() returns a String representation of this DList. 125 | * 126 | * DO NOT CHANGE THIS METHOD. 127 | * 128 | * @return a String representation of this DList. 129 | */ 130 | public String toString() { 131 | String result = "[ "; 132 | DListNode current = head.next; 133 | while (current != head) { 134 | result = result + current.item + " "; 135 | current = current.next; 136 | } 137 | return result + "]"; 138 | } 139 | 140 | public static void main(String[] args) { 141 | DList lst = new DList(); 142 | System.out.println("empty"+lst); 143 | int[] toInsert= new int[2]; 144 | toInsert[0]=2; 145 | toInsert[1]=3; 146 | lst.insertFront(toInsert); 147 | System.out.println("insert [2,5] " + lst); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /projects/pj1/DListNode.java: -------------------------------------------------------------------------------- 1 | /* DListNode.java */ 2 | // Modified from DListNode2.java from lab4 3 | // By Ryan (Weiran) Zhao 4 | // Thu,Jun 13th 2013 02:31:33 PM EDT 5 | 6 | /** 7 | * A DListNode is a node in a DList (doubly-linked list). 8 | */ 9 | 10 | public class DListNode { 11 | 12 | /** 13 | * item references the item stored in the current node. 14 | * prev references the previous node in the DList. 15 | * next references the next node in the DList. 16 | * 17 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 18 | */ 19 | 20 | public Object item; 21 | protected DListNode prev; 22 | protected DListNode next; 23 | 24 | /** 25 | * DListNode() constructor. 26 | */ 27 | DListNode(Object i, DListNode p, DListNode n) { 28 | item = i; 29 | prev = p; 30 | next = n; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /projects/pj1/Record.java: -------------------------------------------------------------------------------- 1 | 2 | public class Record { 3 | /** 4 | * used to represent 1 record in run-length encoding 5 | * each record contains fields: 6 | * type: either empty, fish or shark; 7 | * hungerness: to distinguish different hunger level sharks; 8 | * length: length of this type 9 | */ 10 | public int type; 11 | public int hungerness; 12 | public int length; 13 | 14 | public Record(int type, int hungerness, int length) { 15 | this.type=type; 16 | this.hungerness=hungerness; 17 | this.length=length; 18 | } 19 | 20 | public Record() { 21 | this(-1,-1,-1); 22 | } 23 | 24 | public String toString(){ 25 | String tmp="{ "; 26 | tmp+=type+" "; 27 | tmp+=hungerness+" "; 28 | tmp+=length+" "; 29 | tmp+="}"; 30 | return tmp; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /projects/pj1/SimText.java: -------------------------------------------------------------------------------- 1 | /* SimText.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE (except as noted). */ 4 | /* YOUR SUBMISSION MUST WORK CORRECTLY WITH _OUR_ COPY OF THIS FILE. */ 5 | 6 | /* (You may wish to make temporary changes or insert println() statements */ 7 | /* while testing your code. When you're finished testing and debugging, */ 8 | /* though, make sure your code works with the original version of this file. */ 9 | 10 | import java.util.*; 11 | 12 | /** 13 | * The SimText class is a program that runs and animates a simulation of 14 | * Sharks and Fish. 15 | * 16 | * The SimText program takes up to four parameters. The first two specify 17 | * the width and height of the ocean. The third parameter specifies the value 18 | * of starveTime. For example, if you run 19 | * 20 | * java SimText 25 25 1 21 | * 22 | * then SimText will animate a 25x25 ocean with a starveTime of 1. If you run 23 | * "java SimText" with no parameters, by default SimText will animate a 50x25 24 | * ocean with a starveTime of 3. With some choices of parameters, the ocean 25 | * quickly dies out; with others, it teems forever. 26 | * 27 | * @author Jonathan Shewchuk 28 | */ 29 | 30 | public class SimText { 31 | 32 | /** 33 | * Default parameters. (You may change these if you wish.) 34 | */ 35 | 36 | private static int i = 50; // Default ocean width 37 | private static int j = 25; // Default ocean height 38 | private static int starveTime = 3; // Default shark starvation time 39 | 40 | /** 41 | * paint() prints an Ocean. 42 | */ 43 | 44 | public static void paint(Ocean sea) { 45 | if (sea != null) { 46 | int width = sea.width(); 47 | int height = sea.height(); 48 | 49 | /* Draw the ocean. */ 50 | for (int x = 0; x < width + 2; x++) { 51 | System.out.print("-"); 52 | } 53 | System.out.println(); 54 | for (int y = 0; y < height; y++) { 55 | System.out.print("|"); 56 | for (int x = 0; x < width; x++) { 57 | int contents = sea.cellContents(x, y); 58 | if (contents == Ocean.SHARK) { 59 | System.out.print('S'); 60 | } else if (contents == Ocean.FISH) { 61 | System.out.print('~'); 62 | } else { 63 | System.out.print(' '); 64 | } 65 | } 66 | System.out.println("|"); 67 | } 68 | for (int x = 0; x < width + 2; x++) { 69 | System.out.print("-"); 70 | } 71 | System.out.println(); 72 | } 73 | } 74 | 75 | /** 76 | * main() reads the parameters and performs the simulation and animation. 77 | */ 78 | 79 | public static void main(String[] argv) throws InterruptedException { 80 | Ocean sea; 81 | 82 | /** 83 | * Read the input parameters. 84 | */ 85 | 86 | if (argv.length > 0) { 87 | try { 88 | i = Integer.parseInt(argv[0]); 89 | } 90 | catch (NumberFormatException e) { 91 | System.out.println("First argument to SimText is not an number."); 92 | } 93 | } 94 | 95 | if (argv.length > 1) { 96 | try { 97 | j = Integer.parseInt(argv[1]); 98 | } 99 | catch (NumberFormatException e) { 100 | System.out.println("Second argument to SimText is not an number."); 101 | } 102 | } 103 | 104 | if (argv.length > 2) { 105 | try { 106 | starveTime = Integer.parseInt(argv[2]); 107 | } 108 | catch (NumberFormatException e) { 109 | System.out.println("Third argument to SimText is not an number."); 110 | } 111 | } 112 | 113 | /** 114 | * Create the initial ocean. 115 | */ 116 | 117 | sea = new Ocean(i, j, starveTime); 118 | 119 | /** 120 | * Visit each cell (in a roundabout order); randomly place a fish, shark, 121 | * or nothing in each. 122 | */ 123 | 124 | Random random = new Random(0); // Create a "Random" object with seed 0 125 | int x = 0; 126 | int y = 0; 127 | for (int xx = 0; xx < i; xx++) { 128 | x = (x + 78887) % i; // This will visit every x-coordinate once 129 | if ((x & 8) == 0) { 130 | for (int yy = 0; yy < j; yy++) { 131 | y = (y + 78887) % j; // This will visit every y-coordinate once 132 | if ((y & 8) == 0) { 133 | int r = random.nextInt(); // Between -2147483648 and 2147483647 134 | if (r < 0) { // 50% of cells start with fish 135 | sea.addFish(x, y); 136 | } else if (r > 1500000000) { // ~15% of cells start with sharks 137 | sea.addShark(x, y); 138 | } 139 | } 140 | } 141 | } 142 | } 143 | 144 | /** 145 | * Perform timesteps forever. 146 | */ 147 | 148 | while (true) { // Loop forever 149 | paint(sea); 150 | // For fun, you might wish to change the delay in the next line. 151 | Thread.sleep(1000); // Wait one second (1000 milliseconds) 152 | sea = sea.timeStep(); // Simulate a timestep 153 | } 154 | } 155 | 156 | } 157 | -------------------------------------------------------------------------------- /projects/pj1/Simulation.java: -------------------------------------------------------------------------------- 1 | /* Simulation.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE (except as noted). */ 4 | /* YOUR SUBMISSION MUST WORK CORRECTLY WITH _OUR_ COPY OF THIS FILE. */ 5 | 6 | /* (You may wish to make temporary changes or insert println() statements */ 7 | /* while testing your code. When you're finished testing and debugging, */ 8 | /* though, make sure your code works with the original version of this file. */ 9 | 10 | import java.awt.*; 11 | import java.util.*; 12 | 13 | /** 14 | * The Simulation class is a program that runs and animates a simulation of 15 | * Sharks and Fish. 16 | * 17 | * The Simulation program takes up to four parameters. The first two specify 18 | * the width and height of the ocean. The third parameter specifies the value 19 | * of starveTime. For example, if you run 20 | * 21 | * java SimText 25 25 1 22 | * 23 | * then Simulation will animate a 25x25 ocean with a starveTime of 1. If you 24 | * run "java SimText" with no parameters, by default Simulation will animate 25 | * a 50x25 ocean with a starveTime of 3. With some choices of parameters, 26 | * the ocean quickly dies out; with others, it teems forever. 27 | * 28 | * @author Jonathan Shewchuk 29 | */ 30 | 31 | public class Simulation { 32 | 33 | /** 34 | * The constant cellSize determines the size of each cell on the screen 35 | * during animation. (You may change this if you wish.) 36 | */ 37 | 38 | private static final int cellSize = 4; 39 | 40 | /** 41 | * Default parameters. (You may change these if you wish.) 42 | */ 43 | 44 | private static int i = 80; // Default ocean width 45 | private static int j = 80; // Default ocean height 46 | private static int starveTime = 3; // Default shark starvation time 47 | 48 | private static void drawOcean(Graphics graphics, Ocean ocean) { 49 | if (ocean != null) { 50 | int width = ocean.width(); 51 | int height = ocean.height(); 52 | 53 | for (int y = 0; y < height; y++) { 54 | for (int x = 0; x < width; x++) { 55 | int contents = ocean.cellContents(x, y); 56 | if (contents == Ocean.SHARK) { 57 | graphics.setColor(Color.red); // Draw a red shark 58 | graphics.fillRect(x * cellSize, y * cellSize, cellSize, cellSize); 59 | } else if (contents == Ocean.FISH) { 60 | graphics.setColor(Color.green); // Draw a green fish 61 | graphics.fillRect(x * cellSize, y * cellSize, cellSize, cellSize); 62 | } else { 63 | graphics.clearRect(x * cellSize, y * cellSize, cellSize, cellSize); 64 | } 65 | } 66 | } 67 | } 68 | } 69 | 70 | /** 71 | * main() reads the parameters and performs the simulation and animation. 72 | */ 73 | 74 | public static void main(String[] argv) throws InterruptedException { 75 | Ocean sea; 76 | 77 | /** 78 | * Read the input parameters. 79 | */ 80 | 81 | if (argv.length > 0) { 82 | try { 83 | i = Integer.parseInt(argv[0]); 84 | } 85 | catch (NumberFormatException e) { 86 | System.out.println("First argument to Simulation is not an number."); 87 | } 88 | } 89 | 90 | if (argv.length > 1) { 91 | try { 92 | j = Integer.parseInt(argv[1]); 93 | } 94 | catch (NumberFormatException e) { 95 | System.out.println("Second argument to Simulation is not an number."); 96 | } 97 | } 98 | 99 | if (argv.length > 2) { 100 | try { 101 | starveTime = Integer.parseInt(argv[2]); 102 | } 103 | catch (NumberFormatException e) { 104 | System.out.println("Third argument to Simulation is not an number."); 105 | } 106 | } 107 | 108 | /** 109 | * Create a window on your screen. 110 | */ 111 | 112 | Frame frame = new Frame("Sharks and Fish"); 113 | // The "10" and "30" in the following line were determined by trial and 114 | // error, and seem to be necessary for the lab machines. On some other 115 | // machines, they just create ugly margins. Sigh. 116 | frame.setSize(i * cellSize + 10, j * cellSize + 30); 117 | frame.show(); 118 | 119 | /** 120 | * Create a "Canvas" we can draw upon; attach it to the window. 121 | */ 122 | 123 | Canvas canvas = new Canvas(); 124 | canvas.setBackground(Color.white); 125 | canvas.setSize(i * cellSize, j * cellSize); 126 | frame.add(canvas); 127 | Graphics graphics = canvas.getGraphics(); 128 | 129 | /** 130 | * Create the initial ocean. 131 | */ 132 | 133 | sea = new Ocean(i, j, starveTime); 134 | 135 | /** 136 | * Visit each cell (in a roundabout order); randomly place a fish, shark, 137 | * or nothing in each. 138 | */ 139 | 140 | Random random = new Random(0); // Create a "Random" object with seed 0 141 | int x = 0; 142 | int y = 0; 143 | for (int xx = 0; xx < i; xx++) { 144 | x = (x + 78887) % i; // This will visit every x-coordinate once 145 | if ((x & 8) == 0) { 146 | for (int yy = 0; yy < j; yy++) { 147 | y = (y + 78887) % j; // This will visit every y-coordinate once 148 | if ((y & 8) == 0) { 149 | int r = random.nextInt(); // Between -2147483648 and 2147483647 150 | if (r < 0) { // 50% of cells start with fish 151 | sea.addFish(x, y); 152 | } else if (r > 1500000000) { // ~15% of cells start with sharks 153 | sea.addShark(x, y); 154 | } 155 | } 156 | } 157 | } 158 | } 159 | 160 | /** 161 | * Perform timesteps forever. 162 | */ 163 | 164 | while (true) { // Loop forever 165 | Thread.sleep(1000); // Wait one second (1000 milliseconds) 166 | drawOcean(graphics, sea); // Draw the current ocean 167 | // For fun, you might wish to change the delay in the next line. 168 | // If you make it too short, though, the graphics won't work properly. 169 | sea = sea.timeStep(); // Simulate a timestep 170 | } 171 | } 172 | 173 | } 174 | -------------------------------------------------------------------------------- /projects/pj1/Test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weiran-zhao/java_cs61b/bf37ad9a8868f26811f712f39783bd627d65093b/projects/pj1/Test.class -------------------------------------------------------------------------------- /projects/pj1/Test1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weiran-zhao/java_cs61b/bf37ad9a8868f26811f712f39783bd627d65093b/projects/pj1/Test1.class -------------------------------------------------------------------------------- /projects/pj1/Test2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weiran-zhao/java_cs61b/bf37ad9a8868f26811f712f39783bd627d65093b/projects/pj1/Test2.class -------------------------------------------------------------------------------- /projects/pj1/Test3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weiran-zhao/java_cs61b/bf37ad9a8868f26811f712f39783bd627d65093b/projects/pj1/Test3.class -------------------------------------------------------------------------------- /projects/pj1/Test4.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/weiran-zhao/java_cs61b/bf37ad9a8868f26811f712f39783bd627d65093b/projects/pj1/Test4.class -------------------------------------------------------------------------------- /projects/pj1/Test4.java: -------------------------------------------------------------------------------- 1 | /* Test4.java */ 2 | 3 | public class Test4 { 4 | public static int empty; 5 | public static int shark; 6 | public static int fish; 7 | 8 | public static void init() { 9 | empty = Ocean.EMPTY; 10 | shark = Ocean.SHARK; 11 | fish = Ocean.FISH; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /projects/pj1/things2remember.txt: -------------------------------------------------------------------------------- 1 | 1. In java, except for primal data types, creating an array 2 | type [] arr = new type[N] 3 | ONLY create N number of variables (reference) to type, no object created 4 | --------------------------------------------------------------------------------