├── hw4 ├── Test.zip ├── readme.pdf └── list │ ├── LockDListNode.java │ ├── DListNode.java │ ├── TestHelper.java │ ├── LockDList.java │ ├── TestDList.java │ ├── TestLockDList.java │ └── DList.java ├── hw10 ├── readme.pdf └── sort │ └── Sorts.java ├── hw2 ├── readme.pdf └── Date.java ├── hw3 ├── readme.pdf ├── test.java ├── TestHelper.java ├── SListNode.java ├── Homework3.java └── SList.java ├── hw5 ├── readme.pdf ├── list │ ├── InvalidNodeException.java │ ├── List.java │ ├── ListNode.java │ ├── SListNode.java │ ├── DListNode.java │ ├── SList.java │ └── DList.java └── Set.java ├── hw6 ├── readme.pdf ├── test.java ├── dict │ ├── Entry.java │ ├── Dictionary.java │ └── HashTableChained.java ├── Homework6Test.java └── SimpleBoard.java ├── hw7 ├── readme.pdf └── dict │ ├── IntDictionary.java │ ├── Tree234Node.java │ └── Tree234.java ├── hw8 ├── readme.pdf ├── list │ ├── QueueEmptyException.java │ ├── SListNode.java │ ├── Queue.java │ └── LinkedQueue.java ├── GRADER ├── Timer.java └── ListSorts.java ├── hw9 ├── readme.pdf └── set │ └── DisjointSets.java ├── pj1 ├── TIFF6.pdf ├── baby.tiff ├── black.tiff ├── engine.tiff ├── flower.tiff ├── readme.pdf ├── reggie.tiff ├── woman.tiff ├── feathers.tiff ├── jai_codec.jar ├── jai_core.jar ├── blur_reggie.tiff ├── blur_woman.tiff ├── edge_reggie.tiff ├── edge_woman.tiff ├── rle_reggie.tiff ├── highcontrast.tiff ├── Blur.java ├── RunIterator.java ├── Sobel.java └── ImageUtils.java ├── pj2 ├── readme.pdf ├── Network.class ├── pics │ ├── bad.gif │ ├── black.gif │ ├── blocked.gif │ ├── empty.gif │ ├── shadow.gif │ └── white.gif ├── Network │ ├── X1.class │ ├── X2.class │ ├── X3.class │ ├── X4.class │ ├── X5.class │ ├── X6.class │ └── X7.class ├── player │ ├── Board.java │ ├── Player.java │ └── Move.java └── GRADER.txt ├── pj3 ├── readme.pdf ├── pj3graph.pdf ├── graphalg │ └── Kruskal.java ├── graph │ ├── InternalVertex.java │ ├── Neighbors.java │ ├── HashTableAuto.java │ ├── InternalEdge.java │ └── VertexPair.java ├── set │ └── DisjointSets.java └── KruskalTest.java └── .gitignore /hw4/Test.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw4/Test.zip -------------------------------------------------------------------------------- /hw10/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw10/readme.pdf -------------------------------------------------------------------------------- /hw2/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw2/readme.pdf -------------------------------------------------------------------------------- /hw3/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw3/readme.pdf -------------------------------------------------------------------------------- /hw4/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw4/readme.pdf -------------------------------------------------------------------------------- /hw5/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw5/readme.pdf -------------------------------------------------------------------------------- /hw6/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw6/readme.pdf -------------------------------------------------------------------------------- /hw7/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw7/readme.pdf -------------------------------------------------------------------------------- /hw8/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw8/readme.pdf -------------------------------------------------------------------------------- /hw9/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/hw9/readme.pdf -------------------------------------------------------------------------------- /pj1/TIFF6.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/TIFF6.pdf -------------------------------------------------------------------------------- /pj1/baby.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/baby.tiff -------------------------------------------------------------------------------- /pj1/black.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/black.tiff -------------------------------------------------------------------------------- /pj1/engine.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/engine.tiff -------------------------------------------------------------------------------- /pj1/flower.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/flower.tiff -------------------------------------------------------------------------------- /pj1/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/readme.pdf -------------------------------------------------------------------------------- /pj1/reggie.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/reggie.tiff -------------------------------------------------------------------------------- /pj1/woman.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/woman.tiff -------------------------------------------------------------------------------- /pj2/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/readme.pdf -------------------------------------------------------------------------------- /pj3/readme.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj3/readme.pdf -------------------------------------------------------------------------------- /pj1/feathers.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/feathers.tiff -------------------------------------------------------------------------------- /pj1/jai_codec.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/jai_codec.jar -------------------------------------------------------------------------------- /pj1/jai_core.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/jai_core.jar -------------------------------------------------------------------------------- /pj2/Network.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network.class -------------------------------------------------------------------------------- /pj2/pics/bad.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/bad.gif -------------------------------------------------------------------------------- /pj3/pj3graph.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj3/pj3graph.pdf -------------------------------------------------------------------------------- /pj1/blur_reggie.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/blur_reggie.tiff -------------------------------------------------------------------------------- /pj1/blur_woman.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/blur_woman.tiff -------------------------------------------------------------------------------- /pj1/edge_reggie.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/edge_reggie.tiff -------------------------------------------------------------------------------- /pj1/edge_woman.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/edge_woman.tiff -------------------------------------------------------------------------------- /pj1/rle_reggie.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/rle_reggie.tiff -------------------------------------------------------------------------------- /pj2/Network/X1.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X1.class -------------------------------------------------------------------------------- /pj2/Network/X2.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X2.class -------------------------------------------------------------------------------- /pj2/Network/X3.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X3.class -------------------------------------------------------------------------------- /pj2/Network/X4.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X4.class -------------------------------------------------------------------------------- /pj2/Network/X5.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X5.class -------------------------------------------------------------------------------- /pj2/Network/X6.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X6.class -------------------------------------------------------------------------------- /pj2/Network/X7.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/Network/X7.class -------------------------------------------------------------------------------- /pj2/pics/black.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/black.gif -------------------------------------------------------------------------------- /pj2/pics/blocked.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/blocked.gif -------------------------------------------------------------------------------- /pj2/pics/empty.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/empty.gif -------------------------------------------------------------------------------- /pj2/pics/shadow.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/shadow.gif -------------------------------------------------------------------------------- /pj2/pics/white.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj2/pics/white.gif -------------------------------------------------------------------------------- /pj1/highcontrast.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/convexshiba/CS61B/HEAD/pj1/highcontrast.tiff -------------------------------------------------------------------------------- /hw3/test.java: -------------------------------------------------------------------------------- 1 | package hw3; 2 | 3 | /** 4 | * Created by Meth on 1/4/15. 5 | */ 6 | public class test { 7 | public static void main(String[] args) { 8 | System.out.println(1); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /hw8/list/QueueEmptyException.java: -------------------------------------------------------------------------------- 1 | package hw8.list;/* hw8.list.QueueEmptyException.java */ 2 | 3 | public class QueueEmptyException extends Exception { 4 | 5 | public QueueEmptyException() { 6 | super(); 7 | } 8 | 9 | public QueueEmptyException(String s) { 10 | super(s); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /hw4/list/LockDListNode.java: -------------------------------------------------------------------------------- 1 | package hw4.list; 2 | 3 | /** 4 | * Created by Meth on 1/8/15. 5 | */ 6 | public class LockDListNode extends DListNode { 7 | boolean lockStatus; 8 | 9 | LockDListNode(Object item, DListNode prev, DListNode next) { 10 | super(item, prev, next); 11 | lockStatus = false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /pj2/player/Board.java: -------------------------------------------------------------------------------- 1 | package pj2.player; 2 | 3 | /** 4 | * This file is created by @Muffin_C on 1/26/15 21:05. 5 | * This file is part of Project CS61B. 6 | */ 7 | class Board { 8 | int[][] board = new int[8][8]; 9 | boolean[][] visited = new boolean[8][8]; 10 | 11 | void initVisit() { 12 | visited = new boolean[8][8]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /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 | 100 10 | 1,000 11 | 10,000 12 | 100,000 13 | 1,000,000 14 | 15 | Part IV. 16 | 17 | Is mergesort stable? 18 | Why or why not? 19 | 20 | Is quicksort stable? 21 | Why or why not? 22 | -------------------------------------------------------------------------------- /hw5/list/InvalidNodeException.java: -------------------------------------------------------------------------------- 1 | /* InvalidNodeException.java */ 2 | 3 | package hw5.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 | -------------------------------------------------------------------------------- /hw6/test.java: -------------------------------------------------------------------------------- 1 | package hw6; 2 | 3 | /** 4 | * Created by Meth on 1/11/15. 5 | */ 6 | public class test { 7 | public static void main(String[] args) { 8 | int sizeEstimate = 100; 9 | FOUND: 10 | for (int i = sizeEstimate; ; i++) { 11 | for (int j = 2; j < Math.sqrt(i); j++) { 12 | if (i % j == 0) { 13 | System.out.println(i + "%" + j); 14 | continue FOUND; 15 | } 16 | } 17 | System.out.println(i); 18 | break; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /hw6/dict/Entry.java: -------------------------------------------------------------------------------- 1 | /* Entry.java */ 2 | 3 | package hw6.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 | @Override 26 | public String toString() { 27 | return key + ": " + value; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /pj3/graphalg/Kruskal.java: -------------------------------------------------------------------------------- 1 | /* Kruskal.java */ 2 | 3 | package pj3.graphalg; 4 | 5 | import pj3.graph.WUGraph; 6 | 7 | /** 8 | * The Kruskal class contains the method minSpanTree(), which implements 9 | * Kruskal's algorithm for computing a minimum spanning tree of a graph. 10 | */ 11 | 12 | public class Kruskal { 13 | 14 | /** 15 | * minSpanTree() returns a WUGraph that represents the minimum spanning tree 16 | * of the WUGraph g. The original WUGraph g is NOT changed. 17 | * 18 | * @param g The weighted, undirected graph whose MST we want to compute. 19 | * @return A newly constructed WUGraph representing the MST of g. 20 | */ 21 | public static WUGraph minSpanTree(WUGraph g) { 22 | return new WUGraph(); 23 | } 24 | 25 | ; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /pj3/graph/InternalVertex.java: -------------------------------------------------------------------------------- 1 | package pj3.graph; 2 | 3 | import hw5.list.DList; 4 | import hw5.list.ListNode; 5 | 6 | /** 7 | * This file is created by @Muffin_C on 1/28/15 17:25. 8 | * This file is part of Project CS61B. 9 | */ 10 | public class InternalVertex { 11 | private Object name; 12 | public DList adjList; 13 | 14 | InternalVertex(Object vertex) { 15 | name = vertex; 16 | adjList = new DList(); 17 | } 18 | 19 | public int getDegree() { 20 | return adjList.length(); 21 | } 22 | 23 | public Object getVertexObject() { 24 | return name; 25 | } 26 | 27 | public ListNode addEdge(VertexPair pair) { 28 | adjList.insertFront(pair); 29 | return adjList.front(); 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return name.toString() + ": " + adjList.toString(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hw3/TestHelper.java: -------------------------------------------------------------------------------- 1 | /* TestHelper.java */ 2 | package hw3; 3 | 4 | /** 5 | * The purpose of this class is to provide a shorthand for writing and testing 6 | * invariants in any program. 7 | */ 8 | 9 | public class TestHelper { 10 | 11 | /** 12 | * verify() checks an invariant and prints an error message if it fails. 13 | * If invariant is true, this method does nothing. If invariant is false, 14 | * the message is printed, followed by a dump of the program stack. 15 | * 16 | * @param invariant the condition to be verified 17 | * @param message the error message to be printed if the invariant fails to 18 | * hold true. 19 | */ 20 | 21 | static void verify(boolean invariant, String message) { 22 | if (!invariant) { 23 | System.out.println("*** ERROR: " + message); 24 | Thread.dumpStack(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /hw4/list/DListNode.java: -------------------------------------------------------------------------------- 1 | /* DListNode.java */ 2 | 3 | package hw4.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 | * 26 | * @param i the item to store in the node. 27 | * @param p the node previous to this node. 28 | * @param n the node following this node. 29 | */ 30 | DListNode(Object i, DListNode p, DListNode n) { 31 | item = i; 32 | prev = p; 33 | next = n; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /hw3/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | package hw3; 3 | 4 | /** 5 | * SListNode is a class used internally by the SList class. An SList object 6 | * is a singly-linked list, and an SListNode is a node of a singly-linked 7 | * list. Each SListNode has two references: one to an object, and one to 8 | * the next node in the list. 9 | * 10 | * @author Kathy Yelick and Jonathan Shewchuk 11 | */ 12 | 13 | class SListNode { 14 | Object item; 15 | SListNode next; 16 | 17 | 18 | /** 19 | * SListNode() (with two parameters) constructs a list node referencing the 20 | * item "obj", whose next list node is to be "next". 21 | */ 22 | 23 | SListNode(Object obj, SListNode next) { 24 | item = obj; 25 | this.next = next; 26 | } 27 | 28 | /** 29 | * SListNode() (with one parameter) constructs a list node referencing the 30 | * item "obj". 31 | */ 32 | 33 | SListNode(Object obj) { 34 | this(obj, null); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /hw8/list/SListNode.java: -------------------------------------------------------------------------------- 1 | package hw8.list;/* hw8.list.SListNode.java */ 2 | 3 | /** 4 | * hw8.list.SListNode is a class used internally by the SList class. An SList object 5 | * is a singly-linked list, and an hw8.list.SListNode is a node of a singly-linked 6 | * list. Each hw8.list.SListNode has two references: one to an object, and one to 7 | * the next node in the list. 8 | */ 9 | 10 | class SListNode { 11 | Object item; 12 | SListNode next; 13 | 14 | /** 15 | * hw8.list.SListNode() (with one parameter) constructs a list node referencing the 16 | * item "obj". 17 | */ 18 | 19 | SListNode(Object obj) { 20 | item = obj; 21 | next = null; 22 | } 23 | 24 | /** 25 | * hw8.list.SListNode() (with two parameters) constructs a list node referencing the 26 | * item "obj", whose next list node is to be "next". 27 | */ 28 | 29 | SListNode(Object obj, SListNode next) { 30 | item = obj; 31 | this.next = next; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /pj3/graph/Neighbors.java: -------------------------------------------------------------------------------- 1 | /* Neighbors.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE. */ 4 | /* YOUR SUBMISSION MUST WORK CORRECTLY WITH _OUR_ COPY OF THIS FILE. */ 5 | 6 | package pj3.graph; 7 | 8 | import java.util.Arrays; 9 | 10 | /** 11 | * The Neighbors class is provided solely as a way to allow the method 12 | * WUGraph.getNeighbors() to return two arrays at once. Do NOT use this class 13 | * for any other purpose. 14 | *

15 | * Since this class is NOT an abstract data type, but is merely a collection of 16 | * data, all fields are public. 17 | */ 18 | 19 | public class Neighbors { 20 | public Object[] neighborList; 21 | public int[] weightList; 22 | 23 | @Override 24 | public String toString() { 25 | return Arrays.toString(neighborList) + "\n" + Arrays.toString(weightList); 26 | } 27 | 28 | public static void main(String[] args) { 29 | Neighbors n = new Neighbors(); 30 | n.neighborList = new Object[]{"123", 123}; 31 | System.out.println(n); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 2 | 3 | *.iml 4 | 5 | ## Directory-based project format: 6 | .idea/ 7 | # if you remove the above rule, at least ignore the following: 8 | 9 | # User-specific stuff: 10 | # .idea/workspace.xml 11 | # .idea/tasks.xml 12 | # .idea/dictionaries 13 | 14 | # Sensitive or high-churn files: 15 | # .idea/dataSources.ids 16 | # .idea/dataSources.xml 17 | # .idea/sqlDataSources.xml 18 | # .idea/dynamic.xml 19 | # .idea/uiDesigner.xml 20 | 21 | # Gradle: 22 | # .idea/gradle.xml 23 | # .idea/libraries 24 | 25 | # Mongo Explorer plugin: 26 | # .idea/mongoSettings.xml 27 | 28 | ## File-based project format: 29 | *.ipr 30 | *.iws 31 | 32 | ## Plugin-specific files: 33 | 34 | # IntelliJ 35 | out/ 36 | 37 | # mpeltonen/sbt-idea plugin 38 | .idea_modules/ 39 | 40 | # JIRA plugin 41 | atlassian-ide-plugin.xml 42 | 43 | # Crashlytics plugin (for Android Studio and IntelliJ) 44 | com_crashlytics_export_strings.xml 45 | crashlytics.properties 46 | crashlytics-build.properties -------------------------------------------------------------------------------- /pj3/graph/HashTableAuto.java: -------------------------------------------------------------------------------- 1 | package pj3.graph; 2 | 3 | import hw5.list.SList; 4 | import hw6.dict.Entry; 5 | 6 | /** 7 | * This file is created by @Muffin_C on 1/28/15 15:46. 8 | * This file is part of Project CS61B. 9 | */ 10 | public class HashTableAuto extends hw6.dict.HashTableChained { 11 | 12 | private double loadFactor() { 13 | return (double) entryNumber / hashSize; 14 | } 15 | 16 | private void doubleSize() { 17 | hashSize *= 2; 18 | SList[] oldList = hashList; 19 | arrayInit(); 20 | 21 | for (int i = 0; i < oldList.length; i++) { 22 | hashList[i] = oldList[i]; 23 | } 24 | } 25 | 26 | @Override 27 | public Entry insert(Object key, Object value) { 28 | Entry item = super.insert(key, value); 29 | 30 | if (loadFactor() > 1) { 31 | doubleSize(); 32 | } 33 | 34 | return item; 35 | } 36 | 37 | public static void main(String[] args) { 38 | System.out.println("test"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /hw4/list/TestHelper.java: -------------------------------------------------------------------------------- 1 | /* TestHelper.java */ 2 | package hw4.list; 3 | 4 | /** 5 | * This class is based on code from Arnow/Dexter/Weiss. Its verify() method 6 | * exits with an error message if an invariant fails to hold true. 7 | *

8 | * The purpose of this class is to provide a shorthand for writing and testing 9 | * invariants in any program. 10 | */ 11 | 12 | public class TestHelper { 13 | 14 | /** 15 | * verify() checks an invariant and prints an error message if it fails. 16 | * If invariant is true, this method does nothing. If invariant is false, 17 | * the message is printed, followed by a dump of the program call stack. 18 | * 19 | * @param invariant the condition to be verified 20 | * @param message the error message to be printed if the invariant fails to 21 | * hold true. 22 | */ 23 | 24 | static void verify(boolean invariant, String message) { 25 | if (!invariant) { 26 | System.out.println("*** ERROR: " + message); 27 | Thread.dumpStack(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /hw7/dict/IntDictionary.java: -------------------------------------------------------------------------------- 1 | /* IntDictionary.java */ 2 | 3 | package hw7.dict; 4 | 5 | /** 6 | * An IntDictionary is a mutable ordered dictionary ADT. Each item is an int 7 | * key; there are no additional values or objects associated with the key. 8 | *

9 | * DO NOT CHANGE THIS FILE. 10 | * 11 | * @author Jonathan Shewchuk 12 | */ 13 | 14 | public abstract class IntDictionary { 15 | 16 | /** 17 | * size is the number of items in the dictionary. 18 | */ 19 | 20 | protected int size; 21 | 22 | /** 23 | * isEmpty() returns true if this IntDictionary is empty, false otherwise. 24 | * 25 | * @return true if this IntDictionary is empty, false otherwise. 26 | *

27 | * Performance: runs in O(1) time. 28 | */ 29 | public boolean isEmpty() { 30 | return size == 0; 31 | } 32 | 33 | /** 34 | * size() returns the size of this IntDictionary. 35 | * 36 | * @return the size of this IntDictionary. 37 | *

38 | * Performance: runs in O(1) time. 39 | */ 40 | public int size() { 41 | return size; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /pj3/graph/InternalEdge.java: -------------------------------------------------------------------------------- 1 | package pj3.graph; 2 | 3 | import hw5.list.InvalidNodeException; 4 | import hw5.list.ListNode; 5 | 6 | /** 7 | * This file is created by @Muffin_C on 1/28/15 17:48. 8 | * This file is part of Project CS61B. 9 | */ 10 | public class InternalEdge { 11 | ListNode node1; 12 | ListNode node2; 13 | VertexPair pair; 14 | boolean self = true; 15 | int weight; 16 | 17 | 18 | protected InternalEdge(Object o1, Object o2, int weight) { 19 | pair = new VertexPair(o1, o2); 20 | this.weight = weight; 21 | } 22 | 23 | public void deleteMe() { 24 | try { 25 | if (!self) { 26 | node1.remove(); 27 | node2.remove(); 28 | } else { 29 | node1.remove(); 30 | } 31 | } catch (InvalidNodeException e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | @Override 37 | public int hashCode() { 38 | return pair.hashCode(); 39 | } 40 | 41 | @Override 42 | public boolean equals(Object o) { 43 | return pair.equals(o); 44 | } 45 | 46 | @Override 47 | public String toString() { 48 | return "{" + pair.toString() + "," + weight + "}"; 49 | } 50 | } -------------------------------------------------------------------------------- /pj2/player/Player.java: -------------------------------------------------------------------------------- 1 | /* Player.java */ 2 | 3 | package pj2.player; 4 | 5 | /** 6 | * A class that is extended by all Network players (human and machine). 7 | *

8 | * DO NOT CHANGE THIS FILE. 9 | */ 10 | public abstract class Player { 11 | // This player's name as recognized by the game Network. 12 | public String myName; 13 | 14 | // Returns a new move by "this" player. Internally records the move (updates 15 | // the internal game board) as a move by "this" player. 16 | public abstract Move chooseMove(); 17 | 18 | // If the Move m is legal, records the move as a move by the opponent 19 | // (updates the internal game board) and returns true. If the move is 20 | // illegal, returns false without modifying the internal state of "this" 21 | // player. This method allows your opponents to inform you of their moves. 22 | public abstract boolean opponentMove(Move m); 23 | 24 | // If the Move m is legal, records the move as a move by "this" player 25 | // (updates the internal game board) and returns true. If the move is 26 | // illegal, returns false without modifying the internal state of "this" 27 | // player. This method is used to help set up "Network problems" for your 28 | // player to solve. 29 | public abstract boolean forceMove(Move m); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /hw8/list/Queue.java: -------------------------------------------------------------------------------- 1 | /* Queue.java */ 2 | 3 | package hw8.list; 4 | 5 | public interface Queue { 6 | 7 | /** 8 | * size() returns the size of this Queue. 9 | * 10 | * @return the size of this Queue. 11 | * Performance: runs in O(1) time. 12 | */ 13 | public int size(); 14 | 15 | /** 16 | * isEmpty() returns true if this Queue is empty, false otherwise. 17 | * 18 | * @return true if this Queue is empty, false otherwise. 19 | * Performance: runs in O(1) time. 20 | */ 21 | public boolean isEmpty(); 22 | 23 | /** 24 | * enqueue() inserts an object at the end of the Queue. 25 | * 26 | * @param item the item to be enqueued. 27 | */ 28 | public void enqueue(Object item); 29 | 30 | /** 31 | * dequeue() removes and returns the object at the front of the Queue. 32 | * 33 | * @return the item dequeued. 34 | * @throws a hw8.list.QueueEmptyException if the Queue is empty. 35 | */ 36 | public Object dequeue() throws QueueEmptyException; 37 | 38 | /** 39 | * front() returns the object at the front of the Queue. 40 | * 41 | * @return the item at the front of the Queue. 42 | * @throws a hw8.list.QueueEmptyException if the Queue is empty. 43 | */ 44 | public Object front() throws QueueEmptyException; 45 | 46 | } 47 | -------------------------------------------------------------------------------- /hw4/list/LockDList.java: -------------------------------------------------------------------------------- 1 | package hw4.list; 2 | 3 | /** 4 | * Created by Meth on 1/8/15. 5 | */ 6 | public class LockDList extends DList { 7 | public LockDList() { 8 | head = newNode(null, null, null); 9 | head.next = head; 10 | head.prev = head; 11 | } 12 | 13 | public void lockNode(DListNode node) { 14 | ((LockDListNode) node).lockStatus = true; 15 | } 16 | 17 | @Override 18 | public void remove(DListNode node) { 19 | if (((LockDListNode) node).lockStatus) { 20 | System.out.println("locked"); 21 | return; 22 | } 23 | super.remove(node); 24 | } 25 | 26 | @Override 27 | protected LockDListNode newNode(Object item, DListNode prev, DListNode next) { 28 | return new LockDListNode(item, prev, next); 29 | } 30 | 31 | @Override 32 | public LockDListNode front() { 33 | return (LockDListNode) super.front(); 34 | } 35 | 36 | @Override 37 | public LockDListNode back() { 38 | return (LockDListNode) super.back(); 39 | } 40 | 41 | @Override 42 | public LockDListNode next(DListNode node) { 43 | return (LockDListNode) super.next(node); 44 | } 45 | 46 | @Override 47 | public LockDListNode prev(DListNode node) { 48 | return (LockDListNode) super.prev(node); 49 | } 50 | 51 | 52 | } 53 | -------------------------------------------------------------------------------- /hw8/Timer.java: -------------------------------------------------------------------------------- 1 | /* Timer.java */ 2 | 3 | /** 4 | * Implements a simple stopwatch/timer class based on wall-clock time. 5 | **/ 6 | package hw8; 7 | 8 | /** 9 | * RUNNING() == true <==> start() called with no corresponding 10 | * call to stop() 11 | *

12 | * All times are given in units of msec. 13 | */ 14 | public class Timer { 15 | 16 | private boolean running; 17 | private long tStart; 18 | private long tFinish; 19 | private long tAccum; 20 | 21 | /** 22 | * Initializes Timer to 0 msec 23 | */ 24 | public Timer() { 25 | reset(); 26 | } 27 | 28 | /** 29 | * Starts the timer. Accumulates time across multiple calls to start. 30 | */ 31 | public void start() { 32 | running = true; 33 | tStart = System.currentTimeMillis(); 34 | tFinish = tStart; 35 | } 36 | 37 | /** 38 | * Stops the timer. returns the time elapsed since the last matching call 39 | * to start(), or zero if no such matching call was made. 40 | */ 41 | public long stop() { 42 | tFinish = System.currentTimeMillis(); 43 | if (running) { 44 | running = false; 45 | 46 | long diff = tFinish - tStart; 47 | tAccum += diff; 48 | return diff; 49 | } 50 | return 0; 51 | } 52 | 53 | /** 54 | * if RUNNING() ==> returns the time since last call to start() 55 | * if !RUNNING() ==> returns total elapsed time 56 | */ 57 | public long elapsed() { 58 | if (running) { 59 | return System.currentTimeMillis() - tStart; 60 | } 61 | 62 | return tAccum; 63 | } 64 | 65 | /** 66 | * Stops timing, if currently RUNNING(); resets 67 | * accumulated time to 0. 68 | */ 69 | public void reset() { 70 | running = false; 71 | tStart = 0; 72 | tFinish = 0; 73 | tAccum = 0; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /pj2/player/Move.java: -------------------------------------------------------------------------------- 1 | /* Move.java */ 2 | 3 | package pj2.player; 4 | 5 | /** 6 | * A public class for holding all the fields in a move. This class is a 7 | * container for data, not an ADT; hence, all fields are public. 8 | *

9 | * The moveKind field stores the type of move. The x-coordinates index the 10 | * horizontal direction (left to right) and the y-coordinates index the 11 | * vertical direction (top to bottom). x- and y-coordinates start at zero. 12 | *

13 | * DO NOT CHANGE THIS FILE. 14 | */ 15 | public class Move { 16 | 17 | public final static int QUIT = 0; 18 | public final static int ADD = 1; 19 | public final static int STEP = 2; 20 | 21 | public int moveKind; // ADD, STEP, or QUIT. 22 | 23 | public int x1; // If moveKind == ADD, then x1, y1 are the new 24 | public int y1; // position in which a chip is being added; 25 | public int x2; // x2, y2 are unused. 26 | public int y2; // If moveKind == STEP, then x1, y1 are the new 27 | // position, and x2, y2 are the old position 28 | // of the chip. 29 | // If moveKind == QUIT, then x1, x2, y1, y2 are unused. 30 | 31 | // Construct a step move. 32 | public Move(int xx1, int yy1, int xx2, int yy2) { 33 | moveKind = STEP; 34 | x1 = xx1; 35 | x2 = xx2; 36 | y1 = yy1; 37 | y2 = yy2; 38 | } 39 | 40 | // Construct an add move. 41 | public Move(int x, int y) { 42 | moveKind = ADD; 43 | x1 = x; 44 | y1 = y; 45 | } 46 | 47 | // Construct a quit move. 48 | public Move() { 49 | moveKind = QUIT; 50 | } 51 | 52 | // toString() converts the move to a String. 53 | public String toString() { 54 | switch (moveKind) { 55 | case QUIT: 56 | return "[quit]"; 57 | case ADD: 58 | return "[add to " + x1 + "" + y1 + "]"; 59 | default: 60 | return "[step from " + x2 + "" + y2 + " to " + x1 + "" + y1 + "]"; 61 | } 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /hw5/list/List.java: -------------------------------------------------------------------------------- 1 | /* List.java */ 2 | 3 | package hw5.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 | -------------------------------------------------------------------------------- /pj3/graph/VertexPair.java: -------------------------------------------------------------------------------- 1 | /* VertexPair.java */ 2 | 3 | package pj3.graph; 4 | 5 | /** 6 | * The VertexPair represents a pair of objects that act as vertices in a 7 | * WUGraph (weighted, undirected graph). The purpose of a VertexPair is to 8 | * act as a key for Java's hashCode() and equals() functions. It is designed 9 | * so that the order of the two objects is immaterial; (u, v) is the same as 10 | * (v, u). 11 | */ 12 | 13 | class VertexPair { 14 | protected Object object1; 15 | protected Object object2; 16 | 17 | protected VertexPair(Object o1, Object o2) { 18 | object1 = o1; 19 | object2 = o2; 20 | } 21 | 22 | /** 23 | * hashCode() returns a hashCode equal to the sum of the hashCodes of each 24 | * of the two objects of the pair, so that the order of the objects will 25 | * not affect the hashCode. Self-edges are treated differently: we don't 26 | * add an object's hashCode to itself, since the result would always be even. 27 | * We add one to the hashCode so that a self-edge will not collide with the 28 | * object itself if vertices and edges are stored in the same hash table. 29 | */ 30 | public int hashCode() { 31 | if (object1.equals(object2)) { 32 | return object1.hashCode() + 1; 33 | } else { 34 | return object1.hashCode() + object2.hashCode(); 35 | } 36 | } 37 | 38 | /** 39 | * equals() returns true if this VertexPair represents the same unordered 40 | * pair of objects as the parameter "o". The order of the pair does not 41 | * affect the equality test, so (u, v) is found to be equal to (v, u). 42 | */ 43 | public boolean equals(Object o) { 44 | if (o instanceof VertexPair) { 45 | return ((object1.equals(((VertexPair) o).object1)) && 46 | (object2.equals(((VertexPair) o).object2))) || 47 | ((object1.equals(((VertexPair) o).object2)) && 48 | (object2.equals(((VertexPair) o).object1))); 49 | } else { 50 | return false; 51 | } 52 | } 53 | 54 | public Object theOther(Object object) { 55 | return object.equals(object1) ? object2 : object1; 56 | } 57 | 58 | @Override 59 | public String toString() { 60 | return "(" + object1 + "|" + object2 + ")"; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /hw6/dict/Dictionary.java: -------------------------------------------------------------------------------- 1 | /* Dictionary.java */ 2 | 3 | package hw6.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 | * 18 | * @return number of entries in the dictionary. 19 | */ 20 | 21 | public int size(); 22 | 23 | /** 24 | * Tests if the dictionary is empty. 25 | * 26 | * @return true if the dictionary has no entries; false otherwise. 27 | */ 28 | 29 | public boolean isEmpty(); 30 | 31 | /** 32 | * Create a new Entry object referencing the input key and associated value, 33 | * and insert the entry into the dictionary. Return a reference to the new 34 | * entry. Multiple entries with the same key (or even the same key and 35 | * value) can coexist in the dictionary. 36 | * 37 | * @param key the key by which the entry can be retrieved. 38 | * @param value an arbitrary object. 39 | * @return an entry containing the key and value. 40 | */ 41 | 42 | public Entry insert(Object key, Object value); 43 | 44 | /** 45 | * Search for an entry with the specified key. If such an entry is found, 46 | * return it; otherwise return null. If several entries have the specified 47 | * key, choose one arbitrarily and return it. 48 | * 49 | * @param key the search key. 50 | * @return an entry containing the key and an associated value, or null if 51 | * no entry contains the specified key. 52 | */ 53 | 54 | public Entry find(Object key); 55 | 56 | /** 57 | * Remove an entry with the specified key. If such an entry is found, 58 | * remove it from the table and return it; otherwise return null. 59 | * If several entries have the specified key, choose one arbitrarily, then 60 | * remove and return it. 61 | * 62 | * @param key the search key. 63 | * @return an entry containing the key and an associated value, or null if 64 | * no entry contains the specified key. 65 | */ 66 | 67 | public Entry remove(Object key); 68 | 69 | /** 70 | * Remove all entries from the dictionary. 71 | */ 72 | 73 | public void makeEmpty(); 74 | 75 | } 76 | -------------------------------------------------------------------------------- /hw6/Homework6Test.java: -------------------------------------------------------------------------------- 1 | /* Homework6Test.java */ 2 | package hw6; 3 | 4 | import hw6.dict.*; 5 | 6 | /** 7 | * Initializes a hash table, then stocks it with random SimpleBoards. 8 | */ 9 | 10 | public class Homework6Test { 11 | 12 | /** 13 | * Generates a random 8 x 8 SimpleBoard. 14 | */ 15 | 16 | private static SimpleBoard randomBoard() { 17 | SimpleBoard board = new SimpleBoard(); 18 | for (int y = 0; y < 8; y++) { 19 | for (int x = 0; x < 8; x++) { 20 | double fval = Math.random() * 12; 21 | int value = (int) fval; 22 | board.setElementAt(x, y, value); 23 | } 24 | } 25 | return board; 26 | } 27 | 28 | /** 29 | * Empties the given table, then inserts "numBoards" boards into the table. 30 | * 31 | * @param table is the hash table to be initialized. 32 | * @param numBoards is the number of random boards to place in the table. 33 | */ 34 | 35 | public static void initTable(HashTableChained table, int numBoards) { 36 | table.makeEmpty(); 37 | for (int i = 0; i < numBoards; i++) { 38 | table.insert(randomBoard(), new Integer(i)); 39 | } 40 | } 41 | 42 | /** 43 | * Creates a hash table and stores a certain number of SimpleBoards in it. 44 | * The number is 100 by default, but you can specify any number at the 45 | * command line. For example: 46 | *

47 | * java Homework6Test 12000 48 | */ 49 | 50 | public static void main(String[] args) { 51 | int numBoards; 52 | 53 | if (args.length == 0) { 54 | numBoards = 100; 55 | } else { 56 | numBoards = Integer.parseInt(args[0]); 57 | } 58 | HashTableChained table = new HashTableChained(numBoards); 59 | initTable(table, numBoards); 60 | 61 | // To test your hash function, add a method to your HashTableChained class 62 | // that counts the number of collisions--or better yet, also prints 63 | // a histograph of the number of entries in each bucket. Call this method 64 | // from here. 65 | System.out.println("n = " + numBoards + " N = " + table.hashSize); 66 | System.out.println("Actual number of collisions: " + table.collision); 67 | System.out.printf("Expected number of collisions: %.2f%n", HashTableChained.expectedRate(numBoards, table.size())); 68 | 69 | numBoards = 500; 70 | table = new HashTableChained(numBoards); 71 | initTable(table, numBoards); 72 | System.out.println("n = " + numBoards + " N = " + table.hashSize); 73 | System.out.println("Actual number of collisions: " + table.collision); 74 | System.out.printf("Expected number of collisions: %.2f%n", HashTableChained.expectedRate(numBoards, table.size())); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /pj2/GRADER.txt: -------------------------------------------------------------------------------- 1 | GRADER 2 | 3 | Name of student running submit: 4 | Login of student running submit: 5 | 6 | Second team member's name: 7 | Second team member's login: 8 | 9 | Third team member's name (if any): 10 | Third team member's login: 11 | 12 | IMPORTANT: Once you've submitted Project 2 once, the same team member should 13 | submit always. If a different teammate must submit, inform cs61b@cory.eecs of 14 | all the details. Include a complete list of team members, and let us know 15 | which submission you want graded. 16 | 17 | If you've submitted your project once, or even written a substantial amount of 18 | code together, you may not change partners without the permission of the 19 | instructor. 20 | =============================================================================== 21 | Does your program compile without errors? 22 | 23 | 24 | Have you tested your program on the 61B lab machines? 25 | 26 | 27 | Did you successfully implement game tree search? Did you successfully 28 | implement alpha-beta pruning? Are there any limitations on it? What is the 29 | default number of search levels set by the one-parameter MachinePlayer 30 | constructor (or is it a variable-depth search)? 31 | 32 | 33 | Describe your board evaluation function in some detail. 34 | 35 | 36 | Does your MachinePlayer use any special method of choosing the first few moves? 37 | 38 | 39 | Is there anything else the graders should know to help them read your project? 40 | 41 | 42 | 43 | Describe the classes, modules, and interfaces you designed before and while you 44 | implemented the project. Your description should include: 45 | - A list of the classes your program uses. 46 | - A list of each of the "modules" used in or by MachinePlayer, similar to 47 | the list in the "Teamwork" section of the README (but hopefully more 48 | detailed). (If you're using a list class, that should probably count as 49 | a separate module.) 50 | - For each module, list the class(es) the module is implemented in. 51 | - For each module, say which of your team members implemented it. 52 | - For each module, describe its interface--specifically, the prototype and 53 | behavior of each method that is available for external callers (outside 54 | the module) to call. Don't include methods that are only meant to be 55 | called from within the module. 56 | 57 | For each method, provide (1) a method prototype and (2) a complete, 58 | unambiguous description of the behavior of the method/module. This 59 | description should also appear before the method in your code's comments. 60 | 61 | You will probably need to change some of your design decisions as you go; be 62 | sure to modify this file to reflect these changes before you submit your 63 | project. Your design of classes and interfaces will be worth 10% of your 64 | grade. 65 | -------------------------------------------------------------------------------- /hw5/list/ListNode.java: -------------------------------------------------------------------------------- 1 | /* ListNode.java */ 2 | 3 | package hw5.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 | * @throws 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 | * @throws 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 | * @throws 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 | * @throws 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 | * @throws InvalidNodeException if this node is not valid. 106 | */ 107 | public abstract void remove() throws InvalidNodeException; 108 | 109 | } 110 | -------------------------------------------------------------------------------- /pj3/set/DisjointSets.java: -------------------------------------------------------------------------------- 1 | /* DisjointSets.java */ 2 | 3 | package pj3.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 | */ 43 | public void union(int root1, int root2) { 44 | if (array[root2] < array[root1]) { // root2 has larger tree 45 | array[root2] += array[root1]; // update # of items in root2's tree 46 | array[root1] = root2; // make root2 new root 47 | } else { // root1 has equal or larger tree 48 | array[root1] += array[root2]; // update # of items in root1's tree 49 | array[root2] = root1; // make root1 new root 50 | } 51 | } 52 | 53 | /** 54 | * find() finds the (int) name of the set containing a given element. 55 | * Performs path compression along the way. 56 | * 57 | * @param x the element sought. 58 | * @return the set containing x. 59 | */ 60 | public int find(int x) { 61 | if (array[x] < 0) { 62 | return x; // x is the root of the tree; return it 63 | } else { 64 | // Find out who the root is; compress path by making the root x's parent. 65 | array[x] = find(array[x]); 66 | return array[x]; // Return the root 67 | } 68 | } 69 | 70 | /** 71 | * main() is test code. All the find()s on the same output line should be 72 | * identical. 73 | */ 74 | public static void main(String[] args) { 75 | int NumElements = 128; 76 | int NumInSameSet = 16; 77 | 78 | DisjointSets s = new DisjointSets(NumElements); 79 | int set1, set2; 80 | 81 | for (int k = 1; k < NumInSameSet; k *= 2) { 82 | for (int j = 0; j + k < NumElements; j += 2 * k) { 83 | set1 = s.find(j); 84 | set2 = s.find(j + k); 85 | s.union(set1, set2); 86 | } 87 | } 88 | 89 | for (int i = 0; i < NumElements; i++) { 90 | System.out.print(s.find(i) + "*"); 91 | if (i % NumInSameSet == NumInSameSet - 1) { 92 | System.out.println(); 93 | } 94 | } 95 | System.out.println(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /pj1/Blur.java: -------------------------------------------------------------------------------- 1 | /* Blur.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE. */ 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 | package pj1; 11 | 12 | 13 | /** 14 | * The Blur class is a program that reads an image file in TIFF format, blurs 15 | * it with a 3x3 box blurring kernel, writes the blurred image as a TIFF file, 16 | * and displays both images. 17 | *

18 | * The Blur program takes up to two parameters. The first parameter is 19 | * the name of the TIFF-format file to read. (The output image file is 20 | * constructed by adding "blur_" to the beginning of the input filename.) 21 | * An optional second parameter specifies the number of iterations of the 22 | * box blurring operation. (The default is one iteration.) For example, if 23 | * you run 24 | *

25 | * java Blur engine.tiff 5 26 | *

27 | * then Blur will read engine.tiff, perform 5 iterations of blurring, and 28 | * write the blurred image to blur_engine.tiff . 29 | * 30 | * @author Joel Galenson and Jonathan Shewchuk 31 | */ 32 | 33 | public class Blur { 34 | 35 | /** 36 | * blurFile() reads a TIFF image file, blurs it, write the blurred image to 37 | * a new TIFF image file, and displays both images. 38 | * 39 | * @param filename the name of the input TIFF image file. 40 | * @param numIterations the number of iterations of blurring to perform. 41 | */ 42 | private static void blurFile(String filename, int numIterations) { 43 | System.out.println("Reading image file " + filename); 44 | PixImage image = ImageUtils.readTIFFPix(filename); 45 | 46 | System.out.println("Blurring image file."); 47 | PixImage blurred = image.boxBlur(numIterations); 48 | 49 | String blurname = "blur_" + filename; 50 | System.out.println("Writing blurred image file " + blurname); 51 | // TIFFEncoder.writeTIFF(blurred, blurname); 52 | /* 53 | TIFFEncoder.writeTIFF(new RunLengthEncoding(edges), "rle" + blurname); 54 | */ 55 | 56 | System.out.println("Displaying input image and blurred image."); 57 | System.out.println("Close the image to quit."); 58 | ImageUtils.displayTIFFs(new PixImage[]{image, blurred}); 59 | } 60 | 61 | /** 62 | * main() reads the command-line arguments and initiates the blurring. 63 | *

64 | * The first command-line argument is the name of the image file. 65 | * An optional second argument is number of iterations of blurring. 66 | * 67 | * @param args the usual array of command-line argument Strings. 68 | */ 69 | public static void main(String[] args) { 70 | String[] test = {"pj1/feathers.tiff", "-9"}; 71 | args = test; 72 | if (args.length == 0) { 73 | System.out.println("usage: java Blur imagefile [iterations]"); 74 | System.out.println(" imagefile is an image in TIFF format."); 75 | System.out.println(" interations is the number of blurring iterations" + 76 | " (default 1)."); 77 | System.out.println("The blurred image is written to blur_imagefile."); 78 | System.exit(0); 79 | } 80 | 81 | int numIterations = 1; 82 | if (args.length > 1) { 83 | try { 84 | numIterations = Integer.parseInt(args[1]); 85 | } catch (NumberFormatException ex) { 86 | System.err.println("The second argument must be a number."); 87 | System.exit(1); 88 | } 89 | } 90 | 91 | blurFile(args[0], numIterations); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /hw8/list/LinkedQueue.java: -------------------------------------------------------------------------------- 1 | /* LinkedQueue.java */ 2 | 3 | package hw8.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 | * 23 | * @return the size of this Queue. 24 | * Performance: runs in O(1) time. 25 | */ 26 | public int size() { 27 | return size; 28 | } 29 | 30 | /** 31 | * isEmpty() returns true if this Queue is empty, false otherwise. 32 | * 33 | * @return true if this Queue is empty, false otherwise. 34 | * Performance: runs in O(1) time. 35 | */ 36 | public boolean isEmpty() { 37 | return size == 0; 38 | } 39 | 40 | /** 41 | * enqueue() inserts an object at the end of the Queue. 42 | * 43 | * @param item the item to be enqueued. 44 | */ 45 | public void enqueue(Object item) { 46 | if (head == null) { 47 | head = new SListNode(item); 48 | tail = head; 49 | } else { 50 | tail.next = new SListNode(item); 51 | tail = tail.next; 52 | } 53 | size++; 54 | } 55 | 56 | /** 57 | * dequeue() removes and returns the object at the front of the Queue. 58 | * 59 | * @return the item dequeued. 60 | * @throws hw8.list.QueueEmptyException if the Queue is empty. 61 | */ 62 | public Object dequeue() throws QueueEmptyException { 63 | if (head == null) { 64 | throw new QueueEmptyException(); 65 | } else { 66 | Object o = head.item; 67 | head = head.next; 68 | size--; 69 | if (size == 0) { 70 | tail = null; 71 | } 72 | return o; 73 | } 74 | } 75 | 76 | /** 77 | * front() returns the object at the front of the Queue. 78 | * 79 | * @return the item at the front of the Queue. 80 | * @throws hw8.list.QueueEmptyException if the Queue is empty. 81 | */ 82 | public Object front() throws QueueEmptyException { 83 | if (head == null) { 84 | throw new QueueEmptyException(); 85 | } else { 86 | return head.item; 87 | } 88 | } 89 | 90 | /** 91 | * nth() returns the nth item in this LinkedQueue. 92 | * Items in the queue are numbered from 1. 93 | * 94 | * @param n the number of the item to return. 95 | */ 96 | public Object nth(int n) { 97 | SListNode node = head; 98 | for (; n > 1; n--) { 99 | node = node.next; 100 | } 101 | return node.item; 102 | } 103 | 104 | /** 105 | * append() appends the contents of q onto the end of this LinkedQueue. 106 | * On completion, q is empty. 107 | * 108 | * @param q the LinkedQueue whose contents should be appended onto this 109 | * LinkedQueue. 110 | */ 111 | public void append(LinkedQueue q) { 112 | if (head == null) { 113 | head = q.head; 114 | } else { 115 | tail.next = q.head; 116 | } 117 | if (q.head != null) { 118 | tail = q.tail; 119 | } 120 | size = size + q.size; 121 | q.head = null; 122 | q.tail = null; 123 | q.size = 0; 124 | } 125 | 126 | /** 127 | * toString() converts this queue to a String. 128 | */ 129 | public String toString() { 130 | String out = "[ "; 131 | try { 132 | for (int i = 0; i < size(); i++) { 133 | out = out + front() + " "; 134 | enqueue(dequeue()); 135 | } 136 | } catch (QueueEmptyException uf) { 137 | System.err.println("Error: attempt to dequeue from empty queue."); 138 | } 139 | return out + "]"; 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /hw9/set/DisjointSets.java: -------------------------------------------------------------------------------- 1 | /* DisjointSets.java */ 2 | 3 | package hw9.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 | */ 43 | public void union(int root1, int root2) { 44 | // error checking 45 | if (array[root1] >= 0 || array[root2] >= 0) { 46 | System.out.println("root1 >= 0 || root2 >= 0"); 47 | Thread.dumpStack(); 48 | System.exit(0); 49 | } 50 | 51 | if (isSameSet(root1, root2)) { 52 | System.out.println("Same Set!!!!!!!!"); 53 | return; 54 | } 55 | 56 | if (array[root2] < array[root1]) { // root2 has larger tree 57 | array[root2] += array[root1]; // update # of items in root2's tree 58 | array[root1] = root2; // make root2 new root 59 | } else { // root1 has equal or larger tree 60 | array[root1] += array[root2]; // update # of items in root1's tree 61 | array[root2] = root1; // make root1 new root 62 | } 63 | } 64 | 65 | public boolean isSameSet(int root1, int root2) { 66 | return find(root1) == find(root2); 67 | } 68 | 69 | /** 70 | * find() finds the (int) name of the set containing a given element. 71 | * Performs path compression along the way. 72 | * 73 | * @param x the element sought. 74 | * @return the set containing x. 75 | */ 76 | public int find(int x) { 77 | if (array[x] < 0) { 78 | return x; // x is the root of the tree; return it 79 | } else { 80 | // Find out who the root is; compress path by making the root x's parent. 81 | array[x] = find(array[x]); 82 | return array[x]; // Return the root 83 | } 84 | } 85 | 86 | /** 87 | * main() is test code. All the find()s on the same output line should be 88 | * identical. 89 | */ 90 | public static void main(String[] args) { 91 | int NumElements = 128; 92 | int NumInSameSet = 16; 93 | 94 | DisjointSets s = new DisjointSets(NumElements); 95 | int set1, set2; 96 | 97 | for (int k = 1; k < NumInSameSet; k *= 2) { 98 | for (int j = 0; j + k < NumElements; j += 2 * k) { 99 | set1 = s.find(j); 100 | set2 = s.find(j + k); 101 | s.union(set1, set2); 102 | } 103 | } 104 | 105 | for (int i = 0; i < NumElements; i++) { 106 | System.out.print(s.find(i) + "*"); 107 | if (i % NumInSameSet == NumInSameSet - 1) { 108 | System.out.println(); 109 | } 110 | } 111 | System.out.println(); 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /hw7/dict/Tree234Node.java: -------------------------------------------------------------------------------- 1 | /* Tree234Node.java */ 2 | 3 | package hw7.dict; 4 | 5 | /** 6 | * A Tree234Node is a node in a 2-3-4 tree (Tree234 class). 7 | *

8 | * DO NOT CHANGE ANYTHING IN THIS FILE. 9 | * You may add helper methods and additional constructors, though. 10 | */ 11 | class Tree234Node { 12 | 13 | /** 14 | * keys is the number of keys in this node. Always 1, 2, or 3. 15 | * key1 through key3 are the keys of this node. If keys == 1, the value 16 | * of key2 doesn't matter. If keys < 3, the value of key3 doesn't matter. 17 | * parent is this node's parent; null if this is the root. 18 | * child1 through child4 are the children of this node. If this is a leaf 19 | * node, they must all be set to null. If this node has no third and/or 20 | * fourth child, child3 and/or child4 must be set to null. 21 | */ 22 | int keys; 23 | int key1; 24 | int key2; 25 | int key3; 26 | Tree234Node parent; 27 | Tree234Node child1; 28 | Tree234Node child2; 29 | Tree234Node child3; 30 | Tree234Node child4; 31 | 32 | Tree234Node(Tree234Node p, int key) { 33 | keys = 1; 34 | key1 = key; 35 | parent = p; 36 | child1 = null; 37 | child2 = null; 38 | child3 = null; 39 | child4 = null; 40 | } 41 | 42 | public void insertKey(int key) { 43 | if (key <= this.key1) { 44 | this.key3 = this.key2; 45 | this.key2 = this.key1; 46 | this.key1 = key; 47 | } else if ((this.keys == 1) || (key <= this.key2)) { 48 | this.key3 = this.key2; 49 | this.key2 = key; 50 | } else { 51 | this.key3 = key; 52 | } 53 | this.keys++; 54 | } 55 | 56 | /** 57 | * toString() recursively prints this Tree234Node and its descendants as 58 | * a String. Each node is printed in the form such as (for a 3-key node) 59 | *

60 | * (child1)key1(child2)key2(child3)key3(child4) 61 | *

62 | * where each child is a recursive call to toString, and null children 63 | * are printed as a space with no parentheses. Here's an example. 64 | * ((1)7(11 16)22(23)28(37 49))50((60)84(86 95 100)) 65 | *

66 | * DO NOT CHANGE THIS METHOD. 67 | */ 68 | public String toString() { 69 | String s = ""; 70 | 71 | if (child1 != null) { 72 | s = "(" + child1.toString() + ")"; 73 | } 74 | s = s + key1; 75 | if (child2 != null) { 76 | s = s + "(" + child2.toString() + ")"; 77 | } else if (keys > 1) { 78 | s = s + " "; 79 | } 80 | if (keys > 1) { 81 | s = s + key2; 82 | if (child3 != null) { 83 | s = s + "(" + child3.toString() + ")"; 84 | } else if (keys > 2) { 85 | s = s + " "; 86 | } 87 | } 88 | if (keys > 2) { 89 | s = s + key3; 90 | if (child4 != null) { 91 | s = s + "(" + child4.toString() + ")"; 92 | } 93 | } 94 | return s; 95 | } 96 | 97 | /** 98 | * printSubtree() recursively prints this Tree234Node and its descendants as 99 | * a tree (albeit sideways). 100 | *

101 | * You're welcome to change this method if you like. It won't be tested. 102 | */ 103 | public void printSubtree(int spaces) { 104 | if (child4 != null) { 105 | child4.printSubtree(spaces + 5); 106 | } 107 | if (keys == 3) { 108 | for (int i = 0; i < spaces; i++) { 109 | System.out.print(" "); 110 | } 111 | System.out.println(key3); 112 | } 113 | 114 | if (child3 != null) { 115 | child3.printSubtree(spaces + 5); 116 | } 117 | if (keys > 1) { 118 | for (int i = 0; i < spaces; i++) { 119 | System.out.print(" "); 120 | } 121 | System.out.println(key2); 122 | } 123 | 124 | if (child2 != null) { 125 | child2.printSubtree(spaces + 5); 126 | } 127 | for (int i = 0; i < spaces; i++) { 128 | System.out.print(" "); 129 | } 130 | System.out.println(key1); 131 | 132 | if (child1 != null) { 133 | child1.printSubtree(spaces + 5); 134 | } 135 | } 136 | 137 | public static void main(String[] args) { 138 | Tree234Node node1 = new Tree234Node(null, 5); 139 | Tree234Node node2 = new Tree234Node(node1, 1); 140 | node1.printSubtree(1); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /hw10/sort/Sorts.java: -------------------------------------------------------------------------------- 1 | /* Sorts.java */ 2 | 3 | package hw10.sort; 4 | 5 | import java.util.Arrays; 6 | 7 | public class Sorts { 8 | 9 | /** 10 | * Place any final static fields you would like to have here. 11 | **/ 12 | 13 | 14 | /** 15 | * countingSort() sorts an array of int keys according to the 16 | * values of _one_ of the base-16 digits of each key. "whichDigit" 17 | * indicates which digit is the sort key. A zero means sort on the least 18 | * significant (ones) digit; a one means sort on the second least 19 | * significant (sixteens) digit; and so on, up to a seven, which means 20 | * sort on the most significant digit. 21 | * 22 | * @param keys is an array of ints. Assume no key is negative. 23 | * @param whichDigit is a number in 0...7 specifying which base-16 digit 24 | * is the sort key. 25 | * @return an array of type int, having the same length as "keys" 26 | * and containing the same keys sorted according to the chosen digit. 27 | *

28 | * Note: Return a _newly_ created array. DO NOT CHANGE THE ARRAY keys. 29 | */ 30 | public static int[] countingSort(int[] keys, int whichDigit) { 31 | int[] output = new int[keys.length]; 32 | int[] digits = new int[keys.length]; 33 | 34 | int[] counts = new int[16]; 35 | 36 | for (int i = 0; i < keys.length; i++) { 37 | digits[i] = keys[i] >> whichDigit & 15; 38 | counts[digits[i]]++; 39 | } 40 | 41 | int total = 0; 42 | for (int i = 0; i < counts.length; i++) { 43 | int foo = counts[i]; 44 | counts[i] = total; 45 | total += foo; 46 | } 47 | 48 | for (int i = 0; i < keys.length; i++) { 49 | output[counts[digits[i]]++] = keys[i]; 50 | } 51 | 52 | // Replace the following line with your solution. 53 | return output; 54 | } 55 | 56 | /** 57 | * radixSort() sorts an array of int keys (using all 32 bits 58 | * of each key to determine the ordering). 59 | * 60 | * @param keys is an array of ints. Assume no key is negative. 61 | * @return an array of type int, having the same length as "keys" 62 | * and containing the same keys in sorted order. 63 | *

64 | * Note: Return a _newly_ created array. DO NOT CHANGE THE ARRAY keys. 65 | */ 66 | public static int[] radixSort(int[] keys) { 67 | int[] output = Arrays.copyOf(keys,keys.length); 68 | 69 | 70 | for (int i = 0; i < 32; i++) { 71 | output = countingSort(output, i); 72 | } 73 | // Replace the following line with your solution. 74 | return output; 75 | } 76 | 77 | /** 78 | * yell() prints an array of int keys. Each key is printed in hexadecimal 79 | * (base 16). 80 | * 81 | * @param keys is an array of ints. 82 | */ 83 | public static void yell(int[] keys) { 84 | System.out.print("keys are [ "); 85 | for (int i = 0; i < keys.length; i++) { 86 | System.out.print(Integer.toString(keys[i], 16) + " "); 87 | } 88 | System.out.println("]"); 89 | } 90 | 91 | /** 92 | * main() creates and sorts a sample array. 93 | * We recommend you add more tests of your own. 94 | * Your test code will not be graded. 95 | */ 96 | public static void main(String[] args) { 97 | int[] keys = {Integer.parseInt("60013879", 16), 98 | Integer.parseInt("11111119", 16), 99 | Integer.parseInt("2c735010", 16), 100 | Integer.parseInt("2c732010", 16), 101 | Integer.parseInt("7fffffff", 16), 102 | Integer.parseInt("4001387c", 16), 103 | Integer.parseInt("10111119", 16), 104 | Integer.parseInt("529a7385", 16), 105 | Integer.parseInt("1e635010", 16), 106 | Integer.parseInt("28905879", 16), 107 | Integer.parseInt("00011119", 16), 108 | Integer.parseInt("00000000", 16), 109 | Integer.parseInt("7c725010", 16), 110 | Integer.parseInt("1e630010", 16), 111 | Integer.parseInt("111111e5", 16), 112 | Integer.parseInt("61feed0c", 16), 113 | Integer.parseInt("3bba7387", 16), 114 | Integer.parseInt("52953fdb", 16), 115 | Integer.parseInt("40013879", 16)}; 116 | 117 | yell(keys); 118 | keys = radixSort(keys); 119 | yell(keys); 120 | 121 | int[] foo = new int[] {10,7,6,5,4,3,2,1,6,5,4,7,3,4,3,4,5,6,7,8,9,7,11,2,33,44,55}; 122 | System.out.println(Arrays.toString(radixSort(foo))); 123 | 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /hw6/SimpleBoard.java: -------------------------------------------------------------------------------- 1 | /* SimpleBoard.java */ 2 | 3 | package hw6; 4 | 5 | import java.math.BigInteger; 6 | import java.util.Random; 7 | 8 | /** 9 | * Simple class that implements an 8x8 game board with three possible values 10 | * for each cell: 0, 1 or 2. 11 | *

12 | * DO NOT CHANGE ANY PROTOTYPES IN THIS FILE. 13 | */ 14 | 15 | public class SimpleBoard { 16 | private final static int DIMENSION = 8; 17 | private int[][] grid; 18 | 19 | /** 20 | * Invariants: 21 | * (1) grid.length == DIMENSION. 22 | * (2) for all 0 <= i < DIMENSION, grid[i].length == DIMENSION. 23 | * (3) for all 0 <= i, j < DIMENSION, grid[i][j] >= 0 and grid[i][j] <= 2. 24 | **/ 25 | 26 | /** 27 | * Construct a new board in which all cells are zero. 28 | */ 29 | 30 | public SimpleBoard() { 31 | grid = new int[DIMENSION][DIMENSION]; 32 | } 33 | 34 | /** 35 | * Set the cell (x, y) in the board to the given value mod 3. 36 | * 37 | * @param value to which the element should be set (normally 0, 1, or 2). 38 | * @param x is the x-index. 39 | * @param y is the y-index. 40 | * @throws ArrayIndexOutOfBoundsException is thrown if an invalid index 41 | * is given. 42 | */ 43 | 44 | public void setElementAt(int x, int y, int value) { 45 | grid[x][y] = value % 3; 46 | if (grid[x][y] < 0) { 47 | grid[x][y] = grid[x][y] + 3; 48 | } 49 | } 50 | 51 | /** 52 | * Get the valued stored in cell (x, y). 53 | * 54 | * @param x is the x-index. 55 | * @param y is the y-index. 56 | * @return the stored value (between 0 and 2). 57 | * @throws ArrayIndexOutOfBoundsException is thrown if an invalid index 58 | * is given. 59 | */ 60 | 61 | public int elementAt(int x, int y) { 62 | return grid[x][y]; 63 | } 64 | 65 | /** 66 | * Returns true if "this" SimpleBoard and "board" have identical values in 67 | * every cell. 68 | * 69 | * @param board is the second SimpleBoard. 70 | * @return true if the boards are equal, false otherwise. 71 | */ 72 | 73 | public boolean equals(Object board) { 74 | // Replace the following line with your solution. Be sure to return false 75 | // (rather than throwing a ClassCastException) if "board" is not 76 | // a SimpleBoard. 77 | return toString().equals(((SimpleBoard) board).toString()); 78 | } 79 | 80 | 81 | @Override 82 | public String toString() { 83 | String gridString = ""; 84 | for (int y = 0; y < DIMENSION; y++) { 85 | for (int x = 0; x < DIMENSION; x++) { 86 | gridString += grid[x][y]; 87 | } 88 | } 89 | return gridString; 90 | 91 | // return "010102020121212121220101012121212"; 92 | } 93 | 94 | /** 95 | * Returns a hash code for this SimpleBoard. 96 | * 97 | * @return a number between Integer.MIN_VALUE and Integer.MAX_VALUE. 98 | */ 99 | 100 | public int hashCode() { 101 | String gridString = toString(); 102 | int hashCode = 0; 103 | for (int i = 0; i < gridString.length(); i++) { 104 | long power = (long) Math.pow(3, gridString.length() - i - 1); 105 | int digit = Character.getNumericValue(gridString.charAt(i)); 106 | hashCode += power * digit; 107 | } 108 | return hashCode; 109 | // Replace the following line with your solution. 110 | // return (int)(hashCode % Integer.MAX_VALUE); 111 | // return toString().hashCode(); 112 | } 113 | 114 | public static void main(String[] args) { 115 | SimpleBoard gameGrid = new SimpleBoard(); 116 | // gameGrid.setElementAt(0, 0, 2); 117 | // System.out.println(gameGrid.hashCode()); 118 | // gameGrid.setElementAt(0,1,2); 119 | // System.out.println(gameGrid.hashCode()); 120 | // gameGrid.setElementAt(5, 2, 1); 121 | // System.out.println(gameGrid.hashCode()); 122 | // 123 | // 124 | // SimpleBoard gameGrid2 = new SimpleBoard(); 125 | // gameGrid2.setElementAt(0,0,2); 126 | // gameGrid2.setElementAt(0,1,2); 127 | // gameGrid2.setElementAt(5,2,1); 128 | // 129 | // System.out.println(gameGrid.equals(gameGrid2)); 130 | 131 | Random rand = new Random(345345); 132 | int i = 200; 133 | while (i > 0) { 134 | gameGrid.setElementAt(rand.nextInt(8), rand.nextInt(8), rand.nextInt(3)); 135 | System.out.print(gameGrid.toString()); 136 | System.out.println(" " + gameGrid.hashCode()); 137 | i--; 138 | } 139 | // System.out.println(gameGrid.hashCode()); 140 | 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /pj1/RunIterator.java: -------------------------------------------------------------------------------- 1 | /* RunIterator.java */ 2 | 3 | /** 4 | * The RunIterator class iterates over a RunLengthEncoding and allows other 5 | * classes to inspect the runsDList in a run-length encoding, one run at a time. 6 | * A newly constructed RunIterator "points" to the first run in the encoding 7 | * used to construct it. Each time next() is invoked, it returns a run 8 | * (represented as an array of four ints); a sequence of calls to next() 9 | * returns run in consecutive order until every run has been returned. 10 | * 11 | * Client classes should never call the RunIterator constructor directly; 12 | * instead they should invoke the iterator() method on a RunLengthEncoding 13 | * object, which will construct a properly initialized RunIterator for the 14 | * client. 15 | * 16 | * Calls to hasNext() determine whether another run is available, or whether 17 | * the iterator has reached the end of the run-length encoding. When 18 | * a RunIterator reaches the end of an encoding, it is no longer useful, and 19 | * the next() method may throw an exception; thus it is recommended to check 20 | * hasNext() before each call to next(). To iterate through the encoding 21 | * again, construct a new RunIterator by invoking iterator() on the 22 | * RunLengthEncoding and throw the old RunIterator away. 23 | * 24 | * A RunIterator is not guaranteed to work if the underlying RunLengthEncoding 25 | * is modified after the RunIterator is constructed. (Especially if it is 26 | * modified by setPixel().) 27 | */ 28 | package pj1; 29 | 30 | import java.util.Iterator; 31 | import java.util.NoSuchElementException; 32 | 33 | @SuppressWarnings("rawtypes") 34 | public class RunIterator implements Iterator { 35 | 36 | /** 37 | * Define any variables associated with a RunIterator object here. 38 | * These variables MUST be private. 39 | */ 40 | private DListNode currentNode; 41 | private DList runsDList; 42 | 43 | /** 44 | * RunIterator() constructs a new iterator starting with a specified run. 45 | * 46 | * @param node the run where this iterator starts. 47 | * @param runsDList the 48 | */ 49 | // Unlike all the other methods we have asked you to write, the RunIterator() 50 | // constructor does not have a predefined signature, because no outside 51 | // class should ever call this constructor except the iterator() method in 52 | // the RunLengthEncoding class. The correct way for outside classes to 53 | // get access to a RunIterator is to call the iterator() method on a 54 | // RunLengthEncoding object. You are welcome to add any parameters to the 55 | // constructor that you want so that your RunLengthEncoding.iterator() 56 | // implementation can construct a RunIterator that points to the first run of 57 | // the encoding. 58 | RunIterator(DListNode node, DList runsDList) { 59 | currentNode = node; 60 | this.runsDList = runsDList; 61 | // Your solution here. You may add parameters to the method signature. 62 | } 63 | 64 | /** 65 | * hasNext() returns true if this iterator has more runsDList. If it returns 66 | * false, then the next call to next() may throw an exception. 67 | * 68 | * @return true if the iterator has more elements. 69 | */ 70 | public boolean hasNext() { 71 | if (currentNode.next != runsDList.head) { 72 | return true; 73 | } else { 74 | return false; 75 | } 76 | } 77 | 78 | /** 79 | * next() returns an array of 4 ints that specifies the current run in the 80 | * sequence. It also advances the iterator to the next run, so that the 81 | * next call to next() will return the following run. 82 | *

83 | * If "this" RunIterator has returned every run, it cannot be expected to 84 | * behave well. (Technically, it is supposed to throw a 85 | * NoSuchElementException, but we haven't learned about exceptions yet.) 86 | * 87 | * @return an array of 4 ints that specify the current run in the sequence. 88 | * The pixel count is in index [0]; the red value is in index [1]; the green 89 | * value is in index [2]; and the blue value is in index [3]. 90 | * @throws NoSuchElementException if the iteration has no more elements. 91 | * (We strongly recommend calling hasNext() to check whether there are any 92 | * more runsDList before calling next().) 93 | *

94 | * The returned four-int array is constructed in next(), and can be 95 | * discarded by the calling method after use. The array should not be part 96 | * of your RunLengthEncoding data structure! It must be freshly constructed 97 | * for the sole purpose of returning four ints. 98 | */ 99 | public int[] next() { 100 | if (hasNext()) { 101 | currentNode = currentNode.next; 102 | int[] result = new int[4]; 103 | result[0] = currentNode.number; 104 | result[1] = currentNode.nodePixel.R; 105 | result[2] = currentNode.nodePixel.G; 106 | result[3] = currentNode.nodePixel.B; 107 | return result; 108 | } else { 109 | System.out.println("No More Next"); 110 | return new int[]{-1, -1, -1, -1}; 111 | } 112 | } 113 | 114 | /** 115 | * remove() would remove from the underlying run-length encoding the run 116 | * identified by this iterator, but we are NOT implementing it. 117 | *

118 | * DO NOT CHANGE THIS METHOD. 119 | */ 120 | public void remove() { 121 | throw new UnsupportedOperationException(); 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /hw5/list/SListNode.java: -------------------------------------------------------------------------------- 1 | /* SListNode.java */ 2 | 3 | package hw5.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 | * 24 | * @param i the item to store in the node. 25 | * @param l the list this node is in. 26 | * @param n the node following this node. 27 | */ 28 | SListNode(Object i, SList l, SListNode n) { 29 | item = i; 30 | myList = l; 31 | next = n; 32 | } 33 | 34 | /** 35 | * next() returns the node following this node. If this node is invalid, 36 | * throws an exception. 37 | * 38 | * @return the node following this node. 39 | * @throws InvalidNodeException if this node is not valid. 40 | *

41 | * Performance: runs in O(1) time. 42 | */ 43 | public ListNode next() throws InvalidNodeException { 44 | if (!isValidNode()) { 45 | throw new InvalidNodeException("next() called on invalid node"); 46 | } 47 | if (next == null) { 48 | // Create an invalid node. 49 | SListNode node = ((SList) myList).newNode(null, null); 50 | node.myList = null; 51 | return node; 52 | } else { 53 | return next; 54 | } 55 | } 56 | 57 | /** 58 | * prev() returns the node preceding this node. If this node is invalid, 59 | * throws an exception. 60 | * 61 | * @param node the node whose predecessor is sought. 62 | * @return the node preceding this node. 63 | * @throws InvalidNodeException if this node is not valid. 64 | *

65 | * Performance: runs in O(this.size) time. 66 | */ 67 | public ListNode prev() throws InvalidNodeException { 68 | if (!isValidNode()) { 69 | throw new InvalidNodeException("prev() called on invalid node"); 70 | } 71 | SListNode prev = ((SList) myList).head; 72 | if (prev == this) { 73 | // Create an invalid node. 74 | prev = ((SList) myList).newNode(null, null); 75 | prev.myList = null; 76 | } else { 77 | while (prev.next != this) { 78 | prev = prev.next; 79 | } 80 | } 81 | return prev; 82 | } 83 | 84 | /** 85 | * insertAfter() inserts an item immediately following this node. If this 86 | * node is invalid, throws an exception. 87 | * 88 | * @param item the item to be inserted. 89 | * @throws InvalidNodeException if this node is not valid. 90 | *

91 | * Performance: runs in O(1) time. 92 | */ 93 | public void insertAfter(Object item) throws InvalidNodeException { 94 | if (!isValidNode()) { 95 | throw new InvalidNodeException("insertAfter() called on invalid node"); 96 | } 97 | SListNode newNode = ((SList) myList).newNode(item, next); 98 | if (next == null) { 99 | ((SList) myList).tail = newNode; 100 | } 101 | next = newNode; 102 | myList.size++; 103 | } 104 | 105 | /** 106 | * insertBefore() inserts an item immediately preceding this node. If this 107 | * node is invalid, throws an exception. 108 | * 109 | * @param item the item to be inserted. 110 | * @throws InvalidNodeException if this node is not valid. 111 | *

112 | * Performance: runs in O(this.size) time. 113 | */ 114 | public void insertBefore(Object item) throws InvalidNodeException { 115 | if (!isValidNode()) { 116 | throw new InvalidNodeException("insertBefore() called on invalid node"); 117 | } 118 | SListNode newNode = ((SList) myList).newNode(item, this); 119 | if (this == ((SList) myList).head) { 120 | ((SList) myList).head = newNode; 121 | } else { 122 | SListNode prev = (SListNode) prev(); 123 | prev.next = newNode; 124 | } 125 | myList.size++; 126 | } 127 | 128 | /** 129 | * remove() removes this node from its SList. If this node is invalid, 130 | * throws an exception. 131 | * 132 | * @throws InvalidNodeException if this node is not valid. 133 | *

134 | * Performance: runs in O(this.size) time. 135 | */ 136 | public void remove() throws InvalidNodeException { 137 | if (!isValidNode()) { 138 | throw new InvalidNodeException("remove() called on invalid node"); 139 | } 140 | if (this == ((SList) myList).head) { 141 | ((SList) myList).head = next; 142 | if (next == null) { 143 | ((SList) myList).tail = null; 144 | } 145 | } else { 146 | SListNode prev = (SListNode) prev(); 147 | prev.next = next; 148 | if (next == null) { 149 | ((SList) myList).tail = prev; 150 | } 151 | } 152 | myList.size--; 153 | 154 | // Make this node an invalid node, so it cannot be used to corrupt myList. 155 | myList = null; 156 | // Set other reference to null to improve garbage collection. 157 | next = null; 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /pj3/KruskalTest.java: -------------------------------------------------------------------------------- 1 | /* KruskalTest.java */ 2 | 3 | /** 4 | * The KruskalTest class tests the Kruskal class. 5 | */ 6 | package pj3; 7 | 8 | import pj3.graph.*; 9 | import pj3.graphalg.*; 10 | 11 | import java.util.*; 12 | 13 | public class KruskalTest { 14 | 15 | private static final int VERTICES = 10; 16 | private static final int MAXINT = 100; 17 | 18 | private static boolean tree = true; 19 | private static boolean minTree = true; 20 | 21 | public static void addRandomEdges(WUGraph g, Object[] vertArray) { 22 | int i, j; 23 | 24 | System.out.println("Adding random edges to graph."); 25 | 26 | Random random = new Random(3); // Create a "Random" object with seed 0 27 | 28 | for (i = 0; i < vertArray.length; i++) { 29 | for (j = i; j < vertArray.length; j++) { 30 | int r = random.nextInt() % MAXINT; // Between -99 and 99 31 | if (r >= 0) { 32 | g.addEdge(vertArray[i], vertArray[j], r); 33 | } 34 | } 35 | } 36 | } 37 | 38 | public static void DFS(WUGraph t, DFSVertex current, DFSVertex prev, 39 | int[] maxOnPath, int maxEdge) { 40 | Neighbors neigh; 41 | int i; 42 | 43 | current.visited = true; 44 | maxOnPath[current.number] = maxEdge; 45 | neigh = t.getNeighbors(current); 46 | if (neigh != null) { 47 | for (i = 0; i < neigh.neighborList.length; i++) { 48 | DFSVertex next = (DFSVertex) neigh.neighborList[i]; 49 | if (next.visited) { 50 | if ((next != current) && (next != prev)) { 51 | tree = false; 52 | return; 53 | } 54 | } else if (neigh.weightList[i] > maxEdge) { 55 | DFS(t, next, current, maxOnPath, neigh.weightList[i]); 56 | } else { 57 | DFS(t, next, current, maxOnPath, maxEdge); 58 | } 59 | if (!tree) { 60 | return; 61 | } 62 | } 63 | } 64 | } 65 | 66 | public static void DFSTest(WUGraph g, WUGraph t, DFSVertex[] vertArray) { 67 | int[][] maxOnPath; 68 | Neighbors neigh; 69 | int i, j; 70 | 71 | System.out.println("Testing the tree."); 72 | 73 | maxOnPath = new int[VERTICES][VERTICES]; 74 | for (i = 0; i < VERTICES; i++) { 75 | for (j = 0; j < VERTICES; j++) { 76 | vertArray[j].visited = false; 77 | } 78 | DFS(t, vertArray[i], null, maxOnPath[i], -MAXINT); 79 | for (j = 0; j < VERTICES; j++) { 80 | if (!vertArray[j].visited) { 81 | tree = false; 82 | } 83 | } 84 | if (!tree) { 85 | return; 86 | } 87 | } 88 | 89 | // for (i = 0; i < vertArray.length; i++) { 90 | // for (j = 0; j < vertArray.length; j++) { 91 | // System.out.print(" " + maxOnPath[i][j]); 92 | // } 93 | // System.out.println(); 94 | // } 95 | 96 | for (i = 0; i < VERTICES; i++) { 97 | neigh = g.getNeighbors(vertArray[i]); 98 | if (neigh != null) { 99 | for (j = 0; j < neigh.neighborList.length; j++) { 100 | int v = ((DFSVertex) neigh.neighborList[j]).number; 101 | if (neigh.weightList[j] < maxOnPath[i][v]) { 102 | minTree = false; 103 | } 104 | } 105 | } 106 | } 107 | } 108 | 109 | public static void main(String[] args) { 110 | int i, j; 111 | int score; 112 | WUGraph g, t; 113 | DFSVertex[] vertArray; 114 | 115 | System.out.println("Running minimum spanning tree test."); 116 | System.out.println("Creating empty graph."); 117 | g = new WUGraph(); 118 | 119 | System.out.println("Adding " + VERTICES + " vertices."); 120 | vertArray = new DFSVertex[VERTICES]; 121 | for (i = 0; i < VERTICES; i++) { 122 | vertArray[i] = new DFSVertex(); 123 | vertArray[i].number = i; 124 | g.addVertex(vertArray[i]); 125 | } 126 | 127 | addRandomEdges(g, vertArray); 128 | 129 | // for (i = 0; i < vertArray.length; i++) { 130 | // for (j = 0; j < vertArray.length; j++) { 131 | // if (g.isEdge(vertArray[i], vertArray[j])) { 132 | // System.out.print(" " + g.weight(vertArray[i], vertArray[j])); 133 | // } else { 134 | // System.out.print(" *"); 135 | // } 136 | // } 137 | // System.out.println(); 138 | // } 139 | 140 | System.out.println("Finding the minimum spanning tree."); 141 | t = Kruskal.minSpanTree(g); 142 | 143 | // for (i = 0; i < vertArray.length; i++) { 144 | // for (j = 0; j < vertArray.length; j++) { 145 | // if (t.isEdge(vertArray[i], vertArray[j])) { 146 | // System.out.print(" " + t.weight(vertArray[i], vertArray[j])); 147 | // } else { 148 | // System.out.print(" *"); 149 | // } 150 | // } 151 | // System.out.println(); 152 | // } 153 | 154 | DFSTest(g, t, vertArray); 155 | 156 | if (tree) { 157 | System.out.println("One point for creating a tree."); 158 | if (minTree) { 159 | System.out.println("Two points for creating a minimum spanning tree."); 160 | score = 3; 161 | } else { 162 | System.out.println("Not a minimum spanning tree."); 163 | score = 1; 164 | } 165 | } else { 166 | System.out.println("Not a tree."); 167 | score = 0; 168 | } 169 | 170 | System.out.println("Your Kruskal test score is " + score + " out of 3."); 171 | System.out.println(" (Be sure also to run WUGTest.java.)"); 172 | } 173 | } 174 | 175 | class DFSVertex { 176 | boolean visited; 177 | int number; 178 | } 179 | -------------------------------------------------------------------------------- /hw4/list/TestDList.java: -------------------------------------------------------------------------------- 1 | package hw4.list; 2 | 3 | public class TestDList { 4 | public static void main(String[] args) { 5 | // Fill in your solution for Part I here. 6 | System.out.println("Now we are testing DList."); 7 | DList sl1 = new DList(); 8 | sl1.insertBack(new Integer(6)); 9 | sl1.insertBack(new Integer(9)); 10 | sl1.insertBack(new Integer(12)); 11 | System.out.println("Here is a list after insertBack 6, 9, 12: " 12 | + sl1.toString()); 13 | System.out.println(); 14 | 15 | 16 | sl1.insertFront(new Integer(3)); 17 | sl1.insertBack(new Integer(15)); 18 | System.out.println("Here is the same list after insertBack(15) and insertFront(3): " 19 | + sl1.toString()); 20 | newtest(sl1); 21 | 22 | testEmpty(); 23 | testAfterInsertFront(); 24 | testAfterinsertBack(); 25 | } 26 | 27 | 28 | /** 29 | * testEmpty() tests toString(), isEmpty(), length(), insertFront(), and 30 | * insertBack() on an empty list. Prints summary information of the tests 31 | * and halts the program if errors are detected. 32 | */ 33 | 34 | private static void testEmpty() { 35 | DList lst1 = new DList(); 36 | DList lst2 = new DList(); 37 | System.out.println(); 38 | System.out.println("Here is a list after construction: " 39 | + lst1.toString()); 40 | TestHelper.verify(lst1.toString().equals("[ ]"), 41 | "toString on newly constructed list failed"); 42 | 43 | System.out.println("isEmpty() should be true. It is: " + 44 | lst1.isEmpty()); 45 | TestHelper.verify(lst1.isEmpty() == true, 46 | "isEmpty() on newly constructed list failed"); 47 | 48 | System.out.println("length() should be 0. It is: " + 49 | lst1.length()); 50 | TestHelper.verify(lst1.length() == 0, 51 | "length on newly constructed list failed"); 52 | lst1.insertFront(new Integer(3)); 53 | System.out.println("Here is a list after insertFront(3) to an empty list: " 54 | + lst1.toString()); 55 | TestHelper.verify(lst1.toString().equals("[ 3 ]"), 56 | "InsertFront on empty list failed"); 57 | lst2.insertBack(new Integer(5)); 58 | System.out.println("Here is a list after insertBack(5) on an empty list: " 59 | + lst2.toString()); 60 | TestHelper.verify(lst2.toString().equals("[ 5 ]"), 61 | "insertBack on empty list failed"); 62 | } 63 | 64 | /** 65 | * testAfterInsertFront() tests toString(), isEmpty(), length(), 66 | * insertFront(), and insertBack() after insertFront(). Prints summary 67 | * information of the tests and halts the program if errors are detected. 68 | */ 69 | 70 | private static void testAfterInsertFront() { 71 | DList lst1 = new DList(); 72 | lst1.insertFront(new Integer(3)); 73 | lst1.insertFront(new Integer(2)); 74 | lst1.insertFront(new Integer(1)); 75 | System.out.println(); 76 | System.out.println("Here is a list after insertFront 3, 2, 1: " 77 | + lst1.toString()); 78 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 ]"), 79 | "InsertFronts on non-empty list failed"); 80 | System.out.println("isEmpty() should be false. It is: " + 81 | lst1.isEmpty()); 82 | TestHelper.verify(lst1.isEmpty() == false, 83 | "isEmpty() after insertFront failed"); 84 | System.out.println("length() should be 3. It is: " + 85 | lst1.length()); 86 | TestHelper.verify(lst1.length() == 3, 87 | "length() after insertFront failed"); 88 | lst1.insertBack(new Integer(4)); 89 | System.out.println("Here is the same list after insertBack(4): " 90 | + lst1.toString()); 91 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 4 ]"), 92 | "insertBack on non-empty list failed"); 93 | } 94 | 95 | /** 96 | * testAfterinsertBack() tests toString(), isEmpty(), length(), 97 | * insertFront(), and insertBack() after insertBack(). Prints summary 98 | * information of the tests and halts the program if errors are detected. 99 | */ 100 | 101 | private static void testAfterinsertBack() { 102 | DList lst1 = new DList(); 103 | lst1.insertBack(new Integer(6)); 104 | lst1.insertBack(new Integer(7)); 105 | System.out.println(); 106 | System.out.println("Here is a list after insertBack 6, 7: " 107 | + lst1.toString()); 108 | System.out.println("isEmpty() should be false. It is: " + 109 | lst1.isEmpty()); 110 | TestHelper.verify(lst1.isEmpty() == false, 111 | "isEmpty() after insertBack failed"); 112 | System.out.println("length() should be 2. It is: " + 113 | lst1.length()); 114 | TestHelper.verify(lst1.length() == 2, 115 | "length() after insertBackfailed"); 116 | lst1.insertFront(new Integer(5)); 117 | System.out.println("Here is the same list after insertFront(5): " 118 | + lst1.toString()); 119 | TestHelper.verify(lst1.toString().equals("[ 5 6 7 ]"), 120 | "insertFront after insertBack failed"); 121 | } 122 | 123 | private static void newtest(DList sl1) { 124 | DListNode node = sl1.front(); 125 | System.out.println(); 126 | System.out.println("front() should be 3. It is: " + 127 | sl1.front().item); 128 | System.out.println("front's next should be 6. It is: " + 129 | sl1.next(node).item); 130 | System.out.println("front's next's prev should be 3. It is: " + 131 | sl1.prev(sl1.next(node)).item); 132 | sl1.remove(node); 133 | System.out.println("After remove the front, the front() should be 6. It is: " + 134 | sl1.front().item); 135 | node = sl1.front(); 136 | sl1.insertBefore(new Integer(5), node); 137 | sl1.insertAfter(new Integer(8), node); 138 | System.out.println("After insertBefore() and insertAfter(), The first 3 nodes should be 5,6,8. The list is: " + 139 | sl1.toString()); 140 | 141 | } 142 | } -------------------------------------------------------------------------------- /hw5/list/DListNode.java: -------------------------------------------------------------------------------- 1 | /* DListNode.java */ 2 | 3 | package hw5.list; 4 | 5 | /** 6 | * A DListNode is a mutable node in a DList (doubly-linked list). 7 | */ 8 | 9 | public class DListNode 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 | * 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 | protected DListNode prev; 21 | protected DListNode next; 22 | 23 | /** 24 | * DListNode() constructor. 25 | * 26 | * @param i the item to store in the node. 27 | * @param l the list this node is in. 28 | * @param p the node previous to this node. 29 | * @param n the node following this node. 30 | */ 31 | DListNode(Object i, DList l, DListNode p, DListNode n) { 32 | item = i; 33 | myList = l; 34 | prev = p; 35 | next = n; 36 | } 37 | 38 | /** 39 | * isValidNode returns true if this node is valid; false otherwise. 40 | * An invalid node is represented by a `myList' field with the value null. 41 | * Sentinel nodes are invalid, and nodes that don't belong to a list are 42 | * also invalid. 43 | * 44 | * @return true if this node is valid; false otherwise. 45 | *

46 | * Performance: runs in O(1) time. 47 | */ 48 | public boolean isValidNode() { 49 | return myList != null; 50 | } 51 | 52 | /** 53 | * next() returns the node following this node. If this node is invalid, 54 | * throws an exception. 55 | * 56 | * @return the node following this node. 57 | * @throws InvalidNodeException if this node is not valid. 58 | *

59 | * Performance: runs in O(1) time. 60 | */ 61 | public ListNode next() throws InvalidNodeException { 62 | if (!isValidNode()) { 63 | throw new InvalidNodeException("next() called on invalid node"); 64 | } 65 | return next; 66 | } 67 | 68 | /** 69 | * prev() returns the node preceding this node. If this node is invalid, 70 | * throws an exception. 71 | * 72 | * @return the node preceding this node. 73 | * @throws InvalidNodeException if this node is not valid. 74 | *

75 | * Performance: runs in O(1) time. 76 | */ 77 | public ListNode prev() throws InvalidNodeException { 78 | if (!isValidNode()) { 79 | throw new InvalidNodeException("prev() called on invalid node"); 80 | } 81 | return prev; 82 | } 83 | 84 | /** 85 | * insertAfter() inserts an item immediately following this node. If this 86 | * node is invalid, throws an exception. 87 | * 88 | * @param item the item to be inserted. 89 | * @throws InvalidNodeException if this node is not valid. 90 | *

91 | * Performance: runs in O(1) time. 92 | */ 93 | public void insertAfter(Object item) throws InvalidNodeException { 94 | if (!isValidNode()) { 95 | throw new InvalidNodeException("insertAfter() called on invalid node"); 96 | } 97 | DListNode newNode = ((DList) myList).newNode(item, (DList) myList, this, next); 98 | next = newNode; 99 | newNode.next.prev = newNode; 100 | myList.size++; 101 | // Your solution here. Will look something like your Homework 4 solution, 102 | // but changes are necessary. For instance, there is no need to check if 103 | // "this" is null. Remember that this node's "myList" field tells you 104 | // what DList it's in. You should use myList.newNode() to create the 105 | // new node. 106 | } 107 | 108 | /** 109 | * insertBefore() inserts an item immediately preceding this node. If this 110 | * node is invalid, throws an exception. 111 | * 112 | * @param item the item to be inserted. 113 | * @throws InvalidNodeException if this node is not valid. 114 | *

115 | * Performance: runs in O(1) time. 116 | */ 117 | public void insertBefore(Object item) throws InvalidNodeException { 118 | if (!isValidNode()) { 119 | throw new InvalidNodeException("insertBefore() called on invalid node"); 120 | } 121 | DListNode newNode = ((DList) myList).newNode(item, (DList) myList, prev, this); 122 | prev = newNode; 123 | newNode.prev.next = newNode; 124 | myList.size++; 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 | } 131 | 132 | /** 133 | * remove() removes this node from its DList. If this node is invalid, 134 | * throws an exception. 135 | * 136 | * @throws InvalidNodeException if this node is not valid. 137 | *

138 | * Performance: runs in O(1) time. 139 | */ 140 | public void remove() throws InvalidNodeException { 141 | if (!isValidNode()) { 142 | throw new InvalidNodeException("remove() called on invalid node"); 143 | } 144 | next.prev = prev; 145 | prev.next = next; 146 | myList.size--; 147 | // Your solution here. Will look something like your Homework 4 solution, 148 | // but changes are necessary. For instance, there is no need to check if 149 | // "this" is null. Remember that this node's "myList" field tells you 150 | // what DList it's in. 151 | 152 | 153 | // Make this node an invalid node, so it cannot be used to corrupt myList. 154 | myList = null; 155 | // Set other references to null to improve garbage collection. 156 | next = null; 157 | prev = null; 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /hw4/list/TestLockDList.java: -------------------------------------------------------------------------------- 1 | package hw4.list; 2 | 3 | public class TestLockDList { 4 | public static void main(String[] args) { 5 | // Fill in your solution for Part I here. 6 | System.out.println("Now we are testing LockDList."); 7 | LockDList sl1 = new LockDList(); 8 | sl1.insertBack(new Integer(6)); 9 | sl1.insertBack(new Integer(9)); 10 | sl1.insertBack(new Integer(12)); 11 | System.out.println("Here is a list after insertBack 6, 9, 12: " 12 | + sl1.toString()); 13 | System.out.println(); 14 | 15 | 16 | sl1.insertFront(new Integer(3)); 17 | sl1.insertBack(new Integer(15)); 18 | System.out.println("Here is the same list after insertBack(15) and insertFront(3): " 19 | + sl1.toString()); 20 | newtest(sl1); 21 | 22 | testEmpty(); 23 | testAfterInsertFront(); 24 | testAfterinsertBack(); 25 | } 26 | 27 | 28 | /** 29 | * testEmpty() tests toString(), isEmpty(), length(), insertFront(), and 30 | * insertBack() on an empty list. Prints summary information of the tests 31 | * and halts the program if errors are detected. 32 | */ 33 | 34 | private static void testEmpty() { 35 | LockDList lst1 = new LockDList(); 36 | LockDList lst2 = new LockDList(); 37 | System.out.println(); 38 | System.out.println("Here is a list after construction: " 39 | + lst1.toString()); 40 | TestHelper.verify(lst1.toString().equals("[ ]"), 41 | "toString on newly constructed list failed"); 42 | 43 | System.out.println("isEmpty() should be true. It is: " + 44 | lst1.isEmpty()); 45 | TestHelper.verify(lst1.isEmpty() == true, 46 | "isEmpty() on newly constructed list failed"); 47 | 48 | System.out.println("length() should be 0. It is: " + 49 | lst1.length()); 50 | TestHelper.verify(lst1.length() == 0, 51 | "length on newly constructed list failed"); 52 | lst1.insertFront(new Integer(3)); 53 | System.out.println("Here is a list after insertFront(3) to an empty list: " 54 | + lst1.toString()); 55 | TestHelper.verify(lst1.toString().equals("[ 3 ]"), 56 | "InsertFront on empty list failed"); 57 | lst2.insertBack(new Integer(5)); 58 | System.out.println("Here is a list after insertBack(5) on an empty list: " 59 | + lst2.toString()); 60 | TestHelper.verify(lst2.toString().equals("[ 5 ]"), 61 | "insertBack on empty list failed"); 62 | } 63 | 64 | /** 65 | * testAfterInsertFront() tests toString(), isEmpty(), length(), 66 | * insertFront(), and insertBack() after insertFront(). Prints summary 67 | * information of the tests and halts the program if errors are detected. 68 | */ 69 | 70 | private static void testAfterInsertFront() { 71 | LockDList lst1 = new LockDList(); 72 | lst1.insertFront(new Integer(3)); 73 | lst1.insertFront(new Integer(2)); 74 | lst1.insertFront(new Integer(1)); 75 | System.out.println(); 76 | System.out.println("Here is a list after insertFront 3, 2, 1: " 77 | + lst1.toString()); 78 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 ]"), 79 | "InsertFronts on non-empty list failed"); 80 | System.out.println("isEmpty() should be false. It is: " + 81 | lst1.isEmpty()); 82 | TestHelper.verify(lst1.isEmpty() == false, 83 | "isEmpty() after insertFront failed"); 84 | System.out.println("length() should be 3. It is: " + 85 | lst1.length()); 86 | TestHelper.verify(lst1.length() == 3, 87 | "length() after insertFront failed"); 88 | lst1.insertBack(new Integer(4)); 89 | System.out.println("Here is the same list after insertBack(4): " 90 | + lst1.toString()); 91 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 4 ]"), 92 | "insertBack on non-empty list failed"); 93 | } 94 | 95 | /** 96 | * testAfterinsertBack() tests toString(), isEmpty(), length(), 97 | * insertFront(), and insertBack() after insertBack(). Prints summary 98 | * information of the tests and halts the program if errors are detected. 99 | */ 100 | 101 | private static void testAfterinsertBack() { 102 | LockDList lst1 = new LockDList(); 103 | lst1.insertBack(new Integer(6)); 104 | lst1.insertBack(new Integer(7)); 105 | System.out.println(); 106 | System.out.println("Here is a list after insertBack 6, 7: " 107 | + lst1.toString()); 108 | System.out.println("isEmpty() should be false. It is: " + 109 | lst1.isEmpty()); 110 | TestHelper.verify(lst1.isEmpty() == false, 111 | "isEmpty() after insertBack failed"); 112 | System.out.println("length() should be 2. It is: " + 113 | lst1.length()); 114 | TestHelper.verify(lst1.length() == 2, 115 | "length() after insertBackfailed"); 116 | lst1.insertFront(new Integer(5)); 117 | System.out.println("Here is the same list after insertFront(5): " 118 | + lst1.toString()); 119 | TestHelper.verify(lst1.toString().equals("[ 5 6 7 ]"), 120 | "insertFront after insertBack failed"); 121 | } 122 | 123 | private static void newtest(LockDList sl1) { 124 | LockDListNode node = sl1.front(); 125 | System.out.println(); 126 | System.out.println("front() should be 3. It is: " + 127 | sl1.front().item); 128 | System.out.println("front's next should be 6. It is: " + 129 | sl1.next(node).item); 130 | System.out.println("front's next's prev should be 3. It is: " + 131 | sl1.prev(sl1.next(node)).item); 132 | 133 | System.out.println(node.lockStatus); 134 | 135 | sl1.lockNode(node); 136 | System.out.println("We lockNode front()= " + node.item); 137 | 138 | System.out.println(node.lockStatus); 139 | 140 | sl1.remove(node); 141 | System.out.println("After remove the locked front, the front() should still be 3. It is: " + 142 | sl1.front().item); 143 | LockDListNode back = sl1.back(); 144 | sl1.remove(back); 145 | System.out.println("After remove the back, the back() should be 12. It is: " + 146 | sl1.back().item); 147 | node = sl1.front(); 148 | sl1.insertBefore(new Integer(5), node); 149 | sl1.insertAfter(new Integer(8), node); 150 | System.out.println("After insertBefore(3) and insertAfter(3), The first 3 nodes should be 5,3,8. The list is: " + 151 | sl1.toString()); 152 | } 153 | } -------------------------------------------------------------------------------- /pj1/Sobel.java: -------------------------------------------------------------------------------- 1 | /* Sobel.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE. */ 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 | package pj1; 10 | 11 | /** 12 | * The Sobel class is a program that reads an image file in TIFF format, 13 | * performs Sobel edge detection and uses it to create a grayscale image 14 | * showing the intensities of the strongest edges, writes the grayscale image 15 | * as a TIFF file, and displays both images. Optionally, it can also blur the 16 | * image with one or more iterations of a 3x3 box blurring kernel (similar to 17 | * our Blur program) before performing edge detection, which tends to make 18 | * edge detection more robust. If blurring is selected, this program writes 19 | * both the blurred image and the grayscale-edge image to files and displays 20 | * all three images (the input image and the two output images). 21 | *

22 | * The Sobel program takes up to three parameters. The first parameter is 23 | * the name of the TIFF-format file to read. (The output image file is 24 | * constructed by adding "edge_" to the beginning of the input filename.) 25 | * An optional second parameter specifies the number of iterations of the 26 | * box blurring operation. (The default is zero iterations.) If a third 27 | * parameter is present (regardless of what it is), a second output grayscale 28 | * image is written, run-length encoded to reduce its file size, with prefix 29 | * "rle_". For example, if you run 30 | *

31 | * java Sobel engine.tiff 5 blah 32 | *

33 | * then Sobel will read engine.tiff, perform 5 iterations of blurring, perform 34 | * Sobel edge detection, map the Sobel gradients to grayscale intensities, 35 | * write the blurred image to blur_engine.tiff, write a grayscale-edge image 36 | * to edge_engine.tiff, and write a run-length encoded grayscale-edge image to 37 | * rle_engine.tiff. 38 | * 39 | * @author Joel Galenson and Jonathan Shewchuk 40 | */ 41 | 42 | public class Sobel { 43 | 44 | /** 45 | * sobelFile() reads a TIFF image file, performs Sobel edge detection, maps 46 | * the Sobel gradients to grayscale intensities, writes the edges to a new 47 | * grayscale TIFF image file, and displays both images. Optionally, it can 48 | * blurs the image before edge detection, in which case it also writes the 49 | * blurred image to a file and display all three images. 50 | * 51 | * @param filename the name of the input TIFF image file. 52 | * @param numIterations the number of iterations of blurring to perform. 53 | * @param rle true if the output TIFF file should be run-length encoded. 54 | */ 55 | 56 | private static void sobelFile(String filename, int numIterations, 57 | boolean rle) { 58 | System.out.println("Reading image file " + filename); 59 | PixImage image = ImageUtils.readTIFFPix(filename); 60 | PixImage blurred = image; 61 | 62 | int i = filename(filename); 63 | 64 | if (numIterations > 0) { 65 | System.out.println("Blurring image file."); 66 | blurred = image.boxBlur(numIterations); 67 | 68 | String blurname = "pj1/blur_" + filename.substring(i); 69 | System.out.println("Writing blurred image file " + blurname); 70 | TIFFEncoder.writeTIFF(blurred, blurname); 71 | } 72 | 73 | System.out.println("Performing Sobel edge detection on image file."); 74 | PixImage sobeled = blurred.sobelEdges(); 75 | 76 | String edgename = "pj1/edge_" + filename.substring(i); 77 | System.out.println("Writing grayscale-edge image file " + edgename); 78 | TIFFEncoder.writeTIFF(sobeled, edgename); 79 | if (rle) { 80 | String rlename = "pj1/rle_" + filename.substring(i); 81 | System.out.println("Writing run-length encoded grayscale-edge " + 82 | "image file " + rlename); 83 | TIFFEncoder.writeTIFF(new RunLengthEncoding(sobeled), rlename); 84 | } 85 | 86 | if (numIterations > 0) { 87 | System.out.println("Displaying input image, blurred image, and " + 88 | "grayscale-edge image."); 89 | System.out.println("Close the image to quit."); 90 | ImageUtils.displayTIFFs(new PixImage[]{image, blurred, sobeled}); 91 | } else { 92 | System.out.println("Displaying input image and grayscale-edge image."); 93 | System.out.println("Close the image to quit."); 94 | ImageUtils.displayTIFFs(new PixImage[]{image, sobeled}); 95 | } 96 | } 97 | 98 | 99 | private static int filename(String filename) { 100 | int i = 0; 101 | for (; i < filename.length(); i++) { 102 | if (filename.charAt(i) == '/') { 103 | break; 104 | } 105 | } 106 | return ++i; 107 | } 108 | 109 | /** 110 | * main() reads the command-line arguments and initiates the blurring. 111 | *

112 | * The first command-line argument is the name of the image file. 113 | * An optional second argument is number of iterations of blurring. 114 | * An optional third argument triggers the writing of a run-length encoded 115 | * grayscale-edge image. 116 | * 117 | * @param args the usual array of command-line argument Strings. 118 | */ 119 | public static void main(String[] args) { 120 | String[] foo = {"pj1/reggie.tiff", "6", "4534534"}; 121 | args = foo; 122 | if (args.length == 0) { 123 | System.out.println("usage: java Sobel imagefile [iterations] [RLE]"); 124 | System.out.println(" imagefile is an image in TIFF format."); 125 | System.out.println(" interations is the number of blurring iterations" + 126 | " (default 0)."); 127 | System.out.println(" any third argument (RLE) turns on run-length " + 128 | "encoding in the output file"); 129 | System.out.println("The grayscale-edge image is written to " + 130 | "edge_imagefile."); 131 | System.out.println("If blurring is selected, " + 132 | "the blurred image is written to blur_imagefile."); 133 | System.exit(0); 134 | } 135 | 136 | int numIterations = 0; 137 | if (args.length >= 2) { 138 | try { 139 | numIterations = Integer.parseInt(args[1]); 140 | } catch (NumberFormatException ex) { 141 | System.err.println("The second argument must be a number."); 142 | System.exit(1); 143 | } 144 | } 145 | 146 | sobelFile(args[0], numIterations, args.length >= 3); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /hw3/Homework3.java: -------------------------------------------------------------------------------- 1 | /* Homework3.java */ 2 | package hw3; 3 | 4 | import java.util.Arrays; 5 | 6 | public class Homework3 { 7 | 8 | /** 9 | * smoosh() takes an array of ints. On completion the array contains 10 | * the same numbers, but wherever the array had two or more consecutive 11 | * duplicate numbers, they are replaced by one copy of the number. Hence, 12 | * after smoosh() is done, no two consecutive numbers in the array are the 13 | * same. 14 | *

15 | * Any unused elements at the end of the array are set to -1. 16 | *

17 | * For example, if the input array is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], 18 | * it reads [ 0 1 0 3 1 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 ] after smoosh() 19 | * completes. 20 | * 21 | * @param ints the input array. 22 | */ 23 | 24 | public static void smoosh(int[] ints) { 25 | // Fill in your solution here. (Ours is twelve lines long, not counting 26 | // blank lines or lines already present in this file.) 27 | int currentIndex = 0; 28 | for (int i = 1; i < ints.length; i++) { 29 | if (ints[currentIndex] != ints[i]) { 30 | ints[currentIndex + 1] = ints[i]; 31 | currentIndex++; 32 | } 33 | } 34 | for (int i = currentIndex + 1; i < ints.length; i++) { 35 | ints[i] = -1; 36 | } 37 | } 38 | 39 | /** 40 | * stringInts() converts an array of ints to a String. 41 | * 42 | * @return a String representation of the array. 43 | */ 44 | 45 | private static String stringInts(int[] ints) { 46 | String s = "[ "; 47 | for (int i = 0; i < ints.length; i++) { 48 | s = s + Integer.toString(ints[i]) + " "; 49 | } 50 | return s + "]"; 51 | } 52 | 53 | /** 54 | * main() runs test cases on your smoosh and squish methods. Prints summary 55 | * information on basic operations and halts with an error (and a stack 56 | * trace) if any of the tests fail. 57 | */ 58 | 59 | public static void main(String[] args) { 60 | String result; 61 | int i; 62 | 63 | 64 | System.out.println("Let's smoosh arrays!\n"); 65 | 66 | int[] test1 = {3, 7, 7, 7, 4, 5, 5, 2, 0, 8, 8, 8, 8, 5}; 67 | System.out.println("smooshing " + stringInts(test1) + ":"); 68 | smoosh(test1); 69 | result = stringInts(test1); 70 | System.out.println(result); 71 | TestHelper.verify(result.equals( 72 | "[ 3 7 4 5 2 0 8 5 -1 -1 -1 -1 -1 -1 ]"), 73 | "BAD SMOOSH!!! No cookie."); 74 | 75 | int[] test2 = {6, 6, 6, 6, 6, 3, 6, 3, 6, 3, 3, 3, 3, 3, 3}; 76 | System.out.println("smooshing " + stringInts(test2) + ":"); 77 | smoosh(test2); 78 | result = stringInts(test2); 79 | System.out.println(result); 80 | TestHelper.verify(result.equals( 81 | "[ 6 3 6 3 6 3 -1 -1 -1 -1 -1 -1 -1 -1 -1 ]"), 82 | "BAD SMOOSH!!! No cookie."); 83 | 84 | int[] test3 = {4, 4, 4, 4, 4}; 85 | System.out.println("smooshing " + stringInts(test3) + ":"); 86 | smoosh(test3); 87 | result = stringInts(test3); 88 | System.out.println(result); 89 | TestHelper.verify(result.equals("[ 4 -1 -1 -1 -1 ]"), 90 | "BAD SMOOSH!!! No cookie."); 91 | 92 | int[] test4 = {0, 1, 2, 3, 4, 5, 6}; 93 | System.out.println("smooshing " + stringInts(test4) + ":"); 94 | smoosh(test4); 95 | result = stringInts(test4); 96 | System.out.println(result); 97 | TestHelper.verify(result.equals("[ 0 1 2 3 4 5 6 ]"), 98 | "BAD SMOOSH!!! No cookie."); 99 | 100 | 101 | System.out.println("\nLet's squish linked lists!\n"); 102 | 103 | int[] test5 = {3, 7, 7, 7, 4, 5, 5, 2, 0, 8, 8, 8, 8, 5}; 104 | SList list5 = new SList(); 105 | for (i = 0; i < test5.length; i++) { 106 | list5.insertEnd(new Integer(test5[i])); 107 | } 108 | System.out.println("squishing " + list5.toString() + ":"); 109 | list5.squish(); 110 | result = list5.toString(); 111 | System.out.println(result); 112 | TestHelper.verify(result.equals("[ 3 7 4 5 2 0 8 5 ]"), 113 | "BAD SQUISH!!! No biscuit."); 114 | 115 | int[] test6 = {6, 6, 6, 6, 6, 3, 6, 3, 6, 3, 3, 3, 3, 3, 3}; 116 | SList list6 = new SList(); 117 | for (i = 0; i < test6.length; i++) { 118 | list6.insertEnd(new Integer(test6[i])); 119 | } 120 | System.out.println("squishing " + list6.toString() + ":"); 121 | list6.squish(); 122 | result = list6.toString(); 123 | System.out.println(result); 124 | TestHelper.verify(result.equals("[ 6 3 6 3 6 3 ]"), 125 | "BAD SQUISH!!! No biscuit."); 126 | 127 | int[] test7 = {4, 4, 4, 4, 4}; 128 | SList list7 = new SList(); 129 | for (i = 0; i < test7.length; i++) { 130 | list7.insertEnd(new Integer(test7[i])); 131 | } 132 | System.out.println("squishing " + list7.toString() + ":"); 133 | list7.squish(); 134 | result = list7.toString(); 135 | System.out.println(result); 136 | TestHelper.verify(result.equals("[ 4 ]"), 137 | "BAD SQUISH!!! No biscuit."); 138 | 139 | int[] test8 = {0, 1, 2, 3, 4, 5, 6}; 140 | SList list8 = new SList(); 141 | for (i = 0; i < test8.length; i++) { 142 | list8.insertEnd(new Integer(test8[i])); 143 | } 144 | System.out.println("squishing " + list8.toString() + ":"); 145 | list8.squish(); 146 | result = list8.toString(); 147 | System.out.println(result); 148 | TestHelper.verify(result.equals("[ 0 1 2 3 4 5 6 ]"), 149 | "BAD SQUISH!!! No biscuit."); 150 | 151 | SList list9 = new SList(); 152 | System.out.println("squishing " + list9.toString() + ":"); 153 | list9.squish(); 154 | result = list9.toString(); 155 | System.out.println(result); 156 | TestHelper.verify(result.equals("[ ]"), 157 | "BAD SQUISH!!! No biscuit."); 158 | 159 | 160 | System.out.println("\nLet's twin linked lists!\n"); 161 | 162 | System.out.println("twinning " + list6.toString() + ":"); 163 | list6.twin(); 164 | result = list6.toString(); 165 | System.out.println(result); 166 | TestHelper.verify(result.equals( 167 | "[ 6 6 3 3 6 6 3 3 6 6 3 3 ]"), 168 | "BAD TWIN!!! No gravy."); 169 | 170 | System.out.println("twinning " + list7.toString() + ":"); 171 | list7.twin(); 172 | result = list7.toString(); 173 | System.out.println(result); 174 | TestHelper.verify(result.equals("[ 4 4 ]"), 175 | "BAD TWIN!!! No gravy."); 176 | 177 | System.out.println("twinning " + list9.toString() + ":"); 178 | list9.twin(); 179 | result = list9.toString(); 180 | System.out.println(result); 181 | TestHelper.verify(result.equals("[ ]"), 182 | "BAD TWIN!!! No gravy."); 183 | } 184 | 185 | } 186 | -------------------------------------------------------------------------------- /pj1/ImageUtils.java: -------------------------------------------------------------------------------- 1 | /* ImageUtils.java */ 2 | 3 | /* DO NOT CHANGE THIS FILE. */ 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 | /** 11 | * The ImageUtils class reads and writes TIFF file, converting to and from 12 | * pixel arrays in PixImage format or run-length encodings in 13 | * RunLengthEncoding format. Methods are also included for displaying images 14 | * in PixImage format. 15 | * 16 | * @author Joel Galenson 17 | **/ 18 | package pj1; 19 | 20 | 21 | import java.awt.Color; 22 | import java.awt.event.WindowAdapter; 23 | import java.awt.event.WindowEvent; 24 | import java.awt.image.BufferedImage; 25 | 26 | import javax.media.jai.JAI; 27 | import javax.media.jai.RenderedImageAdapter; 28 | import javax.swing.Box; 29 | import javax.swing.ImageIcon; 30 | import javax.swing.JFrame; 31 | import javax.swing.JLabel; 32 | 33 | /** 34 | * ImageUtils contains utilities for reading, writing, and displaying images. 35 | *

36 | * It uses JAI to read and write TIFF files, as the standard libraries cannot 37 | * read them. 38 | *

39 | * All image data is in RGB format (see BufferedImage.getRGB). 40 | */ 41 | public class ImageUtils { 42 | 43 | /** 44 | * buffer2PixImage() converts a BufferedImage to a PixImage. 45 | * 46 | * @param bImage the image to convert. 47 | * @return a PixImage with the same pixels as the BufferedImage. 48 | */ 49 | private static PixImage buffer2PixImage(BufferedImage bImage) { 50 | PixImage pImage = new PixImage(bImage.getWidth(), bImage.getHeight()); 51 | for (int x = 0; x < bImage.getWidth(); x++) { 52 | for (int y = 0; y < bImage.getHeight(); y++) { 53 | Color color = new Color(bImage.getRGB(x, y)); 54 | pImage.setPixel(x, y, (short) color.getRed(), (short) color.getGreen(), 55 | (short) color.getBlue()); 56 | } 57 | } 58 | return pImage; 59 | } 60 | 61 | /** 62 | * pixImage2buffer() converts a PixImage to a BufferedImage. 63 | * 64 | * @param pImage the image to convert. 65 | * @return a BufferedImage with the same pixels as the PixImage. 66 | */ 67 | static BufferedImage pixImage2buffer(PixImage pImage) { 68 | BufferedImage bImage = new BufferedImage(pImage.getWidth(), 69 | pImage.getHeight(), 70 | BufferedImage.TYPE_INT_ARGB); 71 | for (int x = 0; x < bImage.getWidth(); x++) { 72 | for (int y = 0; y < bImage.getHeight(); y++) { 73 | bImage.setRGB(x, y, new Color(pImage.getRed(x, y), 74 | pImage.getGreen(x, y), 75 | pImage.getBlue(x, y)).getRGB()); 76 | } 77 | } 78 | return bImage; 79 | } 80 | 81 | /** 82 | * readTIFF() reads an image from a file and formats it as a BufferedImage. 83 | * 84 | * @param filename the name of the file to read. 85 | * @return a BufferedImage of the file 86 | */ 87 | private static BufferedImage readTIFF(String filename) { 88 | return (new RenderedImageAdapter(JAI.create("fileload", filename))) 89 | .getAsBufferedImage(); 90 | } 91 | 92 | /** 93 | * readTIFFPix() reads an image from a file and formats it as a PixImage. 94 | * 95 | * @param filename the name of the file to read. 96 | * @return a PixImage of the file 97 | */ 98 | public static PixImage readTIFFPix(String filename) { 99 | return buffer2PixImage(readTIFF(filename)); 100 | } 101 | 102 | /** 103 | * readTIFFRLE() reads an image from a file and formats it as a run-length 104 | * encoding. 105 | * 106 | * @param filename the name of the file to read. 107 | * @return a RunLengthEncoding of the file. 108 | */ 109 | public static RunLengthEncoding readTIFFRLE(String filename) { 110 | return new RunLengthEncoding(readTIFFPix(filename)); 111 | } 112 | 113 | /** 114 | * writeTIFF() writes a BufferedImage to a specified file in TIFF format. 115 | * 116 | * @param rle the input BufferedImage. 117 | * @param filename the output filename. 118 | */ 119 | private static void writeTIFF(BufferedImage image, String filename) { 120 | JAI.create("filestore", image, filename, "tiff"); 121 | } 122 | 123 | /** 124 | * writeTIFF() writes a PixImage to a specified file in TIFF format. 125 | * 126 | * @param image the input PixImage. 127 | * @param filename the output filename. 128 | */ 129 | public static void writeTIFF(PixImage image, String filename) { 130 | writeTIFF(pixImage2buffer(image), filename); 131 | } 132 | 133 | /** 134 | * writeTIFF() writes a run-length encoding to a specified file in TIFF 135 | * format. 136 | * 137 | * @param rle the input run-length encoded image. 138 | * @param filename the output filename. 139 | */ 140 | public static void writeTIFF(RunLengthEncoding rle, String filename) { 141 | writeTIFF(rle.toPixImage(), filename); 142 | } 143 | 144 | /** 145 | * displayFrame displays a JFrame and pauses until the window is closed. 146 | * 147 | * @param frame a JFrame to display. 148 | */ 149 | private static void displayFrame(final JFrame frame) { 150 | try { 151 | synchronized (ImageUtils.class) { 152 | frame.setResizable(false); 153 | frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 154 | frame.addWindowListener(new WindowAdapter() { 155 | @Override 156 | public void windowClosing(WindowEvent event) { 157 | synchronized (ImageUtils.class) { 158 | ImageUtils.class.notify(); 159 | frame.dispose(); 160 | } 161 | } 162 | }); 163 | frame.pack(); 164 | frame.setVisible(true); 165 | ImageUtils.class.wait(); 166 | } 167 | } catch (InterruptedException e) { 168 | System.out.println("Interrupted Exception in displayFrame()."); 169 | e.printStackTrace(); 170 | } 171 | } 172 | 173 | /** 174 | * displayTIFFs displays a sequence of PixImages and pauses until the window 175 | * is closed. 176 | * 177 | * @param images an array of PixImages to display. 178 | */ 179 | public static void displayTIFFs(PixImage[] images) { 180 | JFrame frame = new JFrame(); 181 | Box box = Box.createHorizontalBox(); 182 | for (int i = 0; i < images.length; i++) { 183 | box.add(new JLabel(new ImageIcon(pixImage2buffer(images[i])))); 184 | if (i < images.length - 1) { 185 | box.add(Box.createHorizontalStrut(10)); 186 | } 187 | } 188 | frame.add(box); 189 | displayFrame(frame); 190 | } 191 | 192 | /** 193 | * displayTIFF displays a PixIamge and pauses until the window is closed. 194 | * 195 | * @param image the PixImage to display. 196 | */ 197 | public static void displayTIFF(PixImage image) { 198 | displayTIFFs(new PixImage[]{image}); 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /hw8/ListSorts.java: -------------------------------------------------------------------------------- 1 | /* ListSorts.java */ 2 | package hw8; 3 | 4 | import hw5.list.*; 5 | import hw8.list.*; 6 | 7 | public class ListSorts { 8 | 9 | /** 10 | * makeQueueOfQueues() makes a queue of queues, each containing one item 11 | * of q. Upon completion of this method, q is empty. 12 | * 13 | * @param q is a LinkedQueue of objects. 14 | * @return a LinkedQueue containing LinkedQueue objects, each of which 15 | * contains one object from q. 16 | */ 17 | public static LinkedQueue makeQueueOfQueues(LinkedQueue q) { 18 | LinkedQueue resultQueue = new LinkedQueue(); 19 | 20 | while (!q.isEmpty()) { 21 | try { 22 | LinkedQueue smallQueue = new LinkedQueue(); 23 | smallQueue.enqueue(q.dequeue()); 24 | resultQueue.enqueue(smallQueue); 25 | } catch (QueueEmptyException e) { 26 | e.printStackTrace(); 27 | } 28 | } 29 | // Replace the following line with your solution. 30 | return resultQueue; 31 | } 32 | 33 | /** 34 | * mergeSortedQueues() merges two sorted queues into a third. On completion 35 | * of this method, q1 and q2 are empty, and their items have been merged 36 | * into the returned queue. 37 | * 38 | * @param q1 is LinkedQueue of Comparable objects, sorted from smallest 39 | * to largest. 40 | * @param q2 is LinkedQueue of Comparable objects, sorted from smallest 41 | * to largest. 42 | * @return a LinkedQueue containing all the Comparable objects from q1 43 | * and q2 (and nothing else), sorted from smallest to largest. 44 | */ 45 | public static LinkedQueue mergeSortedQueues(LinkedQueue q1, LinkedQueue q2) { 46 | LinkedQueue result = new LinkedQueue(); 47 | 48 | Object smallerFront; 49 | 50 | try { 51 | while (!q1.isEmpty() && !q2.isEmpty()) { 52 | smallerFront = ((((Comparable) q1.front()).compareTo((Comparable) q2.front()) < 0) ? q1 : q2).dequeue(); 53 | result.enqueue(smallerFront); 54 | } 55 | 56 | while (!q1.isEmpty()) { 57 | result.enqueue(q1.dequeue()); 58 | } 59 | 60 | while (!q2.isEmpty()) { 61 | result.enqueue(q2.dequeue()); 62 | } 63 | } catch (QueueEmptyException e) { 64 | e.printStackTrace(); 65 | } 66 | // Replace the following line with your solution. 67 | return result; 68 | } 69 | 70 | /** 71 | * partition() partitions qIn using the pivot item. On completion of 72 | * this method, qIn is empty, and its items have been moved to qSmall, 73 | * qEquals, and qLarge, according to their relationship to the pivot. 74 | * 75 | * @param qIn is a LinkedQueue of Comparable objects. 76 | * @param pivot is a Comparable item used for partitioning. 77 | * @param qSmall is a LinkedQueue, in which all items less than pivot 78 | * will be enqueued. 79 | * @param qEquals is a LinkedQueue, in which all items equal to the pivot 80 | * will be enqueued. 81 | * @param qLarge is a LinkedQueue, in which all items greater than pivot 82 | * will be enqueued. 83 | */ 84 | public static void partition(LinkedQueue qIn, Comparable pivot, 85 | LinkedQueue qSmall, LinkedQueue qEquals, 86 | LinkedQueue qLarge) { 87 | while (!qIn.isEmpty()) try { 88 | int compare = ((Comparable) qIn.front()).compareTo(pivot); 89 | if (compare > 0) { 90 | qLarge.enqueue(qIn.dequeue()); 91 | } else if (compare < 0) { 92 | qSmall.enqueue(qIn.dequeue()); 93 | } else { 94 | qEquals.enqueue(qIn.dequeue()); 95 | } 96 | } catch (QueueEmptyException e) { 97 | e.printStackTrace(); 98 | } 99 | // Your solution here. 100 | } 101 | 102 | /** 103 | * mergeSort() sorts q from smallest to largest using mergesort. 104 | * 105 | * @param q is a LinkedQueue of Comparable objects. 106 | */ 107 | public static void mergeSort(LinkedQueue p) { 108 | if (p.size() <= 1) { 109 | return; 110 | } 111 | LinkedQueue q = makeQueueOfQueues(p); 112 | try { 113 | while (q.size() > 1) { 114 | LinkedQueue q1 = (LinkedQueue) q.dequeue(); 115 | LinkedQueue q2 = (LinkedQueue) q.dequeue(); 116 | q.enqueue(mergeSortedQueues(q1, q2)); 117 | } 118 | p.append((LinkedQueue) q.dequeue()); 119 | } catch (QueueEmptyException e) { 120 | e.printStackTrace(); 121 | } 122 | // Your solution here. 123 | } 124 | 125 | /** 126 | * quickSort() sorts q from smallest to largest using quicksort. 127 | * 128 | * @param q is a LinkedQueue of Comparable objects. 129 | */ 130 | public static void quickSort(LinkedQueue q) { 131 | if (q.size() <= 1) { 132 | return; 133 | } 134 | int nth = (int) (q.size() * Math.random() + 1); 135 | LinkedQueue lSmaller = new LinkedQueue(); 136 | LinkedQueue lLarger = new LinkedQueue(); 137 | LinkedQueue lEqual = new LinkedQueue(); 138 | partition(q, (Comparable) q.nth(nth), lSmaller, lEqual, lLarger); 139 | quickSort(lSmaller); 140 | quickSort(lLarger); 141 | q.append(lSmaller); 142 | q.append(lEqual); 143 | q.append(lLarger); 144 | // Your solution here. 145 | } 146 | 147 | /** 148 | * makeRandom() builds a LinkedQueue of the indicated size containing 149 | * Integer items. The items are randomly chosen between 0 and size - 1. 150 | * 151 | * @param size is the size of the resulting LinkedQueue. 152 | */ 153 | public static LinkedQueue makeRandom(int size) { 154 | LinkedQueue q = new LinkedQueue(); 155 | for (int i = 0; i < size; i++) { 156 | q.enqueue(new Integer((int) (size * Math.random()))); 157 | } 158 | return q; 159 | } 160 | 161 | /** 162 | * main() performs some tests on mergesort and quicksort. Feel free to add 163 | * more tests of your own to make sure your algorithms works on boundary 164 | * cases. Your test code will not be graded. 165 | */ 166 | public static void main(String[] args) { 167 | 168 | LinkedQueue q = makeRandom(10); 169 | System.out.println(q.toString()); 170 | mergeSort(q); 171 | System.out.println(q.toString()); 172 | 173 | q = makeRandom(10); 174 | System.out.println(q.toString()); 175 | quickSort(q); 176 | System.out.println(q.toString()); 177 | 178 | // /* Remove these comments for Part III. 179 | 180 | int SORTSIZE; 181 | 182 | for (SORTSIZE = 1000; SORTSIZE <= 1000000; SORTSIZE *= 10) { 183 | Timer stopWatch = new Timer(); 184 | q = makeRandom(SORTSIZE); 185 | stopWatch.start(); 186 | mergeSort(q); 187 | stopWatch.stop(); 188 | System.out.println("Mergesort time, " + SORTSIZE + " Integers: " + 189 | stopWatch.elapsed() + " msec."); 190 | 191 | stopWatch.reset(); 192 | q = makeRandom(SORTSIZE); 193 | stopWatch.start(); 194 | quickSort(q); 195 | stopWatch.stop(); 196 | System.out.println("Quicksort time, " + SORTSIZE + " Integers: " + 197 | stopWatch.elapsed() + " msec."); 198 | } 199 | // */ 200 | } 201 | 202 | } 203 | -------------------------------------------------------------------------------- /hw4/list/DList.java: -------------------------------------------------------------------------------- 1 | /* DList.java */ 2 | 3 | package hw4.list; 4 | 5 | /** 6 | * A DList is a mutable doubly-linked list ADT. Its implementation is 7 | * circularly-linked and employs a sentinel (dummy) node at the head 8 | * of the list. 9 | *

10 | * DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE. 11 | */ 12 | 13 | public class DList { 14 | 15 | /** 16 | * head references the sentinel node. 17 | * size is the number of items in the list. (The sentinel node does not 18 | * store an item.) 19 | *

20 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS. 21 | */ 22 | 23 | protected DListNode head; 24 | protected int size; 25 | 26 | /* DList invariants: 27 | * 1) head != null. 28 | * 2) For any DListNode x in a DList, x.next != null. 29 | * 3) For any DListNode x in a DList, x.prev != null. 30 | * 4) For any DListNode x in a DList, if x.next == y, then y.prev == x. 31 | * 5) For any DListNode x in a DList, if x.prev == y, then y.next == x. 32 | * 6) size is the number of DListNodes, NOT COUNTING the sentinel, 33 | * that can be accessed from the sentinel (head) by a sequence of 34 | * "next" references. 35 | */ 36 | 37 | /** 38 | * newNode() calls the DListNode constructor. Use this class to allocate 39 | * new DListNodes rather than calling the DListNode constructor directly. 40 | * That way, only this method needs to be overridden if a subclass of DList 41 | * wants to use a different kind of node. 42 | * 43 | * @param item the item to store in the node. 44 | * @param prev the node previous to this node. 45 | * @param next the node following this node. 46 | */ 47 | protected DListNode newNode(Object item, DListNode prev, DListNode next) { 48 | return new DListNode(item, prev, next); 49 | } 50 | 51 | /** 52 | * DList() constructor for an empty DList. 53 | */ 54 | public DList() { 55 | head = newNode(null, null, null); 56 | head.next = head; 57 | head.prev = head; 58 | size = 0; 59 | } 60 | 61 | /** 62 | * isEmpty() returns true if this DList is empty, false otherwise. 63 | * 64 | * @return true if this DList is empty, false otherwise. 65 | * Performance: runs in O(1) time. 66 | */ 67 | public boolean isEmpty() { 68 | return size == 0; 69 | } 70 | 71 | /** 72 | * length() returns the length of this DList. 73 | * 74 | * @return the length of this DList. 75 | * Performance: runs in O(1) time. 76 | */ 77 | public int length() { 78 | return size; 79 | } 80 | 81 | /** 82 | * insertFront() inserts an item at the front of this DList. 83 | * 84 | * @param item is the item to be inserted. 85 | * Performance: runs in O(1) time. 86 | */ 87 | public void insertFront(Object item) { 88 | DListNode newNode = newNode(item, head, head.next); 89 | head.next.prev = newNode; 90 | head.next = newNode; 91 | size++; 92 | } 93 | 94 | /** 95 | * insertBack() inserts an item at the back of this DList. 96 | * 97 | * @param item is the item to be inserted. 98 | * Performance: runs in O(1) time. 99 | */ 100 | public void insertBack(Object item) { 101 | DListNode newNode = newNode(item, head.prev, head); 102 | head.prev.next = newNode; 103 | head.prev = newNode; 104 | size++; 105 | } 106 | 107 | /** 108 | * front() returns the node at the front of this DList. If the DList is 109 | * empty, return null. 110 | *

111 | * Do NOT return the sentinel under any circumstances! 112 | * 113 | * @return the node at the front of this DList. 114 | * Performance: runs in O(1) time. 115 | */ 116 | public DListNode front() { 117 | if (isEmpty()) { 118 | return null; 119 | } else { 120 | return head.next; 121 | } 122 | } 123 | 124 | /** 125 | * back() returns the node at the back of this DList. If the DList is 126 | * empty, return null. 127 | *

128 | * Do NOT return the sentinel under any circumstances! 129 | * 130 | * @return the node at the back of this DList. 131 | * Performance: runs in O(1) time. 132 | */ 133 | public DListNode back() { 134 | if (isEmpty()) { 135 | return null; 136 | } else { 137 | return head.prev; 138 | } 139 | } 140 | 141 | /** 142 | * next() returns the node following "node" in this DList. If "node" is 143 | * null, or "node" is the last node in this DList, return null. 144 | *

145 | * Do NOT return the sentinel under any circumstances! 146 | * 147 | * @param node the node whose successor is sought. 148 | * @return the node following "node". 149 | * Performance: runs in O(1) time. 150 | */ 151 | public DListNode next(DListNode node) { 152 | if (node.next == head) { 153 | return null; 154 | } else { 155 | return node.next; 156 | } 157 | } 158 | 159 | /** 160 | * prev() returns the node prior to "node" in this DList. If "node" is 161 | * null, or "node" is the first node in this DList, return null. 162 | *

163 | * Do NOT return the sentinel under any circumstances! 164 | * 165 | * @param node the node whose predecessor is sought. 166 | * @return the node prior to "node". 167 | * Performance: runs in O(1) time. 168 | */ 169 | public DListNode prev(DListNode node) { 170 | if (node.prev == head) { 171 | return null; 172 | } else { 173 | return node.prev; 174 | } 175 | } 176 | 177 | /** 178 | * insertAfter() inserts an item in this DList immediately following "node". 179 | * If "node" is null, do nothing. 180 | * 181 | * @param item the item to be inserted. 182 | * @param node the node to insert the item after. 183 | * Performance: runs in O(1) time. 184 | */ 185 | public void insertAfter(Object item, DListNode node) { 186 | if (node == null) { 187 | return; 188 | } else { 189 | DListNode newNode = newNode(item, node, node.next); 190 | node.next = newNode; 191 | newNode.next.prev = newNode; 192 | } 193 | size++; 194 | } 195 | 196 | /** 197 | * insertBefore() inserts an item in this DList immediately before "node". 198 | * If "node" is null, do nothing. 199 | * 200 | * @param item the item to be inserted. 201 | * @param node the node to insert the item before. 202 | * Performance: runs in O(1) time. 203 | */ 204 | public void insertBefore(Object item, DListNode node) { 205 | if (node == null) { 206 | return; 207 | } else { 208 | DListNode newNode = newNode(item, node.prev, node); 209 | newNode.prev.next = newNode; 210 | node.prev = newNode; 211 | } 212 | size++; 213 | } 214 | 215 | /** 216 | * remove() removes "node" from this DList. If "node" is null, do nothing. 217 | * Performance: runs in O(1) time. 218 | */ 219 | public void remove(DListNode node) { 220 | if (node == null) { 221 | return; 222 | } else { 223 | node.prev.next = node.next; 224 | node.next.prev = node.prev; 225 | } 226 | size--; 227 | } 228 | 229 | /** 230 | * toString() returns a String representation of this DList. 231 | *

232 | * DO NOT CHANGE THIS METHOD. 233 | * 234 | * @return a String representation of this DList. 235 | * Performance: runs in O(n) time, where n is the length of the list. 236 | */ 237 | public String toString() { 238 | String result = "[ "; 239 | DListNode current = head.next; 240 | while (current != head) { 241 | result = result + current.item + " "; 242 | current = current.next; 243 | } 244 | return result + "]"; 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /hw6/dict/HashTableChained.java: -------------------------------------------------------------------------------- 1 | /* HashTableChained.java */ 2 | 3 | package hw6.dict; 4 | 5 | import hw5.list.*; 6 | 7 | import java.util.Random; 8 | 9 | /** 10 | * HashTableChained implements a Dictionary as a hashList table with chaining. 11 | * All objects used as keys must have a valid hashCode() method, which is 12 | * used to determine which bucket of the hashList table an entry is stored in. 13 | * Each object's hashCode() is presumed to return an int between 14 | * Integer.MIN_VALUE and Integer.MAX_VALUE. The HashTableChained class 15 | * implements only the compression function, which maps the hashList code to 16 | * a bucket in the table's range. 17 | *

18 | * DO NOT CHANGE ANY PROTOTYPES IN THIS FILE. 19 | */ 20 | 21 | public class HashTableChained implements Dictionary { 22 | 23 | /** 24 | * Place any data fields here. 25 | */ 26 | public int hashSize; 27 | protected SList[] hashList; 28 | protected int entryNumber = 0; 29 | public int collision = 0; 30 | 31 | /** 32 | * Construct a new empty hashList table intended to hold roughly sizeEstimate 33 | * entries. (The precise number of buckets is up to you, but we recommend 34 | * you use a prime number, and shoot for a load factor between 0.5 and 1.) 35 | */ 36 | 37 | public HashTableChained(int sizeEstimate) { 38 | LOOP: 39 | for (int i = sizeEstimate; ; i++) { 40 | for (int j = 2; j < Math.sqrt(i); j++) { 41 | if (i % j == 0) { 42 | continue LOOP; 43 | } 44 | } 45 | hashSize = i; 46 | break; 47 | } 48 | arrayInit(); 49 | // Your solution here. 50 | } 51 | 52 | /** 53 | * Construct a new empty hashList table with a default size. Say, a prime in 54 | * the neighborhood of 100. 55 | */ 56 | 57 | public HashTableChained() { 58 | hashSize = 101; 59 | arrayInit(); 60 | // Your solution here. 61 | } 62 | 63 | protected void arrayInit() { 64 | hashList = new SList[hashSize]; 65 | for (int i = 0; i < hashSize; i++) { 66 | hashList[i] = new SList(); 67 | } 68 | } 69 | 70 | /** 71 | * Converts a hashList code in the range Integer.MIN_VALUE...Integer.MAX_VALUE 72 | * to a value in the range 0...(size of hashList table) - 1. 73 | *

74 | * This function should have package protection (so we can test it), and 75 | * should be used by insert, find, and remove. 76 | */ 77 | 78 | int compFunction(int code) { 79 | // long largePrime; 80 | // for (long i = (long)Math.pow(hashSize,3); ; i++) { 81 | // for (int j = 2; j < Math.sqrt(i); j++) { 82 | // if (i % j == 0) { 83 | // break; 84 | // } 85 | // } 86 | // largePrime = i; 87 | // break; 88 | // } 89 | // // Replace the following line with your solution. 90 | // return Math.abs((int)(((long)23 * code + 47) % largePrime) % hashSize); 91 | return Math.abs(code % hashSize); 92 | } 93 | 94 | /** 95 | * Returns the number of entries stored in the dictionary. Entries with 96 | * the same key (or even the same key and value) each still count as 97 | * a separate entry. 98 | * 99 | * @return number of entries in the dictionary. 100 | */ 101 | 102 | public int size() { 103 | // Replace the following line with your solution. 104 | return entryNumber; 105 | } 106 | 107 | /** 108 | * Tests if the dictionary is empty. 109 | * 110 | * @return true if the dictionary has no entries; false otherwise. 111 | */ 112 | 113 | public boolean isEmpty() { 114 | return entryNumber == 0; 115 | } 116 | 117 | /** 118 | * Create a new Entry object referencing the input key and associated value, 119 | * and insert the entry into the dictionary. Return a reference to the new 120 | * entry. Multiple entries with the same key (or even the same key and 121 | * value) can coexist in the dictionary. 122 | *

123 | * This method should run in O(1) time if the number of collisions is small. 124 | * 125 | * @param key the key by which the entry can be retrieved. 126 | * @param value an arbitrary object. 127 | * @return an entry containing the key and value. 128 | */ 129 | 130 | public Entry insert(Object key, Object value) { 131 | Entry item = new Entry(); 132 | item.key = key; 133 | item.value = value; 134 | SList hashNode = hashList[compFunction(key.hashCode())]; 135 | if (!hashNode.isEmpty()) { 136 | collision++; 137 | } 138 | hashNode.insertFront(item); 139 | entryNumber++; 140 | 141 | // Replace the following line with your solution. 142 | return item; 143 | } 144 | 145 | /** 146 | * Search for an entry with the specified key. If such an entry is found, 147 | * return it; otherwise return null. If several entries have the specified 148 | * key, choose one arbitrarily and return it. 149 | *

150 | * This method should run in O(1) time if the number of collisions is small. 151 | * 152 | * @param key the search key. 153 | * @return an entry containing the key and an associated value, or null if 154 | * no entry contains the specified key. 155 | */ 156 | 157 | public Entry find(Object key) { 158 | SList hashNode = hashList[compFunction(key.hashCode())]; 159 | ListNode currentNode = hashNode.front(); 160 | while (currentNode.isValidNode()) { 161 | try { 162 | if (((Entry) currentNode.item()).key().equals(key)) { 163 | return ((Entry) currentNode.item()); 164 | } else { 165 | currentNode = currentNode.next(); 166 | } 167 | } catch (InvalidNodeException e) { 168 | e.printStackTrace(); 169 | } 170 | } 171 | return null; 172 | // Replace the following line with your solution. 173 | } 174 | 175 | /** 176 | * Remove an entry with the specified key. If such an entry is found, 177 | * remove it from the table and return it; otherwise return null. 178 | * If several entries have the specified key, choose one arbitrarily, then 179 | * remove and return it. 180 | *

181 | * This method should run in O(1) time if the number of collisions is small. 182 | * 183 | * @param key the search key. 184 | * @return an entry containing the key and an associated value, or null if 185 | * no entry contains the specified key. 186 | */ 187 | 188 | public Entry remove(Object key) { 189 | SList hashNode = hashList[compFunction(key.hashCode())]; 190 | ListNode currentNode = hashNode.front(); 191 | while (currentNode.isValidNode()) { 192 | try { 193 | if (((Entry) currentNode.item()).key().equals(key)) { 194 | Entry entry = (Entry) currentNode.item(); 195 | currentNode.remove(); 196 | entryNumber--; 197 | return entry; 198 | } else { 199 | currentNode = currentNode.next(); 200 | } 201 | } catch (InvalidNodeException e) { 202 | e.printStackTrace(); 203 | } 204 | } 205 | return null; 206 | // Replace the following line with your solution. 207 | } 208 | 209 | /** 210 | * Remove all entries from the dictionary. 211 | */ 212 | public void makeEmpty() { 213 | arrayInit(); 214 | // Your solution here. 215 | } 216 | 217 | @Override 218 | public String toString() { 219 | String hashString = ""; 220 | for (int i = 0; i < hashSize; i++) { 221 | if (!hashList[i].isEmpty()) { 222 | hashString += i + " :" + hashList[i] + "\n"; 223 | } 224 | } 225 | return hashString; 226 | } 227 | 228 | public static double expectedRate(int n, int N) { 229 | return n - N + N * Math.pow(1 - 1 / (double) N, n); 230 | } 231 | 232 | public static void main(String[] args) { 233 | HashTableChained hash = new HashTableChained(100); 234 | Random rand = new Random(1); 235 | for (int i = 20; i > 0; i--) { 236 | hash.insert(Math.abs(rand.nextInt()), i); 237 | } 238 | 239 | 240 | System.out.println(hash); 241 | System.out.println(hash.collision); 242 | System.out.printf("%.2f", expectedRate(20, 100)); 243 | // 244 | // System.out.println("1".hashCode()); 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /hw5/Set.java: -------------------------------------------------------------------------------- 1 | /* Set.java */ 2 | 3 | package hw5; 4 | 5 | import hw5.list.*; 6 | 7 | /** 8 | * A Set is a collection of Comparable elements stored in sorted order. 9 | * Duplicate elements are not permitted in a Set. 10 | */ 11 | public class Set { 12 | /* Fill in the data fields here. */ 13 | 14 | private List setList; 15 | /** 16 | * Set ADT invariants: 17 | * 1) The Set's elements must be precisely the elements of the List. 18 | * 2) The List must always contain Comparable elements, and those elements 19 | * must always be sorted in ascending order. 20 | * 3) No two elements in the List may be equal according to compareTo(). 21 | **/ 22 | 23 | /** 24 | * Constructs an empty Set. 25 | *

26 | * Performance: runs in O(1) time. 27 | */ 28 | public Set() { 29 | setList = new DList(); 30 | // Your solution here. 31 | } 32 | 33 | /** 34 | * cardinality() returns the number of elements in this Set. 35 | *

36 | * Performance: runs in O(1) time. 37 | */ 38 | public int cardinality() { 39 | // Replace the following line with your solution. 40 | return setList.length(); 41 | } 42 | 43 | /** 44 | * insert() inserts a Comparable element into this Set. 45 | *

46 | * Sets are maintained in sorted order. The ordering is specified by the 47 | * compareTo() method of the java.lang.Comparable interface. 48 | *

49 | * Performance: runs in O(this.cardinality()) time. 50 | */ 51 | public void insert(Comparable c) { 52 | if (cardinality() == 0) { 53 | setList.insertFront(c); 54 | } else { 55 | ListNode node = setList.front(); 56 | try { 57 | while (c.compareTo(node.item()) != 0) { 58 | if (c.compareTo(node.item()) > 0) { 59 | node = node.next(); 60 | } else { 61 | node.insertBefore(c); 62 | break; 63 | } 64 | if (!node.isValidNode()) { 65 | setList.back().insertAfter(c); 66 | break; 67 | } 68 | } 69 | } catch (InvalidNodeException e) { 70 | e.printStackTrace(); 71 | } 72 | } 73 | // Your solution here. 74 | } 75 | 76 | /** 77 | * union() modifies this Set so that it contains all the elements it 78 | * started with, plus all the elements of s. The Set s is NOT modified. 79 | * Make sure that duplicate elements are not created. 80 | *

81 | * Performance: Must run in O(this.cardinality() + s.cardinality()) time. 82 | *

83 | * Your implementation should NOT copy elements of s or "this", though it 84 | * will copy _references_ to the elements of s. Your implementation will 85 | * create new _nodes_ for the elements of s that are added to "this", but 86 | * you should reuse the nodes that are already part of "this". 87 | *

88 | * DO NOT MODIFY THE SET s. 89 | * DO NOT ATTEMPT TO COPY ELEMENTS; just copy _references_ to them. 90 | */ 91 | public void union(Set s) { 92 | ListNode thisSetNode = setList.front(); 93 | ListNode sNode = s.setList.front(); 94 | try { 95 | while (sNode.isValidNode()) { 96 | if (!thisSetNode.isValidNode()) { 97 | setList.back().insertAfter(sNode.item()); 98 | 99 | sNode = sNode.next(); 100 | continue; 101 | } 102 | 103 | if (compareItem(sNode, thisSetNode) > 0) { 104 | thisSetNode = thisSetNode.next(); 105 | continue; 106 | } else if (compareItem(sNode, thisSetNode) < 0) { 107 | thisSetNode.insertBefore(sNode.item()); 108 | sNode = sNode.next(); 109 | continue; 110 | } else { 111 | sNode = sNode.next(); 112 | } 113 | } 114 | } catch (InvalidNodeException e) { 115 | e.printStackTrace(); 116 | } 117 | // Your solution here. 118 | } 119 | 120 | private int compareItem(ListNode node1, ListNode node2) { 121 | try { 122 | if (((Comparable) node1.item()).compareTo((Comparable) node2.item()) == 0) { 123 | return 0; 124 | } else if (((Comparable) node1.item()).compareTo((Comparable) node2.item()) > 0) { 125 | return 1; 126 | } else { 127 | return -1; 128 | } 129 | } catch (InvalidNodeException e) { 130 | e.printStackTrace(); 131 | return -1; 132 | } 133 | } 134 | 135 | /** 136 | * intersect() modifies this Set so that it contains the intersection of 137 | * its own elements and the elements of s. The Set s is NOT modified. 138 | *

139 | * Performance: Must run in O(this.cardinality() + s.cardinality()) time. 140 | *

141 | * Do not construct any new ListNodes during the execution of intersect. 142 | * Reuse the nodes of "this" that will be in the intersection. 143 | *

144 | * DO NOT MODIFY THE SET s. 145 | * DO NOT CONSTRUCT ANY NEW NODES. 146 | * DO NOT ATTEMPT TO COPY ELEMENTS. 147 | */ 148 | public void intersect(Set s) { 149 | ListNode thisNode = setList.front(); 150 | ListNode sNode = s.setList.front(); 151 | 152 | try { 153 | 154 | while (thisNode.isValidNode()) { 155 | if (!sNode.isValidNode()) { 156 | if (!thisNode.next().isValidNode()) { 157 | thisNode.remove(); 158 | break; 159 | } else { 160 | thisNode = thisNode.next(); 161 | thisNode.prev().remove(); 162 | continue; 163 | } 164 | } 165 | 166 | if (compareItem(thisNode, sNode) == 0) { 167 | thisNode = thisNode.next(); 168 | sNode = sNode.next(); 169 | continue; 170 | } else if (compareItem(thisNode, sNode) > 0) { 171 | sNode = sNode.next(); 172 | continue; 173 | } else { 174 | thisNode = thisNode.next(); 175 | thisNode.prev().remove(); 176 | } 177 | } 178 | } catch (InvalidNodeException e) { 179 | e.printStackTrace(); 180 | } 181 | 182 | // Your solution here. 183 | } 184 | 185 | /** 186 | * toString() returns a String representation of this Set. The String must 187 | * have the following format: 188 | * { } for an empty Set. No spaces before "{" or after "}"; two spaces 189 | * between them. 190 | * { 1 2 3 } for a Set of three Integer elements. No spaces before 191 | * "{" or after "}"; two spaces before and after each element. 192 | * Elements are printed with their own toString method, whatever 193 | * that may be. The elements must appear in sorted order, from 194 | * lowest to highest according to the compareTo() method. 195 | *

196 | * WARNING: THE AUTOGRADER EXPECTS YOU TO PRINT SETS IN _EXACTLY_ THIS 197 | * FORMAT, RIGHT UP TO THE TWO SPACES BETWEEN ELEMENTS. ANY 198 | * DEVIATIONS WILL LOSE POINTS. 199 | */ 200 | public String toString() { 201 | if (setList.isEmpty()) { 202 | return "{ }"; 203 | } else { 204 | String setString = "{ "; 205 | try { 206 | ListNode node = setList.front(); 207 | while (node.isValidNode()) { 208 | setString += node.item() + " "; 209 | node = node.next(); 210 | } 211 | setString += "}"; 212 | } catch (InvalidNodeException e) { 213 | e.printStackTrace(); 214 | } 215 | return setString; 216 | } 217 | // Replace the following line with your solution. 218 | } 219 | 220 | public static void main(String[] argv) { 221 | Set s = new Set(); 222 | s.insert(new Integer(3)); 223 | s.insert(new Integer(4)); 224 | s.insert(new Integer(5)); 225 | s.insert(new Integer(6)); 226 | s.insert(new Integer(7)); 227 | s.insert(new Integer(8)); 228 | s.insert(new Integer(5)); 229 | System.out.println("Set s = " + s); 230 | 231 | Set s2 = new Set(); 232 | s2.insert(new Integer(1)); 233 | s2.insert(new Integer(4)); 234 | s2.insert(new Integer(5)); 235 | System.out.println("Set s2 = " + s2); 236 | 237 | Set s3 = new Set(); 238 | s3.insert(new Integer(5)); 239 | s3.insert(new Integer(3)); 240 | s3.insert(new Integer(8)); 241 | System.out.println("Set s3 = " + s3); 242 | 243 | s.union(s2); 244 | System.out.println("After s.union(s2), s = " + s); 245 | 246 | s.intersect(s3); 247 | System.out.println("After s.intersect(s3), s = " + s); 248 | 249 | System.out.println("s.cardinality() = " + s.cardinality()); 250 | 251 | Set s4 = new Set(); 252 | System.out.println("Empty Set s4 = " + s4); 253 | 254 | System.out.println("s4.cardinality() = " + s4.cardinality()); 255 | 256 | s4.union(s4); 257 | System.out.println("After s4.union(s4), s4 = " + s4); 258 | 259 | s4.intersect(s4); 260 | System.out.println("After s4.intersect(s4), s4 = " + s4); 261 | 262 | s3.union(s4); 263 | System.out.println("After s3.union(s4), s3 = " + s3); 264 | 265 | s3.intersect(s4); 266 | System.out.println("After s3.intersect(s4), s3 = " + s3); 267 | 268 | // You may want to add more (ungraded) test code here. 269 | } 270 | } 271 | -------------------------------------------------------------------------------- /hw5/list/SList.java: -------------------------------------------------------------------------------- 1 | /* SList.java */ 2 | 3 | package hw5.list; 4 | 5 | /** 6 | * A SList is a mutable singly-linked list ADT. Its implementation employs 7 | * a tail reference. 8 | *

9 | * DO NOT CHANGE THIS FILE. 10 | */ 11 | 12 | public class SList extends List { 13 | 14 | /** 15 | * (inherited) size is the number of items in the list. 16 | * head references the first node. 17 | * tail references the last node. 18 | */ 19 | 20 | protected SListNode head; 21 | protected SListNode tail; 22 | 23 | /* SList invariants: 24 | * 1) Either head == null and tail == null, or tail.next == null and the 25 | * SListNode referenced by tail can be reached from the head by a 26 | * sequence of zero or more "next" references. This implies that the 27 | * list is not circularly linked. 28 | * 2) The "size" field is the number of SListNodes that can be accessed 29 | * from head (including head itself) by a sequence of "next" references. 30 | * 3) For every SListNode x in an SList l, x.myList = l. 31 | **/ 32 | 33 | /** 34 | * newNode() calls the SListNode constructor. Use this method to allocate 35 | * new SListNodes rather than calling the SListNode constructor directly. 36 | * That way, only this method need be overridden if a subclass of SList 37 | * wants to use a different kind of node. 38 | * 39 | * @param item the item to store in the node. 40 | * @param next the node following this node. 41 | */ 42 | protected SListNode newNode(Object item, SListNode next) { 43 | return new SListNode(item, this, next); 44 | } 45 | 46 | /** 47 | * SList() constructs for an empty SList. 48 | */ 49 | public SList() { 50 | head = null; 51 | tail = null; 52 | size = 0; 53 | } 54 | 55 | /** 56 | * insertFront() inserts an item at the front of this SList. 57 | * 58 | * @param item is the item to be inserted. 59 | *

60 | * Performance: runs in O(1) time. 61 | */ 62 | public void insertFront(Object item) { 63 | head = newNode(item, head); 64 | if (size == 0) { 65 | tail = head; 66 | } 67 | size++; 68 | } 69 | 70 | /** 71 | * insertBack() inserts an item at the back of this SList. 72 | * 73 | * @param item is the item to be inserted. 74 | *

75 | * Performance: runs in O(1) time. 76 | */ 77 | public void insertBack(Object item) { 78 | if (head == null) { 79 | head = newNode(item, null); 80 | tail = head; 81 | } else { 82 | tail.next = newNode(item, null); 83 | tail = tail.next; 84 | } 85 | size++; 86 | } 87 | 88 | /** 89 | * front() returns the node at the front of this SList. If the SList is 90 | * empty, return an "invalid" node--a node with the property that any 91 | * attempt to use it will cause an exception. 92 | * 93 | * @return a ListNode at the front of this SList. 94 | *

95 | * Performance: runs in O(1) time. 96 | */ 97 | public ListNode front() { 98 | if (head == null) { 99 | // Create an invalid node. 100 | SListNode node = newNode(null, null); 101 | node.myList = null; 102 | return node; 103 | } else { 104 | return head; 105 | } 106 | } 107 | 108 | /** 109 | * back() returns the node at the back of this SList. If the SList is 110 | * empty, return an "invalid" node--a node with the property that any 111 | * attempt to use it will cause an exception. 112 | * 113 | * @return a ListNode at the back of this SList. 114 | *

115 | * Performance: runs in O(1) time. 116 | */ 117 | public ListNode back() { 118 | if (tail == null) { 119 | // Create an invalid node. 120 | SListNode node = newNode(null, null); 121 | node.myList = null; 122 | return node; 123 | } else { 124 | return tail; 125 | } 126 | } 127 | 128 | /** 129 | * toString() returns a String representation of this SList. 130 | * 131 | * @return a String representation of this SList. 132 | *

133 | * Performance: runs in O(n) time, where n is the length of the list. 134 | */ 135 | public String toString() { 136 | String result = "[ "; 137 | SListNode current = head; 138 | while (current != null) { 139 | result = result + current.item + " "; 140 | current = current.next; 141 | } 142 | return result + "]"; 143 | } 144 | 145 | private static void testInvalidNode(ListNode p) { 146 | System.out.println("p.isValidNode() should be false: " + p.isValidNode()); 147 | try { 148 | p.item(); 149 | System.out.println("p.item() should throw an exception, but didn't."); 150 | } catch (InvalidNodeException lbe) { 151 | System.out.println("p.item() should throw an exception, and did."); 152 | } 153 | try { 154 | p.setItem(new Integer(0)); 155 | System.out.println("p.setItem() should throw an exception, but didn't."); 156 | } catch (InvalidNodeException lbe) { 157 | System.out.println("p.setItem() should throw an exception, and did."); 158 | } 159 | try { 160 | p.next(); 161 | System.out.println("p.next() should throw an exception, but didn't."); 162 | } catch (InvalidNodeException lbe) { 163 | System.out.println("p.next() should throw an exception, and did."); 164 | } 165 | try { 166 | p.prev(); 167 | System.out.println("p.prev() should throw an exception, but didn't."); 168 | } catch (InvalidNodeException lbe) { 169 | System.out.println("p.prev() should throw an exception, and did."); 170 | } 171 | try { 172 | p.insertBefore(new Integer(1)); 173 | System.out.println("p.insertBefore() should throw an exception, but " + 174 | "didn't."); 175 | } catch (InvalidNodeException lbe) { 176 | System.out.println("p.insertBefore() should throw an exception, and did." 177 | ); 178 | } 179 | try { 180 | p.insertAfter(new Integer(1)); 181 | System.out.println("p.insertAfter() should throw an exception, but " + 182 | "didn't."); 183 | } catch (InvalidNodeException lbe) { 184 | System.out.println("p.insertAfter() should throw an exception, and did." 185 | ); 186 | } 187 | try { 188 | p.remove(); 189 | System.out.println("p.remove() should throw an exception, but didn't."); 190 | } catch (InvalidNodeException lbe) { 191 | System.out.println("p.remove() should throw an exception, and did."); 192 | } 193 | } 194 | 195 | private static void testEmpty() { 196 | List l = new SList(); 197 | System.out.println("An empty list should be [ ]: " + l); 198 | System.out.println("l.isEmpty() should be true: " + l.isEmpty()); 199 | System.out.println("l.length() should be 0: " + l.length()); 200 | System.out.println("Finding front node p of l."); 201 | ListNode p = l.front(); 202 | testInvalidNode(p); 203 | System.out.println("Finding back node p of l."); 204 | p = l.back(); 205 | testInvalidNode(p); 206 | l.insertFront(new Integer(10)); 207 | System.out.println("l after insertFront(10) should be [ 10 ]: " + l); 208 | } 209 | 210 | public static void main(String[] argv) { 211 | testEmpty(); 212 | List l = new SList(); 213 | l.insertFront(new Integer(3)); 214 | l.insertFront(new Integer(2)); 215 | l.insertFront(new Integer(1)); 216 | System.out.println("l is a list of 3 elements: " + l); 217 | try { 218 | ListNode n; 219 | int i = 1; 220 | for (n = l.front(); n.isValidNode(); n = n.next()) { 221 | System.out.println("n.item() should be " + i + ": " + n.item()); 222 | n.setItem(new Integer(((Integer) n.item()).intValue() * 2)); 223 | System.out.println("n.item() should be " + 2 * i + ": " + n.item()); 224 | i++; 225 | } 226 | System.out.println("After doubling all elements of l: " + l); 227 | testInvalidNode(n); 228 | 229 | i = 6; 230 | for (n = l.back(); n.isValidNode(); n = n.prev()) { 231 | System.out.println("n.item() should be " + i + ": " + n.item()); 232 | n.setItem(new Integer(((Integer) n.item()).intValue() * 2)); 233 | System.out.println("n.item() should be " + 2 * i + ": " + n.item()); 234 | i = i - 2; 235 | } 236 | System.out.println("After doubling all elements of l again: " + l); 237 | testInvalidNode(n); 238 | 239 | n = l.front().next(); 240 | System.out.println("Removing middle element (8) of l: " + n.item()); 241 | n.remove(); 242 | System.out.println("l is now: " + l); 243 | testInvalidNode(n); 244 | n = l.back(); 245 | System.out.println("Removing end element (12) of l: " + n.item()); 246 | n.remove(); 247 | System.out.println("l is now: " + l); 248 | testInvalidNode(n); 249 | 250 | n = l.front(); 251 | System.out.println("Removing first element (4) of l: " + n.item()); 252 | n.remove(); 253 | System.out.println("l is now: " + l); 254 | testInvalidNode(n); 255 | } catch (InvalidNodeException lbe) { 256 | System.err.println("Caught InvalidNodeException that should not happen." 257 | ); 258 | System.err.println("Aborting the testing code."); 259 | } 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /hw2/Date.java: -------------------------------------------------------------------------------- 1 | /* Date.java */ 2 | 3 | class Date { 4 | private int month; 5 | private int day; 6 | private int year; 7 | 8 | private int days; 9 | 10 | /* Put your private data fields here. */ 11 | 12 | /** 13 | * Constructs a date with the given month, day and year. If the date is 14 | * not valid, the entire program will halt with an error message. 15 | * 16 | * @param month is a month, numbered in the range 1...12. 17 | * @param day is between 1 and the number of days in the given month. 18 | * @param year is the year in question, with no digits omitted. 19 | */ 20 | public Date(int month, int day, int year) { 21 | if (isValidDate(month, day, year)) { 22 | this.day = day; 23 | this.month = month; 24 | this.year = year; 25 | } else { 26 | System.out.println("Invalid Date, Program exits"); 27 | System.exit(0); 28 | } 29 | 30 | for (int i = 1; i < year; i++) { 31 | days += dayInYear(i); 32 | } 33 | for (int i = 1; i < month; i++) { 34 | days += daysInMonth(i, year); 35 | } 36 | days += day; 37 | } 38 | 39 | /** 40 | * Constructs a Date object corresponding to the given string. 41 | * 42 | * @param s should be a string of the form "month/day/year" where month must 43 | * be one or two digits, day must be one or two digits, and year must be 44 | * between 1 and 4 digits. If s does not match these requirements or is not 45 | * a valid date, the program halts with an error message. 46 | */ 47 | public Date(String s) { 48 | int[] position = new int[2]; 49 | 50 | for (int i = 0, j = 0; i < s.length(); i++) { 51 | if (s.charAt(i) == '/') { 52 | position[j++] = i; 53 | } 54 | } 55 | 56 | month = Integer.parseInt(s.substring(0, position[0])); 57 | day = Integer.parseInt(s.substring(position[0] + 1, position[1])); 58 | year = Integer.parseInt(s.substring(position[1] + 1)); 59 | 60 | if (!isValidDate(month, day, year)) { 61 | System.out.println("Invalid Date, Program exits"); 62 | System.exit(0); 63 | } 64 | 65 | for (int i = 1; i < year; i++) { 66 | days += dayInYear(i); 67 | } 68 | for (int i = 1; i < month; i++) { 69 | days += daysInMonth(i, year); 70 | } 71 | days += day; 72 | } 73 | 74 | /** 75 | * Checks whether the given year is a leap year. 76 | * 77 | * @return true if and only if the input year is a leap year. 78 | */ 79 | public static boolean isLeapYear(int year) { 80 | boolean leapYear = false; 81 | if (year % 4 == 0) { 82 | leapYear = true; 83 | 84 | if (year % 100 == 0) { 85 | leapYear = false; 86 | 87 | if (year % 400 == 0) { 88 | leapYear = true; 89 | } 90 | } 91 | } 92 | return leapYear; // replace this line with your solution 93 | } 94 | 95 | /** 96 | * Returns the number of days in a given month. 97 | * 98 | * @param month is a month, numbered in the range 1...12. 99 | * @param year is the year in question, with no digits omitted. 100 | * @return the number of days in the given month. 101 | */ 102 | public static int daysInMonth(int month, int year) { 103 | switch (month) { 104 | case 1: 105 | case 3: 106 | case 5: 107 | case 7: 108 | case 8: 109 | case 10: 110 | case 12: 111 | return 31; 112 | case 4: 113 | case 6: 114 | case 9: 115 | case 11: 116 | return 30; 117 | } 118 | 119 | if (isLeapYear(year)) { 120 | return 29; 121 | } else { 122 | return 28; 123 | } 124 | // replace this line with your solution 125 | } 126 | 127 | /** 128 | * Checks whether the given date is valid. 129 | * 130 | * @return true if and only if month/day/year constitute a valid date. 131 | *

132 | * Years prior to A.D. 1 are NOT valid. 133 | */ 134 | public static boolean isValidDate(int month, int day, int year) { 135 | if (year < 1) { 136 | System.out.println(year); 137 | System.out.println("year < 1"); 138 | return false; 139 | } 140 | 141 | if (month > 12 || month < 0) { 142 | System.out.println(month); 143 | System.out.println("month > 12 || month < 0"); 144 | return false; 145 | } 146 | 147 | if (day < 0 || day > daysInMonth(month, year)) { 148 | System.out.println(day); 149 | System.out.println("day < 0 || day > " + daysInMonth(month, year)); 150 | return false; 151 | } 152 | 153 | return true; 154 | } 155 | 156 | /** 157 | * Returns a string representation of this date in the form month/day/year. 158 | * The month, day, and year are expressed in full as integers; for example, 159 | * 12/7/2006 or 3/21/407. 160 | * 161 | * @return a String representation of this date. 162 | */ 163 | public String toString() { 164 | String dateString; 165 | dateString = Integer.toString(month) + "/" + Integer.toString(day) + "/" + Integer.toString(year); 166 | return dateString; // replace this line with your solution 167 | } 168 | 169 | /** 170 | * Determines whether this Date is before the Date d. 171 | * 172 | * @return true if and only if this Date is before d. 173 | */ 174 | public boolean isBefore(Date d) { 175 | return days < d.days; 176 | } 177 | 178 | /** 179 | * Determines whether this Date is after the Date d. 180 | * 181 | * @return true if and only if this Date is after d. 182 | */ 183 | public boolean isAfter(Date d) { 184 | return days > d.days; 185 | } 186 | 187 | /** 188 | * Returns the number of this Date in the year. 189 | * 190 | * @return a number n in the range 1...366, inclusive, such that this Date 191 | * is the nth day of its year. (366 is used only for December 31 in a leap 192 | * year.) 193 | */ 194 | public int dayInYear() { 195 | int days; 196 | days = 7 * 31 + 4 * 30 + 28; 197 | if (isLeapYear(year)) { 198 | days++; 199 | } 200 | return days; // replace this line with your solution 201 | } 202 | 203 | private int dayInYear(int year) { 204 | int days; 205 | days = 7 * 31 + 4 * 30 + 28; 206 | if (isLeapYear(year)) { 207 | days++; 208 | } 209 | return days; // replace this line with your solution 210 | } 211 | 212 | /** 213 | * Determines the difference in days between d and this Date. For example, 214 | * if this Date is 12/15/2012 and d is 12/14/2012, the difference is 1. 215 | * If this Date occurs before d, the result is negative. 216 | * 217 | * @return the difference in days between d and this date. 218 | */ 219 | public int difference(Date d) { 220 | return days - d.days; 221 | } 222 | 223 | public static void main(String[] argv) { 224 | System.out.println("\nTesting constructors."); 225 | Date d1 = new Date(1, 1, 1); 226 | System.out.println("Date should be 1/1/1: " + d1); 227 | d1 = new Date("2/4/2"); 228 | System.out.println("Date should be 2/4/2: " + d1); 229 | d1 = new Date("2/29/2000"); 230 | System.out.println("Date should be 2/29/2000: " + d1); 231 | d1 = new Date("2/29/1904"); 232 | System.out.println("Date should be 2/29/1904: " + d1); 233 | 234 | d1 = new Date(12, 31, 1975); 235 | System.out.println("Date should be 12/31/1975: " + d1); 236 | Date d2 = new Date("1/1/1976"); 237 | System.out.println("Date should be 1/1/1976: " + d2); 238 | Date d3 = new Date("1/2/1976"); 239 | System.out.println("Date should be 1/2/1976: " + d3); 240 | 241 | Date d4 = new Date("2/27/1977"); 242 | Date d5 = new Date("8/31/2110"); 243 | 244 | /* I recommend you write code to test the isLeapYear function! */ 245 | 246 | System.out.println("\nTesting before and after."); 247 | System.out.println(d2 + " after " + d1 + " should be true: " + 248 | d2.isAfter(d1)); 249 | System.out.println(d3 + " after " + d2 + " should be true: " + 250 | d3.isAfter(d2)); 251 | System.out.println(d1 + " after " + d1 + " should be false: " + 252 | d1.isAfter(d1)); 253 | System.out.println(d1 + " after " + d2 + " should be false: " + 254 | d1.isAfter(d2)); 255 | System.out.println(d2 + " after " + d3 + " should be false: " + 256 | d2.isAfter(d3)); 257 | 258 | System.out.println(d1 + " before " + d2 + " should be true: " + 259 | d1.isBefore(d2)); 260 | System.out.println(d2 + " before " + d3 + " should be true: " + 261 | d2.isBefore(d3)); 262 | System.out.println(d1 + " before " + d1 + " should be false: " + 263 | d1.isBefore(d1)); 264 | System.out.println(d2 + " before " + d1 + " should be false: " + 265 | d2.isBefore(d1)); 266 | System.out.println(d3 + " before " + d2 + " should be false: " + 267 | d3.isBefore(d2)); 268 | 269 | System.out.println("\nTesting difference."); 270 | System.out.println(d1 + " - " + d1 + " should be 0: " + 271 | d1.difference(d1)); 272 | System.out.println(d2 + " - " + d1 + " should be 1: " + 273 | d2.difference(d1)); 274 | System.out.println(d3 + " - " + d1 + " should be 2: " + 275 | d3.difference(d1)); 276 | System.out.println(d3 + " - " + d4 + " should be -422: " + 277 | d3.difference(d4)); 278 | System.out.println(d5 + " - " + d4 + " should be 48762: " + 279 | d5.difference(d4)); 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /hw3/SList.java: -------------------------------------------------------------------------------- 1 | /* SList.java */ 2 | package hw3; 3 | 4 | /** 5 | * The SList class is a singly-linked implementation of the linked list 6 | * abstraction. SLists are mutable data structures, which can grow at either 7 | * end. 8 | * 9 | * @author Kathy Yelick and Jonathan Shewchuk 10 | */ 11 | 12 | public class SList { 13 | 14 | private SListNode head; 15 | private int size; 16 | 17 | /** 18 | * SList() constructs an empty list. 19 | */ 20 | 21 | public SList() { 22 | size = 0; 23 | head = null; 24 | } 25 | 26 | /** 27 | * isEmpty() indicates whether the list is empty. 28 | * 29 | * @return true if the list is empty, false otherwise. 30 | */ 31 | 32 | public boolean isEmpty() { 33 | return size == 0; 34 | } 35 | 36 | /** 37 | * length() returns the length of this list. 38 | * 39 | * @return the length of this list. 40 | */ 41 | 42 | public int length() { 43 | return size; 44 | } 45 | 46 | /** 47 | * insertFront() inserts item "obj" at the beginning of this list. 48 | * 49 | * @param obj the item to be inserted. 50 | */ 51 | 52 | public void insertFront(Object obj) { 53 | head = new SListNode(obj, head); 54 | size++; 55 | } 56 | 57 | /** 58 | * insertEnd() inserts item "obj" at the end of this list. 59 | * 60 | * @param obj the item to be inserted. 61 | */ 62 | 63 | public void insertEnd(Object obj) { 64 | if (head == null) { 65 | head = new SListNode(obj); 66 | } else { 67 | SListNode node = head; 68 | while (node.next != null) { 69 | node = node.next; 70 | } 71 | node.next = new SListNode(obj); 72 | } 73 | size++; 74 | } 75 | 76 | /** 77 | * nth() returns the item at the specified position. If position < 1 or 78 | * position > this.length(), null is returned. Otherwise, the item at 79 | * position "position" is returned. The list does not change. 80 | * 81 | * @param position the desired position, from 1 to length(), in the list. 82 | * @return the item at the given position in the list. 83 | */ 84 | 85 | public Object nth(int position) { 86 | SListNode currentNode; 87 | 88 | if ((position < 1) || (head == null)) { 89 | System.out.println("Out of Index"); 90 | return null; 91 | } else { 92 | currentNode = head; 93 | while (position > 1) { 94 | currentNode = currentNode.next; 95 | if (currentNode == null) { 96 | System.out.println("Out of Index"); 97 | return null; 98 | } 99 | position--; 100 | } 101 | return currentNode.item; 102 | } 103 | } 104 | 105 | /** 106 | * squish() takes this list and, wherever two or more consecutive items are 107 | * equals(), it removes duplicate nodes so that only one consecutive copy 108 | * remains. Hence, no two consecutive items in this list are equals() upon 109 | * completion of the procedure. 110 | *

111 | * After squish() executes, the list may well be shorter than when squish() 112 | * began. No extra items are added to make up for those removed. 113 | *

114 | * For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the 115 | * output list is [ 0 1 0 3 1 0 ]. 116 | *

117 | * IMPORTANT: Be sure you use the equals() method, and not the "==" 118 | * operator, to compare items. 119 | */ 120 | 121 | public void squish() { 122 | if (isEmpty()) { 123 | return; 124 | } 125 | SListNode currentNode = head; 126 | for (int i = 1; i <= length(); i++) { 127 | if (!currentNode.item.equals(nth(i))) { 128 | currentNode.next.item = nth(i); 129 | currentNode = currentNode.next; 130 | } 131 | } 132 | currentNode.next = null; 133 | // Fill in your solution here. (Ours is eleven lines long.) 134 | } 135 | 136 | /** 137 | * twin() takes this list and doubles its length by replacing each node 138 | * with two consecutive nodes referencing the same item. 139 | *

140 | * For example, if the input list is [ 3 7 4 2 2 ], the 141 | * output list is [ 3 3 7 7 4 4 2 2 2 2 ]. 142 | *

143 | * IMPORTANT: Do not try to make new copies of the items themselves. 144 | * Make new SListNodes, but just copy the references to the items. 145 | */ 146 | 147 | public void twin() { 148 | SListNode currentNode = head; 149 | while (currentNode != null) { 150 | System.out.println("here"); 151 | SListNode newNode = new SListNode(currentNode.item, currentNode.next); 152 | currentNode.next = newNode; 153 | currentNode = newNode.next; 154 | } 155 | // Fill in your solution here. (Ours is seven lines long.) 156 | } 157 | 158 | /** 159 | * toString() converts the list to a String. 160 | * 161 | * @return a String representation of the list. 162 | */ 163 | 164 | public String toString() { 165 | int i; 166 | Object obj; 167 | String result = "[ "; 168 | 169 | SListNode cur = head; 170 | 171 | while (cur != null) { 172 | obj = cur.item; 173 | result = result + obj.toString() + " "; 174 | cur = cur.next; 175 | } 176 | result = result + "]"; 177 | return result; 178 | } 179 | 180 | 181 | /** 182 | * main() runs test cases on the SList class. Prints summary 183 | * information on basic operations and halts with an error (and a stack 184 | * trace) if any of the tests fail. 185 | */ 186 | 187 | public static void main(String[] args) { 188 | testEmpty(); 189 | testAfterInsertFront(); 190 | testAfterInsertEnd(); 191 | } 192 | 193 | 194 | /** 195 | * testEmpty() tests toString(), isEmpty(), length(), insertFront(), and 196 | * insertEnd() on an empty list. Prints summary information of the tests 197 | * and halts the program if errors are detected. 198 | */ 199 | 200 | private static void testEmpty() { 201 | SList lst1 = new SList(); 202 | SList lst2 = new SList(); 203 | System.out.println(); 204 | System.out.println("Here is a list after construction: " 205 | + lst1.toString()); 206 | TestHelper.verify(lst1.toString().equals("[ ]"), 207 | "toString on newly constructed list failed"); 208 | 209 | System.out.println("isEmpty() should be true. It is: " + 210 | lst1.isEmpty()); 211 | TestHelper.verify(lst1.isEmpty() == true, 212 | "isEmpty() on newly constructed list failed"); 213 | 214 | System.out.println("length() should be 0. It is: " + 215 | lst1.length()); 216 | TestHelper.verify(lst1.length() == 0, 217 | "length on newly constructed list failed"); 218 | lst1.insertFront(new Integer(3)); 219 | System.out.println("Here is a list after insertFront(3) to an empty list: " 220 | + lst1.toString()); 221 | TestHelper.verify(lst1.toString().equals("[ 3 ]"), 222 | "InsertFront on empty list failed"); 223 | lst2.insertEnd(new Integer(5)); 224 | System.out.println("Here is a list after insertEnd(5) on an empty list: " 225 | + lst2.toString()); 226 | TestHelper.verify(lst2.toString().equals("[ 5 ]"), 227 | "insertEnd on empty list failed"); 228 | } 229 | 230 | /** 231 | * testAfterInsertFront() tests toString(), isEmpty(), length(), 232 | * insertFront(), and insertEnd() after insertFront(). Prints summary 233 | * information of the tests and halts the program if errors are detected. 234 | */ 235 | 236 | private static void testAfterInsertFront() { 237 | SList lst1 = new SList(); 238 | lst1.insertFront(new Integer(3)); 239 | lst1.insertFront(new Integer(2)); 240 | lst1.insertFront(new Integer(1)); 241 | System.out.println(); 242 | System.out.println("Here is a list after insertFront 3, 2, 1: " 243 | + lst1.toString()); 244 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 ]"), 245 | "InsertFronts on non-empty list failed"); 246 | System.out.println("isEmpty() should be false. It is: " + 247 | lst1.isEmpty()); 248 | TestHelper.verify(lst1.isEmpty() == false, 249 | "isEmpty() after insertFront failed"); 250 | System.out.println("length() should be 3. It is: " + 251 | lst1.length()); 252 | TestHelper.verify(lst1.length() == 3, 253 | "length() after insertFront failed"); 254 | lst1.insertEnd(new Integer(4)); 255 | System.out.println("Here is the same list after insertEnd(4): " 256 | + lst1.toString()); 257 | TestHelper.verify(lst1.toString().equals("[ 1 2 3 4 ]"), 258 | "insertEnd on non-empty list failed"); 259 | } 260 | 261 | /** 262 | * testAfterInsertEnd() tests toString(), isEmpty(), length(), 263 | * insertFront(), and insertEnd() after insertEnd(). Prints summary 264 | * information of the tests and halts the program if errors are detected. 265 | */ 266 | 267 | private static void testAfterInsertEnd() { 268 | SList lst1 = new SList(); 269 | lst1.insertEnd(new Integer(6)); 270 | lst1.insertEnd(new Integer(7)); 271 | System.out.println(); 272 | System.out.println("Here is a list after insertEnd 6, 7: " 273 | + lst1.toString()); 274 | System.out.println("isEmpty() should be false. It is: " + 275 | lst1.isEmpty()); 276 | TestHelper.verify(lst1.isEmpty() == false, 277 | "isEmpty() after insertEnd failed"); 278 | System.out.println("length() should be 2. It is: " + 279 | lst1.length()); 280 | TestHelper.verify(lst1.length() == 2, 281 | "length() after insertEndfailed"); 282 | lst1.insertFront(new Integer(5)); 283 | System.out.println("Here is the same list after insertFront(5): " 284 | + lst1.toString()); 285 | TestHelper.verify(lst1.toString().equals("[ 5 6 7 ]"), 286 | "insertFront after insertEnd failed"); 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /hw5/list/DList.java: -------------------------------------------------------------------------------- 1 | /* DList.java */ 2 | 3 | package hw5.list; 4 | 5 | /** 6 | * A DList is a mutable doubly-linked list ADT. Its implementation is 7 | * circularly-linked and employs a sentinel node at the head of the list. 8 | *

9 | * DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE. 10 | */ 11 | 12 | public class DList extends List { 13 | 14 | /** 15 | * (inherited) size is the number of items in the list. 16 | * head references the sentinel node. 17 | * Note that the sentinel node does not store an item, and is not included 18 | * in the count stored by the "size" field. 19 | *

20 | * DO NOT CHANGE THE FOLLOWING FIELD DECLARATION. 21 | */ 22 | 23 | protected DListNode head; 24 | 25 | /* DList invariants: 26 | * 1) head != null. 27 | * 2) For every DListNode x in a DList, x.next != null. 28 | * 3) For every DListNode x in a DList, x.prev != null. 29 | * 4) For every DListNode x in a DList, if x.next == y, then y.prev == x. 30 | * 5) For every DListNode x in a DList, if x.prev == y, then y.next == x. 31 | * 6) For every DList l, l.head.myList = null. (Note that l.head is the 32 | * sentinel.) 33 | * 7) For every DListNode x in a DList l EXCEPT l.head (the sentinel), 34 | * x.myList = l. 35 | * 8) size is the number of DListNodes, NOT COUNTING the sentinel, 36 | * that can be accessed from the sentinel (head) by a sequence of 37 | * "next" references. 38 | **/ 39 | 40 | /** 41 | * newNode() calls the DListNode constructor. Use this method to allocate 42 | * new DListNodes rather than calling the DListNode constructor directly. 43 | * That way, only this method need be overridden if a subclass of DList 44 | * wants to use a different kind of node. 45 | * 46 | * @param item the item to store in the node. 47 | * @param list the list that owns this node. (null for sentinels.) 48 | * @param prev the node previous to this node. 49 | * @param next the node following this node. 50 | */ 51 | protected DListNode newNode(Object item, DList list, 52 | DListNode prev, DListNode next) { 53 | return new DListNode(item, list, prev, next); 54 | } 55 | 56 | /** 57 | * DList() constructs for an empty DList. 58 | */ 59 | public DList() { 60 | head = newNode(null, null, null, null); 61 | head.next = head; 62 | head.prev = head; 63 | // Your solution here. Similar to Homework 4, but now you need to specify 64 | // the `list' field (second parameter) as well. 65 | } 66 | 67 | /** 68 | * insertFront() inserts an item at the front of this DList. 69 | * 70 | * @param item is the item to be inserted. 71 | *

72 | * Performance: runs in O(1) time. 73 | */ 74 | public void insertFront(Object item) { 75 | DListNode newNode = newNode(item, this, head, head.next); 76 | head.next = newNode; 77 | newNode.next.prev = newNode; 78 | size++; 79 | // Your solution here. Similar to Homework 4, but now you need to specify 80 | // the `list' field (second parameter) as well. 81 | } 82 | 83 | /** 84 | * insertBack() inserts an item at the back of this DList. 85 | * 86 | * @param item is the item to be inserted. 87 | *

88 | * Performance: runs in O(1) time. 89 | */ 90 | public void insertBack(Object item) { 91 | DListNode newNode = newNode(item, this, head.prev, head); 92 | head.prev = newNode; 93 | newNode.next.prev = newNode; 94 | // Your solution here. Similar to Homework 4, but now you need to specify 95 | // the `list' field (second parameter) as well. 96 | } 97 | 98 | /** 99 | * front() returns the node at the front of this DList. If the DList is 100 | * empty, return an "invalid" node--a node with the property that any 101 | * attempt to use it will cause an exception. (The sentinel is "invalid".) 102 | *

103 | * DO NOT CHANGE THIS METHOD. 104 | * 105 | * @return a ListNode at the front of this DList. 106 | *

107 | * Performance: runs in O(1) time. 108 | */ 109 | public ListNode front() { 110 | return head.next; 111 | } 112 | 113 | /** 114 | * back() returns the node at the back of this DList. If the DList is 115 | * empty, return an "invalid" node--a node with the property that any 116 | * attempt to use it will cause an exception. (The sentinel is "invalid".) 117 | *

118 | * DO NOT CHANGE THIS METHOD. 119 | * 120 | * @return a ListNode at the back of this DList. 121 | *

122 | * Performance: runs in O(1) time. 123 | */ 124 | public ListNode back() { 125 | return head.prev; 126 | } 127 | 128 | /** 129 | * toString() returns a String representation of this DList. 130 | *

131 | * DO NOT CHANGE THIS METHOD. 132 | * 133 | * @return a String representation of this DList. 134 | *

135 | * Performance: runs in O(n) time, where n is the length of the list. 136 | */ 137 | public String toString() { 138 | String result = "[ "; 139 | DListNode current = head.next; 140 | while (current != head) { 141 | result = result + current.item + " "; 142 | current = current.next; 143 | } 144 | return result + "]"; 145 | } 146 | 147 | private static void testInvalidNode(ListNode p) { 148 | System.out.println("p.isValidNode() should be false: " + p.isValidNode()); 149 | try { 150 | p.item(); 151 | System.out.println("p.item() should throw an exception, but didn't."); 152 | } catch (InvalidNodeException lbe) { 153 | System.out.println("p.item() should throw an exception, and did."); 154 | } 155 | try { 156 | p.setItem(new Integer(0)); 157 | System.out.println("p.setItem() should throw an exception, but didn't."); 158 | } catch (InvalidNodeException lbe) { 159 | System.out.println("p.setItem() should throw an exception, and did."); 160 | } 161 | try { 162 | p.next(); 163 | System.out.println("p.next() should throw an exception, but didn't."); 164 | } catch (InvalidNodeException lbe) { 165 | System.out.println("p.next() should throw an exception, and did."); 166 | } 167 | try { 168 | p.prev(); 169 | System.out.println("p.prev() should throw an exception, but didn't."); 170 | } catch (InvalidNodeException lbe) { 171 | System.out.println("p.prev() should throw an exception, and did."); 172 | } 173 | try { 174 | p.insertBefore(new Integer(1)); 175 | System.out.println("p.insertBefore() should throw an exception, but " + 176 | "didn't."); 177 | } catch (InvalidNodeException lbe) { 178 | System.out.println("p.insertBefore() should throw an exception, and did." 179 | ); 180 | } 181 | try { 182 | p.insertAfter(new Integer(1)); 183 | System.out.println("p.insertAfter() should throw an exception, but " + 184 | "didn't."); 185 | } catch (InvalidNodeException lbe) { 186 | System.out.println("p.insertAfter() should throw an exception, and did." 187 | ); 188 | } 189 | try { 190 | p.remove(); 191 | System.out.println("p.remove() should throw an exception, but didn't."); 192 | } catch (InvalidNodeException lbe) { 193 | System.out.println("p.remove() should throw an exception, and did."); 194 | } 195 | } 196 | 197 | private static void testEmpty() { 198 | List l = new DList(); 199 | System.out.println("An empty list should be [ ]: " + l); 200 | System.out.println("l.isEmpty() should be true: " + l.isEmpty()); 201 | System.out.println("l.length() should be 0: " + l.length()); 202 | System.out.println("Finding front node p of l."); 203 | ListNode p = l.front(); 204 | testInvalidNode(p); 205 | System.out.println("Finding back node p of l."); 206 | p = l.back(); 207 | testInvalidNode(p); 208 | l.insertFront(new Integer(10)); 209 | System.out.println("l after insertFront(10) should be [ 10 ]: " + l); 210 | } 211 | 212 | public static void main(String[] argv) { 213 | testEmpty(); 214 | List l = new DList(); 215 | l.insertFront(new Integer(3)); 216 | l.insertFront(new Integer(2)); 217 | l.insertFront(new Integer(1)); 218 | System.out.println("l is a list of 3 elements: " + l); 219 | try { 220 | ListNode n; 221 | int i = 1; 222 | for (n = l.front(); n.isValidNode(); n = n.next()) { 223 | System.out.println("n.item() should be " + i + ": " + n.item()); 224 | n.setItem(new Integer(((Integer) n.item()).intValue() * 2)); 225 | System.out.println("n.item() should be " + 2 * i + ": " + n.item()); 226 | i++; 227 | } 228 | System.out.println("After doubling all elements of l: " + l); 229 | testInvalidNode(n); 230 | 231 | i = 6; 232 | for (n = l.back(); n.isValidNode(); n = n.prev()) { 233 | System.out.println("n.item() should be " + i + ": " + n.item()); 234 | n.setItem(new Integer(((Integer) n.item()).intValue() * 2)); 235 | System.out.println("n.item() should be " + 2 * i + ": " + n.item()); 236 | i = i - 2; 237 | } 238 | System.out.println("After doubling all elements of l again: " + l); 239 | testInvalidNode(n); 240 | 241 | n = l.front().next(); 242 | System.out.println("Removing middle element (8) of l: " + n.item()); 243 | n.remove(); 244 | System.out.println("l is now: " + l); 245 | testInvalidNode(n); 246 | n = l.back(); 247 | System.out.println("Removing end element (12) of l: " + n.item()); 248 | n.remove(); 249 | System.out.println("l is now: " + l); 250 | testInvalidNode(n); 251 | 252 | n = l.front(); 253 | System.out.println("Removing first element (4) of l: " + n.item()); 254 | n.remove(); 255 | System.out.println("l is now: " + l); 256 | testInvalidNode(n); 257 | } catch (InvalidNodeException lbe) { 258 | System.err.println("Caught InvalidNodeException that should not happen." 259 | ); 260 | System.err.println("Aborting the testing code."); 261 | } 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /hw7/dict/Tree234.java: -------------------------------------------------------------------------------- 1 | /* Tree234.java */ 2 | 3 | package hw7.dict; 4 | 5 | /** 6 | * A Tree234 implements an ordered integer dictionary ADT using a 2-3-4 tree. 7 | * Only int keys are stored; no object is associated with each key. Duplicate 8 | * keys are not stored in the tree. 9 | * 10 | * @author Jonathan Shewchuk 11 | */ 12 | public class Tree234 extends IntDictionary { 13 | 14 | /** 15 | * You may add fields if you wish, but don't change anything that 16 | * would prevent toString() or find() from working correctly. 17 | *

18 | * (inherited) size is the number of keys in the dictionary. 19 | * root is the root of the 2-3-4 tree. 20 | */ 21 | Tree234Node root; 22 | 23 | /** 24 | * Tree234() constructs an empty 2-3-4 tree. 25 | *

26 | * You may change this constructor, but you may not change the fact that 27 | * an empty Tree234 contains no nodes. 28 | */ 29 | public Tree234() { 30 | root = null; 31 | size = 0; 32 | } 33 | 34 | /** 35 | * toString() prints this Tree234 as a String. Each node is printed 36 | * in the form such as (for a 3-key node) 37 | *

38 | * (child1)key1(child2)key2(child3)key3(child4) 39 | *

40 | * where each child is a recursive call to toString, and null children 41 | * are printed as a space with no parentheses. Here's an example. 42 | * ((1)7(11 16)22(23)28(37 49))50((60)84(86 95 100)) 43 | *

44 | * DO NOT CHANGE THIS METHOD. The test code depends on it. 45 | * 46 | * @return a String representation of the 2-3-4 tree. 47 | */ 48 | public String toString() { 49 | if (root == null) { 50 | return ""; 51 | } else { 52 | /* Most of the work is done by Tree234Node.toString(). */ 53 | return root.toString(); 54 | } 55 | } 56 | 57 | /** 58 | * printTree() prints this Tree234 as a tree, albeit sideways. 59 | *

60 | * You're welcome to change this method if you like. It won't be tested. 61 | */ 62 | public void printTree() { 63 | if (root != null) { 64 | /* Most of the work is done by Tree234Node.printSubtree(). */ 65 | root.printSubtree(0); 66 | } 67 | } 68 | 69 | /** 70 | * find() prints true if "key" is in this 2-3-4 tree; false otherwise. 71 | * 72 | * @param key is the key sought. 73 | * @return true if "key" is in the tree; false otherwise. 74 | */ 75 | // TODO code cleanup 76 | public boolean find(int key) { 77 | Tree234Node node = root; 78 | while (node != null) { 79 | if (key < node.key1) { 80 | node = node.child1; 81 | } else if (key == node.key1) { 82 | return true; 83 | } else if ((node.keys == 1) || (key < node.key2)) { 84 | node = node.child2; 85 | } else if (key == node.key2) { 86 | return true; 87 | } else if ((node.keys == 2) || (key < node.key3)) { 88 | node = node.child3; 89 | } else if (key == node.key3) { 90 | return true; 91 | } else { 92 | node = node.child4; 93 | } 94 | } 95 | return false; 96 | } 97 | 98 | /** 99 | * insert() inserts the key "key" into this 2-3-4 tree. If "key" is 100 | * already present, a duplicate copy is NOT inserted. 101 | * 102 | * @param key is the key sought. 103 | */ 104 | public void insert(int key) { 105 | if (root == null) { 106 | root = new Tree234Node(null, key); 107 | return; 108 | } 109 | Tree234Node node = root; 110 | if (node.keys == 3) { 111 | if (key <= node.key1) { 112 | rearrangeNode(node); 113 | } else if (key <= node.key2) { 114 | rearrangeNode(node); 115 | } else { 116 | node = rearrangeNode(node); 117 | } 118 | } 119 | while (node.child1 != null) { 120 | if (node.keys == 3) { 121 | if (key <= node.key1) { 122 | rearrangeNode(node); 123 | } else if (key <= node.key2) { 124 | rearrangeNode(node); 125 | } else { 126 | node = rearrangeNode(node); 127 | } 128 | } 129 | if (key <= node.key1) { 130 | node = node.child1; 131 | } else if ((node.keys == 1) || (key <= node.key2)) { 132 | node = node.child2; 133 | } else if ((node.keys == 2) || (key <= node.key3)) { 134 | node = node.child3; 135 | } else { 136 | node = node.child4; 137 | } 138 | } 139 | 140 | if (node.keys == 3) { 141 | if (key <= node.key2) { 142 | rearrangeNode(node); 143 | } else { 144 | node = rearrangeNode(node); 145 | } 146 | } 147 | node.insertKey(key); 148 | size++; 149 | // Fill in your solution here. 150 | } 151 | 152 | private Tree234Node rearrangeNode(Tree234Node node) { 153 | if (node.parent == null) { 154 | Tree234Node newRoot = new Tree234Node(null, node.key2); 155 | newRoot.child1 = node; 156 | node.parent = newRoot; 157 | newRoot.child2 = deleteNSplitNode(node); 158 | root = newRoot; 159 | return newRoot.child2; 160 | } else { 161 | node.parent.insertKey(node.key2); 162 | if (node.parent.child1 == node) { 163 | node.parent.child4 = node.parent.child3; 164 | node.parent.child3 = node.parent.child2; 165 | node.parent.child2 = deleteNSplitNode(node); 166 | return node.parent.child2; 167 | } else if (node.parent.child2 == node) { 168 | node.parent.child4 = node.parent.child3; 169 | node.parent.child3 = deleteNSplitNode(node); 170 | return node.parent.child3; 171 | } else if (node.parent.child3 == node) { 172 | node.parent.child4 = deleteNSplitNode(node); 173 | return node.parent.child4; 174 | } else { 175 | System.out.println("Error, Node is not child"); 176 | return new Tree234Node(null, 0); 177 | } 178 | } 179 | } 180 | 181 | private Tree234Node deleteNSplitNode(Tree234Node node) { 182 | Tree234Node newNode = new Tree234Node(node.parent, node.key3); 183 | node.keys = 1; 184 | if (node.child1 != null) { 185 | newNode.child1 = node.child3; 186 | newNode.child2 = node.child4; 187 | newNode.child1.parent = newNode.child2.parent = newNode; 188 | node.child3 = node.child4 = null; 189 | } 190 | return newNode; 191 | } 192 | 193 | 194 | /** 195 | * testHelper() prints the String representation of this tree, then 196 | * compares it with the expected String, and prints an error message if 197 | * the two are not equal. 198 | * 199 | * @param correctString is what the tree should look like. 200 | */ 201 | public void testHelper(String correctString) { 202 | String treeString = toString(); 203 | System.out.println(treeString); 204 | if (!treeString.equals(correctString)) { 205 | System.out.println("ERROR: Should be " + correctString); 206 | } 207 | } 208 | 209 | /** 210 | * main() is a bunch of test code. Feel free to add test code of your own; 211 | * this code won't be tested or graded. 212 | */ 213 | public static void main(String[] args) { 214 | Tree234 t = new Tree234(); 215 | 216 | System.out.println("\nInserting 84."); 217 | t.insert(84); 218 | t.testHelper("84"); 219 | 220 | System.out.println("\nInserting 7."); 221 | t.insert(7); 222 | t.testHelper("7 84"); 223 | 224 | System.out.println("\nInserting 22."); 225 | t.insert(22); 226 | t.testHelper("7 22 84"); 227 | 228 | System.out.println("\nInserting 95."); 229 | t.insert(95); 230 | t.testHelper("(7)22(84 95)"); 231 | 232 | System.out.println("\nInserting 50."); 233 | t.insert(50); 234 | t.testHelper("(7)22(50 84 95)"); 235 | 236 | System.out.println("\nInserting 11."); 237 | t.insert(11); 238 | t.testHelper("(7 11)22(50 84 95)"); 239 | 240 | System.out.println("\nInserting 37."); 241 | t.insert(37); 242 | t.testHelper("(7 11)22(37 50)84(95)"); 243 | 244 | System.out.println("\nInserting 60."); 245 | t.insert(60); 246 | t.testHelper("(7 11)22(37 50 60)84(95)"); 247 | 248 | System.out.println("\nInserting 1."); 249 | t.insert(1); 250 | t.testHelper("(1 7 11)22(37 50 60)84(95)"); 251 | 252 | System.out.println("\nInserting 23."); 253 | t.insert(23); 254 | t.testHelper("(1 7 11)22(23 37)50(60)84(95)"); 255 | 256 | System.out.println("\nInserting 16."); 257 | t.insert(16); 258 | t.testHelper("((1)7(11 16)22(23 37))50((60)84(95))"); 259 | 260 | System.out.println("\nInserting 100."); 261 | t.insert(100); 262 | t.testHelper("((1)7(11 16)22(23 37))50((60)84(95 100))"); 263 | 264 | System.out.println("\nInserting 28."); 265 | t.insert(28); 266 | t.testHelper("((1)7(11 16)22(23 28 37))50((60)84(95 100))"); 267 | 268 | System.out.println("\nInserting 86."); 269 | t.insert(86); 270 | t.testHelper("((1)7(11 16)22(23 28 37))50((60)84(86 95 100))"); 271 | 272 | System.out.println("\nInserting 49."); 273 | t.insert(49); 274 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((60)84(86 95 100))"); 275 | 276 | System.out.println("\nInserting 81."); 277 | t.insert(81); 278 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((60 81)84(86 95 100))"); 279 | 280 | System.out.println("\nInserting 51."); 281 | t.insert(51); 282 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((51 60 81)84(86 95 100))"); 283 | 284 | System.out.println("\nInserting 99."); 285 | t.insert(99); 286 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((51 60 81)84(86)95(99 100))"); 287 | 288 | System.out.println("\nInserting 75."); 289 | t.insert(75); 290 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((51)60(75 81)84(86)95" + 291 | "(99 100))"); 292 | 293 | System.out.println("\nInserting 66."); 294 | t.insert(66); 295 | t.testHelper("((1)7(11 16)22(23)28(37 49))50((51)60(66 75 81))84((86)95" + 296 | "(99 100))"); 297 | 298 | System.out.println("\nInserting 4."); 299 | t.insert(4); 300 | t.testHelper("((1 4)7(11 16))22((23)28(37 49))50((51)60(66 75 81))84" + 301 | "((86)95(99 100))"); 302 | 303 | System.out.println("\nInserting 80."); 304 | t.insert(80); 305 | t.testHelper("(((1 4)7(11 16))22((23)28(37 49)))50(((51)60(66)75" + 306 | "(80 81))84((86)95(99 100)))"); 307 | 308 | System.out.println("\nFinal tree:"); 309 | t.printTree(); 310 | } 311 | 312 | } 313 | --------------------------------------------------------------------------------