├── ANSVP ├── README.txt └── src │ ├── EmptyStackException.java │ ├── Node.java │ ├── NodeStack.java │ ├── Stack.java │ └── StackANSVP.java ├── EquationSolver ├── README.md └── src │ ├── ArrayIndexList.java │ ├── ArrayListCompleteBinaryTree.java │ ├── BoundaryViolationException.java │ ├── DefaultComparator.java │ ├── EmptyPriorityQueueException.java │ ├── EmptyTreeException.java │ ├── Entry.java │ ├── EquationSolver.java │ ├── HeapPriorityQueue.java │ ├── HeapSort.java │ ├── InvalidPositionException.java │ ├── MyEntry.java │ ├── Position.java │ └── PriorityQueue.java ├── MazeConstruct ├── README.txt ├── constructinput.txt ├── constructoutput.txt └── src │ ├── ArrayIndexList.java │ ├── ArrayListCompleteBinaryTree.java │ ├── BoundaryViolationException.java │ ├── Cell.java │ ├── DefaultComparator.java │ ├── Edge.java │ ├── EdgeListGraph.java │ ├── EmptyPriorityQueueException.java │ ├── EmptyTreeException.java │ ├── Entry.java │ ├── HeapAdaptablePriorityQueue.java │ ├── HeapPriorityQueue.java │ ├── InvalidEntryException.java │ ├── InvalidPositionException.java │ ├── MazeConstruct.java │ ├── MyEntry.java │ ├── Position.java │ ├── PrimJarnikMST.java │ ├── PriorityQueue.java │ └── Vertex.java ├── PuzzleSolve ├── README.txt └── src │ ├── Node.java │ ├── PuzzleSolve.java │ └── SLinkedList.java └── StockTran ├── README.txt └── src ├── CircleQueue.java ├── EmptyQueueException.java ├── FullQueueException.java ├── Node.java └── StockTran.java /ANSVP/README.txt: -------------------------------------------------------------------------------- 1 | ANSVP 2 | By Steven Gerhard 3 | 4 | compile src and run StackANSVP.class 5 | 6 | The All Nearest Smaller Values Problem, ANSVP, is defined as follows: For each number in a sequence, search among the previous positions for the last number that is smaller. 7 | 8 | For a given input sequence, the previous nearest smaller values are returned as an array. Using Stacks this is solved in O(N) time. 9 | 10 | The input must be a series of numbers separated by spaces or commas. 11 | 12 | An Example: 13 | Input 14 | 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 15 | Output 16 | [-, 0, 0, 4, 0, 2, 2, 6, 0, 1, 1, 5, 1, 3, 3, 7] 17 | 18 | 19 | -------------------------------------------------------------------------------- /ANSVP/src/EmptyStackException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Runtime exception thrown when one tries to perform 3 | * operation top or pop on an empty stack. 4 | */ 5 | public class EmptyStackException extends RuntimeException { 6 | public EmptyStackException(String err){ 7 | super(err); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /ANSVP/src/Node.java: -------------------------------------------------------------------------------- 1 | 2 | public class Node { 3 | private E element; 4 | private Node next; 5 | // Creates a node with null references to its element and next node. 6 | public Node(){ 7 | this(null,null); 8 | } 9 | //Creates a node with the given element and next node. 10 | public Node(E e, Node n){ 11 | element = e; 12 | next = n; 13 | } 14 | // Accessor methods 15 | public E getElement(){ 16 | return element; 17 | } 18 | public Node getNext(){ 19 | return next; 20 | } 21 | // Modifier methods 22 | public void setElement(E newElem){ 23 | element = newElem; 24 | } 25 | public void setNext(Node newNext){ 26 | next = newNext; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /ANSVP/src/NodeStack.java: -------------------------------------------------------------------------------- 1 | 2 | public class NodeStack implements Stack{ 3 | protected Node top; // reference to the head node 4 | protected int size; // number of elements in stack 5 | public NodeStack() { // constructs an empty stack 6 | top = null; 7 | size = 0; 8 | } 9 | public int size() { 10 | return size; 11 | } 12 | public boolean isEmpty() { 13 | if (top == null) 14 | return true; 15 | return false; 16 | } 17 | public void push(E elem) { 18 | Node v = new Node(elem,top); // create and link-in a new node 19 | top = v; 20 | size++; 21 | } 22 | public E top() throws EmptyStackException { 23 | if (isEmpty()) 24 | throw new EmptyStackException("Stack is empty."); 25 | return top.getElement(); 26 | } 27 | public E pop() throws EmptyStackException { 28 | if (isEmpty()) 29 | throw new EmptyStackException("Stack is empty."); 30 | E temp = top.getElement(); 31 | top = top.getNext(); // link out the former top node 32 | size--; 33 | return temp; 34 | 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /ANSVP/src/Stack.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Interface for a stack: a collection of objects that 3 | * are inserted and removed according to the last-in 4 | * first- out principle. This interface includes 5 | * the main methods of java.utill.Stack. 6 | * 7 | * @author Roberto Tamassia 8 | * @author Michael Goodrich 9 | * @see EmpthStackException 10 | */ 11 | public interface Stack { 12 | /** 13 | * @return the number of elements in the stack. 14 | */ 15 | public int size(); 16 | /** 17 | * @return true if the stack is empty, false otherwise. 18 | */ 19 | public boolean isEmpty(); 20 | /** 21 | * Inspect element at top. 22 | * @return top element in stack. 23 | * @exception EmptyStackException if the stack is empty. 24 | */ 25 | public E top() 26 | throws EmptyStackException; 27 | /** 28 | * Insert an element at top of stack. 29 | * @param element to be inserted 30 | */ 31 | public void push (E element); 32 | /** 33 | * Remove the top element of the stack 34 | * @return element removed. 35 | * @exception EmptyStackException 36 | */ 37 | public E pop() 38 | throws EmptyStackException; 39 | } 40 | -------------------------------------------------------------------------------- /ANSVP/src/StackANSVP.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author Steven Gerhard 3 | * ID: sjg10009 4 | */ 5 | 6 | import java.util.Arrays; 7 | import java.util.Scanner; 8 | 9 | public class StackANSVP { 10 | private Stack _S; 11 | 12 | public StackANSVP(int[] nums){ 13 | _S = new NodeStack(); // stack for comparison 14 | String[] ans = new String[nums.length]; // resultant array 15 | for(int i = 0; i < nums.length; i++){ // for every elem in nums 16 | while(!_S.isEmpty() && _S.top() >= nums[i] ) 17 | _S.pop(); // if S.top is greater than nums its useless 18 | if(_S.isEmpty()) 19 | ans[i] = "-"; // nums[i] has no preceding smaller value 20 | else 21 | ans[i] = String.valueOf(_S.top()); 22 | _S.push(nums[i]); // nearest smaller value is top of S 23 | } 24 | System.out.println("The nearest previous smaller values for this sequence:"); 25 | System.out.println(Arrays.toString(ans)); 26 | } 27 | 28 | public static void main(String[] args){ 29 | Scanner input = new Scanner(System.in); 30 | System.out.println("Enter the sequence:"); 31 | String hold = input.nextLine().replaceAll(",", " "); // removes commas from input 32 | String[] read = hold.split("\\s+"); // stores input as string array 33 | 34 | int[] nums = new int[read.length]; 35 | for (int i = 0; i < read.length; i++) // converts string array to num array 36 | nums[i] = Integer.parseInt(read[i]); 37 | StackANSVP run = new StackANSVP(nums); // passes num array to StackANSVP 38 | input.close(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /EquationSolver/README.md: -------------------------------------------------------------------------------- 1 | 5-1 Diophantine Equation Solver 2 | By Steven Gerhard 3 | 4 | compile src and run EquationSolver.class 5 | 6 | The 2-1 third-order Diophantine equation A^3 + B^3 = C^3, a special instance of Fermat’s 7 | Last Theorem, was proved in 1994 to not have any positive integral solution. Many fifth-order Diophantine equations do have integral solutions. For example, the 5-1 fifth-order equation (A^5)+(B^5)+(C^5)+(D^5)+(E^5) = (F^5) has an integral solution that satisfies 0<=A<=B<=C<=D<=E<=F<=N, where N is as small as 75. 8 | 9 | A straightforward approach to solving a 5-1 equation is to first precompute all values of X^5 and store them in an array. Then for each 5 tuple (A,B,C,D,E), 10 | check whether there exists some F such that the equation holds. This would take O(N^5) time which may have trouble finding even one solution on a typical personal computer. 11 | 12 | A more efficient algorithm sorts all the values of A^5 + B^5 + C^5 and 13 | F^5 - (D^5 + E^5). The values are compared one at a time (similar to way the pointers work during the merging procedure in mergeSort) to determine if a value in the first group is equal to a value in the second group. 14 | 15 | Using Heap-Sort implemented with a heap-based priority queue, solutions for 5-1 Diophantine equations can be found in O( (N^3)logN ) time. 16 | 17 | WARNING: Inputs of N larger than 100 may take a considerable amount of time, or produce a java.lang.OutOfMemoryError depending on your computer. 18 | -------------------------------------------------------------------------------- /EquationSolver/src/ArrayIndexList.java: -------------------------------------------------------------------------------- 1 | /** Realization of an indexed list by means of an array, which is doubled 2 | * when the size of the indexed list exceeds the capacity of the array. 3 | * Data Structures and Algorithms page 244 4 | */ 5 | 6 | public class ArrayIndexList { 7 | private E[] A; // array storing the elements of the indexed list 8 | private int capacity = 10; // initial length of array A 9 | private int size = 0; // number of elements stored in the indexed list 10 | /** Creates the indexed list with initial capacity 10. */ 11 | public ArrayIndexList() { 12 | A = (E[]) new Object[capacity]; 13 | } 14 | /** Inserts an element at the given index. */ 15 | public void add(int r, E e) 16 | throws IndexOutOfBoundsException { 17 | checkIndex(r,size() + 1); 18 | if(size == capacity) { // an overflow 19 | capacity *= 2; 20 | E[] B = (E[]) new Object[capacity]; 21 | for (int i = 0; i < size; i++) 22 | B[i] = A[i]; 23 | A = B; 24 | } 25 | for (int i = size -1; i >= r; i--) // shift elements up 26 | A[i+1] = A[i]; 27 | A[r] = e; 28 | size++; 29 | } 30 | /** Removes the element stored at the given index. */ 31 | public E remove(int r) 32 | throws IndexOutOfBoundsException{ 33 | checkIndex(r,size()); 34 | E temp = A[r]; 35 | for (int i=r; i= size) 44 | throw new IndexOutOfBoundsException(); 45 | } 46 | /** returns the number of elements stored */ 47 | public int size() { return size; } 48 | /** returns the element stored at index r */ 49 | public E get(int r){ 50 | return A[r]; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /EquationSolver/src/ArrayListCompleteBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a complete Binary Tree 3 | * stored as an ArrayIndexList 4 | * 5 | * from Data Structures and Algorithms page 355 6 | */ 7 | 8 | public class ArrayListCompleteBinaryTree { 9 | protected ArrayIndexList> T; // indexed list of tree positions 10 | 11 | /** Nested class for an index list-based complete binary tree node. */ 12 | protected static class BTPos implements Position { 13 | E element; // element stored at this position 14 | int index; // index of this position in the array 15 | public BTPos(E elt, int i) { 16 | element = elt; 17 | index = i; 18 | } 19 | public E element() { return element; } 20 | public int index() { return index; } 21 | public E setElement(E elt) { 22 | E temp = element; 23 | element = elt; 24 | return temp; 25 | } 26 | } 27 | 28 | /** default constructor */ 29 | public ArrayListCompleteBinaryTree() { 30 | T = new ArrayIndexList>(); 31 | T.add(0,null); // the location at rank 0 is deliberately empty 32 | } 33 | 34 | /** Returns the number of (internal and external) nodes. */ 35 | public int size() { return T.size() -1; } 36 | 37 | /** Returns whether the tree is empty. */ 38 | public boolean isEmpty() { return (size() == 0); } 39 | 40 | /** Returns whether v is an internal node. */ 41 | public boolean isInternal(Position v) throws InvalidPositionException { 42 | return hasLeft(v); // if v has a right child it will have a left child 43 | } 44 | 45 | /** Returns whether v is an external node. */ 46 | public boolean isExternal(Position v) throws InvalidPositionException { 47 | return !isInternal(v); 48 | } 49 | 50 | /** Returns whether v is the root node. */ 51 | public boolean isRoot(Position v) throws InvalidPositionException { 52 | BTPos vv = checkPosition(v); 53 | return vv.index() == 1; 54 | } 55 | 56 | /** Returns whether v has a left child. */ 57 | public boolean hasLeft(Position v) throws InvalidPositionException { 58 | BTPos vv = checkPosition(v); 59 | return 2*vv.index() <= size(); 60 | } 61 | 62 | /** Returns whether v has a right child. */ 63 | public boolean hasRight(Position v) throws InvalidPositionException { 64 | BTPos vv = checkPosition(v); 65 | return 2*vv.index() + 1 <= size(); 66 | } 67 | 68 | /** Returns the root of the tree. */ 69 | public Position root() throws EmptyTreeException { 70 | if (isEmpty()) throw new EmptyTreeException("Tree is empty"); 71 | return T.get(1); 72 | } 73 | 74 | /** Returns the left child of v. */ 75 | public Position left(Position v) 76 | throws InvalidPositionException, BoundaryViolationException { 77 | if(!hasLeft(v)) throw new BoundaryViolationException("No left child"); 78 | BTPos vv = checkPosition(v); 79 | return T.get(2*vv.index()); 80 | } 81 | 82 | /** Returns the right child of v. */ 83 | public Position right(Position v) 84 | throws InvalidPositionException, BoundaryViolationException { 85 | if(!hasRight(v)) throw new BoundaryViolationException("No right child"); 86 | BTPos vv = checkPosition(v); 87 | return T.get(2*vv.index() + 1); 88 | } 89 | 90 | /** Returns the parent of v. */ 91 | public Position parent(Position v) 92 | throws InvalidPositionException, BoundaryViolationException { 93 | if (isRoot(v)) throw new BoundaryViolationException("No parent"); 94 | BTPos vv = checkPosition(v); 95 | return T.get(vv.index()/2); 96 | } 97 | 98 | /** Replaces the element at v. */ 99 | public E replace(Position v, E o) throws InvalidPositionException { 100 | BTPos vv = checkPosition(v); 101 | return vv.setElement(o); 102 | } 103 | 104 | /** Adds an element just after the last node (in a level numbering). */ 105 | public Position add(E e) { 106 | int i = size() + 1; 107 | BTPos p = new BTPos(e,i); 108 | T.add(i,p); 109 | return p; 110 | } 111 | 112 | /** Removes and returns the element at the last node. */ 113 | public E remove() throws EmptyTreeException { 114 | if(isEmpty()) throw new EmptyTreeException("Tree is empty"); 115 | return T.remove(size()).element(); 116 | } 117 | 118 | /** Determines whether the given position is a valid node. */ 119 | protected BTPos checkPosition(Position v) 120 | throws InvalidPositionException { 121 | if ( v == null || !( v instanceof BTPos)) 122 | throw new InvalidPositionException("Position is invalid"); 123 | return (BTPos) v; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /EquationSolver/src/BoundaryViolationException.java: -------------------------------------------------------------------------------- 1 | 2 | public class BoundaryViolationException extends Exception { 3 | public BoundaryViolationException(String err) { 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /EquationSolver/src/DefaultComparator.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | 4 | public class DefaultComparator implements Comparator { 5 | @SuppressWarnings("unchecked") 6 | public int compare(E a, E b) throws ClassCastException { 7 | return ((Comparable) a).compareTo(b); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /EquationSolver/src/EmptyPriorityQueueException.java: -------------------------------------------------------------------------------- 1 | 2 | public class EmptyPriorityQueueException extends Exception { 3 | public EmptyPriorityQueueException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /EquationSolver/src/EmptyTreeException.java: -------------------------------------------------------------------------------- 1 | 2 | public class EmptyTreeException extends Exception { 3 | public EmptyTreeException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /EquationSolver/src/Entry.java: -------------------------------------------------------------------------------- 1 | /** Interface for a key-value pair entry **/ 2 | public interface Entry { 3 | /** Returns the key stored in this entry. */ 4 | public K getKey(); 5 | /** Returns the value stored in the entry. */ 6 | public V getValue(); 7 | } 8 | -------------------------------------------------------------------------------- /EquationSolver/src/EquationSolver.java: -------------------------------------------------------------------------------- 1 | /** @author Steven Gerhard 2 | * ID: sjg10009 3 | * 5-1 Diophantine Equation Solver 4 | * Using a Heap Priority Queue (from book) 5 | * stored in an ArrayIndexList 6 | */ 7 | 8 | import java.security.InvalidKeyException; 9 | import java.util.Scanner; 10 | 11 | public class EquationSolver { 12 | private HeapPriorityQueue> LHS,RHS; // stores solutions 13 | private long[] powerOf5; // all possible n^5 numbers 14 | 15 | public EquationSolver() { 16 | LHS = new HeapPriorityQueue>(); 17 | RHS = new HeapPriorityQueue>(); 18 | } 19 | 20 | /** generates all possible solutions */ 21 | public void generateSolutions(int max) throws InvalidKeyException, 22 | InvalidPositionException, BoundaryViolationException, 23 | EmptyPriorityQueueException, EmptyTreeException{ 24 | powerOf5 = allPow5(max); 25 | long num1,num2,num3,resLeft,resRight; 26 | //0A,j->B,k->C; i->D,j->E,k->F 27 | for(int i=1;i<=max;i++){ 28 | for(int j=i;j<=max;j++){ 29 | for(int k=j;k<=max;k++){ 30 | String solnA,solnB; 31 | solnA = "A:" + String.valueOf(i) + " " + 32 | "B:" + String.valueOf(j) + " " + 33 | "C:" + String.valueOf(k) + " "; 34 | solnB = "D:" + String.valueOf(i) + " " + 35 | "E:" + String.valueOf(j) + " " + 36 | "F:" + String.valueOf(k); 37 | num1=powerOf5[i]; 38 | num2=powerOf5[j]; 39 | num3=powerOf5[k]; 40 | // A^5 +B^5 +C^5 41 | resLeft=num1+num2+num3; 42 | // F^5-E^5-D^5 43 | resRight=num3-num2-num1; 44 | LHS.insert(resLeft, new MyEntry(solnA,k)); 45 | if(resRight>=0)RHS.insert(resRight,new MyEntry(solnB,i)); 46 | } 47 | } 48 | } 49 | } 50 | 51 | /** returns the left hand side. */ 52 | public HeapPriorityQueue> getLeft() { return LHS; } 53 | /** returns the right hand side */ 54 | public HeapPriorityQueue> getRight() { return RHS; } 55 | 56 | /** Creates a long array of all possible 57 | * values of x^5 58 | * quicker than computing each time 59 | */ 60 | public static long[] allPow5(int numElem){ 61 | long[] ans = new long[numElem+1]; 62 | for(int i = 0; i<= numElem; i++){ 63 | ans[i] = (long) (i) * (i) * (i) * (i) * (i); 64 | } 65 | return ans; 66 | } 67 | 68 | /** returns all solutions of A^5 + B^5 + C^5 + D^5 + E^5 = F^5 69 | * for A <= B <= C <= D <= E <= F <= N 70 | * determined by max input N 71 | */ 72 | public static void main(String[] args) throws InvalidKeyException, 73 | InvalidPositionException, BoundaryViolationException, 74 | EmptyPriorityQueueException, EmptyTreeException{ 75 | Scanner input = new Scanner(System.in); 76 | System.out.println("Enter max F:"); 77 | 78 | boolean hasAns = false; 79 | EquationSolver eq = new EquationSolver(); 80 | eq.generateSolutions(input.nextInt()); 81 | HeapPriorityQueue> right = eq.getRight(); 82 | HeapPriorityQueue> left = eq.getLeft(); 83 | 84 | while(!(left.isEmpty() || right.isEmpty())){ 85 | if (left.min().getKey() < right.min().getKey()) { 86 | left.removeMin(); 87 | } 88 | else 89 | if (left.min().getKey() > right.min().getKey()) { 90 | right.removeMin(); 91 | } 92 | else 93 | if (left.min().getKey().equals(right.min().getKey())) { 94 | if(left.min().getValue().getValue() <= right.min().getValue().getValue()){ 95 | System.out.println("Solution Found:"); 96 | System.out.println(left.min().getValue().getKey() + right.min().getValue().getKey()); 97 | } 98 | hasAns = true; 99 | left.removeMin(); 100 | right.removeMin(); 101 | } 102 | } 103 | if(!hasAns) System.out.print("No Solution"); 104 | input.close(); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /EquationSolver/src/HeapPriorityQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Realization of a priority queue by means of a heap. A complete 3 | * binary tree realized by means of an array list is used to 4 | * represent the heap. 5 | * 6 | * From Data Structures and Algorithms 7 | * page 363 8 | */ 9 | 10 | import java.security.InvalidKeyException; 11 | import java.util.Comparator; 12 | 13 | public class HeapPriorityQueue implements PriorityQueue { 14 | protected ArrayListCompleteBinaryTree> heap; // underlying heap 15 | protected Comparator comp; // comparator for the keys 16 | 17 | /** Creates an empty heap with the default comparator */ 18 | public HeapPriorityQueue(){ 19 | heap = new ArrayListCompleteBinaryTree>(); // use an array list 20 | comp = new DefaultComparator(); // use the default comparator 21 | } 22 | 23 | /** Creates an empty heap with the given comparator */ 24 | public HeapPriorityQueue(Comparator c){ 25 | heap = new ArrayListCompleteBinaryTree>(); 26 | comp = c; 27 | } 28 | 29 | /** Returns the size of the heap. */ 30 | public int size() { return heap.size(); } 31 | 32 | /** Returns whether the heap is empty. */ 33 | public boolean isEmpty() { return heap.size() == 0; } 34 | 35 | /** Returns but does not remove an entry with minimum key */ 36 | public Entry min() throws EmptyPriorityQueueException, EmptyTreeException { 37 | if (isEmpty()) 38 | throw new EmptyPriorityQueueException("Priority queue is empty"); 39 | return heap.root().element(); 40 | } 41 | 42 | /** Inserts a key-value pair and returns the entry created */ 43 | public Entry insert(K k, V x) throws InvalidKeyException, 44 | InvalidPositionException, BoundaryViolationException { 45 | checkKey(k); // may throw an InvalidKeyException 46 | Entry entry = new MyEntry(k,x); 47 | upHeap(heap.add(entry)); 48 | return entry; 49 | } 50 | 51 | /** Removes and returns an entry with minimum key */ 52 | public Entry removeMin() throws EmptyPriorityQueueException, EmptyTreeException, 53 | InvalidPositionException, BoundaryViolationException { 54 | if (isEmpty()) 55 | throw new EmptyPriorityQueueException("Priority Queue is empty"); 56 | Entry min = heap.root().element(); 57 | if (size() == 1) 58 | heap.remove(); 59 | else{ 60 | heap.replace(heap.root(), heap.remove()); 61 | downHeap(heap.root()); 62 | } 63 | return min; 64 | } 65 | 66 | /** Determines whether a give key is valid. */ 67 | protected void checkKey(K key) throws InvalidKeyException { 68 | try { 69 | comp.compare(key, key); 70 | } 71 | catch(Exception e) { 72 | throw new InvalidKeyException("Invalid key"); 73 | } 74 | } 75 | 76 | /** Perform up-heap bubbling. */ 77 | protected void upHeap(Position> v) throws InvalidPositionException, BoundaryViolationException { 78 | Position> u; 79 | while(!heap.isRoot(v)) { 80 | u = heap.parent(v); 81 | if (comp.compare(u.element().getKey(), v.element().getKey()) <= 0) break; 82 | swap(u,v); 83 | v = u; 84 | } 85 | } 86 | 87 | /** Perform down-heap bubbling */ 88 | protected void downHeap(Position> r) throws InvalidPositionException, BoundaryViolationException { 89 | while (heap.isInternal(r)) { 90 | Position> s; // the position of the smaller child 91 | if(!heap.hasRight(r)) 92 | s = heap.left(r); 93 | else if (comp.compare(heap.left(r).element().getKey(), 94 | heap.right(r).element().getKey()) <= 0) 95 | s = heap.left(r); 96 | else 97 | s = heap.right(r); 98 | if (comp.compare(s.element().getKey(), r.element().getKey()) < 0) { 99 | swap(r,s); 100 | r = s; 101 | } 102 | else 103 | break; 104 | } 105 | } 106 | 107 | /** Swaps the entries of the two given positions. */ 108 | protected void swap(Position> x, Position> y) throws InvalidPositionException { 109 | Entry temp = x.element(); 110 | heap.replace(x,y.element()); 111 | heap.replace(y, temp); 112 | } 113 | 114 | /** returns a sorted Entry[] */ 115 | public MyEntry[] PQsort() throws EmptyPriorityQueueException, EmptyTreeException, 116 | InvalidPositionException, BoundaryViolationException { 117 | MyEntry[] sorted = new MyEntry[size()]; 118 | int i = 0; 119 | while(!isEmpty()){ 120 | sorted[i] = (MyEntry) this.removeMin(); 121 | i++; 122 | } 123 | return sorted; 124 | } 125 | 126 | /** Text visualisation for debugging purposes */ 127 | public String toString() { 128 | return heap.toString(); 129 | } 130 | 131 | 132 | } -------------------------------------------------------------------------------- /EquationSolver/src/HeapSort.java: -------------------------------------------------------------------------------- 1 | 2 | public class HeapSort { 3 | 4 | } 5 | -------------------------------------------------------------------------------- /EquationSolver/src/InvalidPositionException.java: -------------------------------------------------------------------------------- 1 | 2 | public class InvalidPositionException extends Exception { 3 | public InvalidPositionException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /EquationSolver/src/MyEntry.java: -------------------------------------------------------------------------------- 1 | /** Inner class for heap entries. */ 2 | public final class MyEntry implements Entry{ 3 | protected K key; 4 | protected V value; 5 | public MyEntry(K k, V v) { key = k; value = v; } 6 | public K getKey() { return key; } 7 | public V getValue() { return value; } 8 | public String toString() { return "(" + key + "," + value + ")"; } 9 | } -------------------------------------------------------------------------------- /EquationSolver/src/Position.java: -------------------------------------------------------------------------------- 1 | public interface Position { 2 | /** Return the element stored at this position. */ 3 | E element(); 4 | } -------------------------------------------------------------------------------- /EquationSolver/src/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | /** Interface for the priority queue ADT */ 2 | import java.security.InvalidKeyException; 3 | 4 | public interface PriorityQueue { 5 | /** Returns the number of items in the priority queue. */ 6 | public int size(); 7 | /** Returns whether the priority queue is empty. */ 8 | public boolean isEmpty(); 9 | /** Returns but does not remove an entry with minimum key. */ 10 | public Entry min() 11 | throws EmptyPriorityQueueException, EmptyTreeException; 12 | /** Inserts a key-value pair and return the entry created. */ 13 | public Entry insert(K key, V value) 14 | throws InvalidKeyException, BoundaryViolationException, InvalidPositionException; 15 | /** Removes and returns an entry with minimum key. */ 16 | public Entry removeMin() 17 | throws EmptyPriorityQueueException, EmptyTreeException, InvalidPositionException, 18 | BoundaryViolationException; 19 | } 20 | -------------------------------------------------------------------------------- /MazeConstruct/README.txt: -------------------------------------------------------------------------------- 1 | MazeConstruct 2 | By Steven Gerhard 3 | 4 | compile src and run MazeConstruct.class 5 | 6 | Sample inputs and outputs are given in .txt files. 7 | 8 | MazeConstruct creates an n by n size text based maze based on the input n, and the weights of each maze wall. The maze is constructed by finding a minimum spanning tree T for input G and removing all the walls corresponding to edges in T. The minimum spanning tree is found using the Prim-Jarnik MST algorithm. -------------------------------------------------------------------------------- /MazeConstruct/constructinput.txt: -------------------------------------------------------------------------------- 1 | 4 1 0 2 3 2 | 1 2 3 3 | 4 5 6 7 4 | 8 9 10 5 | 11 12 13 14 6 | 15 16 17 7 | 18 19 20 21 8 | 22 23 24 9 | -------------------------------------------------------------------------------- /MazeConstruct/constructoutput.txt: -------------------------------------------------------------------------------- 1 | 0 0 0 1 2 | 0 0 1 0 3 | 0 1 0 2 4 | 0 1 1 1 5 | 0 2 0 3 6 | 0 2 1 2 7 | 0 3 1 3 8 | 1 0 2 0 9 | 1 1 2 1 10 | 1 2 2 2 11 | 1 3 2 3 12 | 2 0 3 0 13 | 2 1 3 1 14 | 2 2 3 2 15 | 2 3 3 3 16 | 17 | _ _ _ _ 18 | | | 19 | | | | | 20 | | | | | 21 | |_|_|_|_| 22 | 23 | -------------------------------------------------------------------------------- /MazeConstruct/src/ArrayIndexList.java: -------------------------------------------------------------------------------- 1 | /** Realization of an indexed list by means of an array, which is doubled 2 | * when the size of the indexed list exceeds the capacity of the array. 3 | * Data Structures and Algorithms page 244 4 | */ 5 | 6 | public class ArrayIndexList { 7 | private E[] A; // array storing the elements of the indexed list 8 | private int capacity = 10; // initial length of array A 9 | private int size = 0; // number of elements stored in the indexed list 10 | /** Creates the indexed list with initial capacity 10. */ 11 | public ArrayIndexList() { 12 | A = (E[]) new Object[capacity]; 13 | } 14 | /** Inserts an element at the given index. */ 15 | public void add(int r, E e) 16 | throws IndexOutOfBoundsException { 17 | checkIndex(r,size() + 1); 18 | if(size == capacity) { // an overflow 19 | capacity *= 2; 20 | E[] B = (E[]) new Object[capacity]; 21 | for (int i = 0; i < size; i++) 22 | B[i] = A[i]; 23 | A = B; 24 | } 25 | for (int i = size -1; i >= r; i--) // shift elements up 26 | A[i+1] = A[i]; 27 | A[r] = e; 28 | size++; 29 | } 30 | /** Removes and returns the element stored at the given index. 31 | * Shifts all elements down in list */ 32 | public E remove(int r) 33 | throws IndexOutOfBoundsException{ 34 | checkIndex(r,size()); 35 | E temp = A[r]; 36 | for (int i=r; i= size) 45 | throw new IndexOutOfBoundsException(); 46 | } 47 | /** returns the number of elements stored */ 48 | public int size() { return size; } 49 | /** returns the element stored at index r */ 50 | 51 | public E get(int r){ 52 | return A[r]; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /MazeConstruct/src/ArrayListCompleteBinaryTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a complete Binary Tree 3 | * stored as an ArrayIndexList 4 | * 5 | * from Data Structures and Algorithms page 355 6 | */ 7 | 8 | public class ArrayListCompleteBinaryTree { 9 | protected ArrayIndexList> T; // indexed list of tree positions 10 | 11 | /** Nested class for an index list-based complete binary tree node. */ 12 | protected static class BTPos implements Position { 13 | E element; // element stored at this position 14 | int index; // index of this position in the array 15 | public BTPos(E elt, int i) { 16 | element = elt; 17 | index = i; 18 | } 19 | public E element() { return element; } 20 | public int index() { return index; } 21 | public E setElement(E elt) { 22 | E temp = element; 23 | element = elt; 24 | return temp; 25 | } 26 | } 27 | 28 | /** default constructor */ 29 | public ArrayListCompleteBinaryTree() { 30 | T = new ArrayIndexList>(); 31 | T.add(0,null); // the location at rank 0 is deliberately empty 32 | } 33 | 34 | /** Returns the number of (internal and external) nodes. */ 35 | public int size() { return T.size() -1; } 36 | 37 | /** Returns whether the tree is empty. */ 38 | public boolean isEmpty() { return (size() == 0); } 39 | 40 | /** Returns whether v is an internal node. */ 41 | public boolean isInternal(Position v) throws InvalidPositionException { 42 | return hasLeft(v); // if v has a right child it will have a left child 43 | } 44 | 45 | /** Returns whether v is an external node. */ 46 | public boolean isExternal(Position v) throws InvalidPositionException { 47 | return !isInternal(v); 48 | } 49 | 50 | /** Returns whether v is the root node. */ 51 | public boolean isRoot(Position v) throws InvalidPositionException { 52 | BTPos vv = checkPosition(v); 53 | return vv.index() == 1; 54 | } 55 | 56 | /** Returns whether v has a left child. */ 57 | public boolean hasLeft(Position v) throws InvalidPositionException { 58 | BTPos vv = checkPosition(v); 59 | return 2*vv.index() <= size(); 60 | } 61 | 62 | /** Returns whether v has a right child. */ 63 | public boolean hasRight(Position v) throws InvalidPositionException { 64 | BTPos vv = checkPosition(v); 65 | return 2*vv.index() + 1 <= size(); 66 | } 67 | 68 | /** Returns the root of the tree. */ 69 | public Position root() throws EmptyTreeException { 70 | if (isEmpty()) throw new EmptyTreeException("Tree is empty"); 71 | return T.get(1); 72 | } 73 | 74 | /** Returns the left child of v. */ 75 | public Position left(Position v) 76 | throws InvalidPositionException, BoundaryViolationException { 77 | if(!hasLeft(v)) throw new BoundaryViolationException("No left child"); 78 | BTPos vv = checkPosition(v); 79 | return T.get(2*vv.index()); 80 | } 81 | 82 | /** Returns the right child of v. */ 83 | public Position right(Position v) 84 | throws InvalidPositionException, BoundaryViolationException { 85 | if(!hasRight(v)) throw new BoundaryViolationException("No right child"); 86 | BTPos vv = checkPosition(v); 87 | return T.get(2*vv.index() + 1); 88 | } 89 | 90 | /** Returns the parent of v. */ 91 | public Position parent(Position v) 92 | throws InvalidPositionException, BoundaryViolationException { 93 | if (isRoot(v)) throw new BoundaryViolationException("No parent"); 94 | BTPos vv = checkPosition(v); 95 | return T.get(vv.index()/2); 96 | } 97 | 98 | /** Replaces the element at v. */ 99 | public E replace(Position v, E o) throws InvalidPositionException { 100 | BTPos vv = checkPosition(v); 101 | return vv.setElement(o); 102 | } 103 | 104 | /** Adds an element just after the last node (in a level numbering). */ 105 | public Position add(E e) { 106 | int i = size() + 1; 107 | BTPos p = new BTPos(e,i); 108 | T.add(i,p); 109 | return p; 110 | } 111 | 112 | /** Removes and returns the element at the last node. */ 113 | public E remove() throws EmptyTreeException { 114 | if(isEmpty()) throw new EmptyTreeException("Tree is empty"); 115 | return T.remove(size()).element(); 116 | } 117 | 118 | /** Determines whether the given position is a valid node. */ 119 | protected BTPos checkPosition(Position v) 120 | throws InvalidPositionException { 121 | if ( v == null || !( v instanceof BTPos)) 122 | throw new InvalidPositionException("Position is invalid"); 123 | return (BTPos) v; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /MazeConstruct/src/BoundaryViolationException.java: -------------------------------------------------------------------------------- 1 | 2 | public class BoundaryViolationException extends Exception { 3 | public BoundaryViolationException(String err) { 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MazeConstruct/src/Cell.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Cell Object 3 | * stores x,y coordinates for maze 4 | * @author SteveG 5 | */ 6 | 7 | public class Cell { 8 | int x,y; 9 | 10 | public Cell(int X, int Y) { 11 | x = X; 12 | y = Y; 13 | } 14 | 15 | public int getX() { return x; } 16 | public int getY() { return y; } 17 | public void print() { 18 | System.out.print("(" + x + "," + y + ") "); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /MazeConstruct/src/DefaultComparator.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | 3 | 4 | public class DefaultComparator implements Comparator { 5 | @SuppressWarnings("unchecked") 6 | public int compare(E a, E b) throws ClassCastException { 7 | return ((Comparable) a).compareTo(b); 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /MazeConstruct/src/Edge.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Edge Object 3 | * stores an element (wall weight) 4 | * and 2 vertices 5 | * also stores index for edge list graph structure 6 | * @author Steven Gerhard 7 | */ 8 | 9 | public class Edge { 10 | 11 | private int weight; 12 | private int index; 13 | private Vertex v1,v2; 14 | 15 | public Edge(int in, int wei, Vertex V1, Vertex V2) { 16 | weight = wei; 17 | index = in; 18 | v1 = V1; 19 | v2 = V2; 20 | } 21 | public Vertex vertex1() { return v1; } 22 | public Vertex vertex2() { return v2; } 23 | public ArrayIndexList vertices() { 24 | ArrayIndexList ans = new ArrayIndexList(); 25 | ans.add(0,v1); 26 | ans.add(1,v2); 27 | return ans; 28 | } 29 | public int weight() { return weight; } 30 | public int index() { return index; } 31 | public void setIndex(int i) { index = i; } 32 | public int setWeight(int wei) { 33 | int temp = weight; 34 | weight = wei; 35 | return temp; 36 | } 37 | 38 | public void print() { 39 | v1.print(); 40 | v2.print(); 41 | System.out.println(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /MazeConstruct/src/EdgeListGraph.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This creates a graph implemented using edge list structure. 3 | * All vertices stored in an ArrayIndex 4 | * All edges stored in an ArrayIndex 5 | * @author Steven Gerhard 6 | * 7 | */ 8 | 9 | public class EdgeListGraph { 10 | 11 | private ArrayIndexList edges; 12 | private ArrayIndexList vertices; 13 | 14 | /** Creates a new EdgeListGraph. */ 15 | public EdgeListGraph() { 16 | edges = new ArrayIndexList(); 17 | vertices = new ArrayIndexList(); 18 | } 19 | 20 | /** Returns the vertices a given edge connects. */ 21 | public ArrayIndexList endVertices(Edge e) { 22 | return e.vertices(); 23 | } 24 | 25 | /** Returns the opposite vertex given an edge and 1 vertex. */ 26 | public Vertex opposite(Vertex ver, Edge ed) { 27 | ArrayIndexList test = ed.vertices(); 28 | if (test.get(0).equals(ver)) 29 | return test.get(1); 30 | else 31 | return test.get(0); 32 | } 33 | 34 | /** Returns true iff an edge connects the two vertices. */ 35 | public boolean areAdjacent(Vertex v1, Vertex v2) { 36 | boolean ans = false; 37 | for(int i = 0; i temp = incidentEdges(ans); 97 | while (temp.size() != 0) { 98 | this.removeEdge(temp.get(0).index()); 99 | temp.remove(0); 100 | } 101 | return ans; 102 | } 103 | 104 | /** Remove and returns edge at given index. */ 105 | public Edge removeEdge(int r) { 106 | Edge ans = null; 107 | for(int i = 0; i < edges.size(); i++) { 108 | if( edges.get(i).index() == r) { 109 | ans = edges.remove(i); 110 | break; 111 | } 112 | } 113 | return ans; 114 | } 115 | 116 | /** Returns an array of incidentEdges to a given vertex. */ 117 | public ArrayIndexList incidentEdges(Vertex ver) { 118 | ArrayIndexList ans = new ArrayIndexList(); 119 | int x = 0; 120 | for( int i = 0; i < edges.size(); i++) { 121 | if(edges.get(i).vertex1().equals(ver) || edges.get(i).vertex2().equals(ver)) { 122 | ans.add(x, edges().get(i)); 123 | x++; 124 | } 125 | } 126 | return ans; 127 | } 128 | /** Returns an array of all vertexes 129 | * the first vertex has index 0 */ 130 | public ArrayIndexList vertices() { 131 | return vertices; 132 | } 133 | /** Returns an array of all edges. 134 | * the first edge has index 0 */ 135 | public ArrayIndexList edges() { 136 | return edges; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /MazeConstruct/src/EmptyPriorityQueueException.java: -------------------------------------------------------------------------------- 1 | 2 | public class EmptyPriorityQueueException extends Exception { 3 | public EmptyPriorityQueueException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MazeConstruct/src/EmptyTreeException.java: -------------------------------------------------------------------------------- 1 | 2 | public class EmptyTreeException extends Exception { 3 | public EmptyTreeException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MazeConstruct/src/Entry.java: -------------------------------------------------------------------------------- 1 | /** Interface for a key-value pair entry **/ 2 | public interface Entry { 3 | /** Returns the key stored in this entry. */ 4 | public K getKey(); 5 | /** Returns the value stored in the entry. */ 6 | public V getValue(); 7 | } 8 | -------------------------------------------------------------------------------- /MazeConstruct/src/HeapAdaptablePriorityQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Realization of an adaptable priority queue by means of a heap. 3 | * 4 | * @see HeapPriorityQueue 5 | */ 6 | import java.security.InvalidKeyException; 7 | import java.util.Comparator; 8 | 9 | public class HeapAdaptablePriorityQueue extends HeapPriorityQueue { 10 | 11 | /** Creates an empty heap with a default comparator. */ 12 | public HeapAdaptablePriorityQueue() { 13 | super(); 14 | } 15 | 16 | /** Creates an empty heap with the given comparator. */ 17 | public HeapAdaptablePriorityQueue(Comparator comp) { 18 | super(comp); 19 | } 20 | 21 | /** Inserts a key-value pair and returns the entry created. 22 | * @throws BoundaryViolationException 23 | * @throws InvalidPositionException */ 24 | public Entry insert (K k, V v) throws InvalidKeyException, InvalidPositionException, BoundaryViolationException { 25 | checkKey(k); 26 | LocationAwareEntry entry = new LocationAwareEntry(k,v); 27 | Position z = heap.add(entry); // add entry to the tree 28 | entry.setLocation(z); // make this entry location-aware 29 | upHeap(z); // perform up-heap bubbling 30 | return entry; 31 | } 32 | 33 | /** Removes and returns the given entry from the heap. 34 | * @throws EmptyTreeException 35 | * @throws BoundaryViolationException 36 | * @throws InvalidPositionException */ 37 | public Entry remove(Entry entry) throws InvalidEntryException, 38 | EmptyTreeException, InvalidPositionException, BoundaryViolationException { 39 | LocationAwareEntry ee = checkEntry(entry); 40 | Position p = ee.location(); 41 | if(size() == 1) 42 | return (Entry) heap.remove(); 43 | replaceEntry(p,(LocationAwareEntry) heap.remove()); 44 | upHeap(p); 45 | downHeap(p); 46 | ee.setLocation(null); 47 | return ee; 48 | } 49 | 50 | /** Replaces the key of the given entry. 51 | * @throws BoundaryViolationException 52 | * @throws InvalidPositionException 53 | * @throws InvalidKeyException */ 54 | public K replaceKey(Entry entry, K k) 55 | throws InvalidEntryException, InvalidPositionException, BoundaryViolationException, 56 | InvalidKeyException { 57 | checkKey(k); 58 | LocationAwareEntry ee = checkEntry(entry); 59 | K oldKey = ee.setKey(k); 60 | upHeap(ee.location()); 61 | downHeap(ee.location()); 62 | return oldKey; 63 | } 64 | 65 | /** Replaces the value of the given entry. */ 66 | public V replaceValue(Entry e, V value) throws InvalidEntryException { 67 | LocationAwareEntry ee = checkEntry(e); 68 | return ee.setValue(value); 69 | } 70 | 71 | /** Swaps the elements of the two positions. This method is called 72 | * when up-heaping and down-heaping. 73 | * @throws InvalidPositionException */ 74 | protected void swap(Position> u, Position> v) throws InvalidPositionException { 75 | super.swap(u,v); // swap the entries held by the positions 76 | getEntry(u).setLocation(u); // swap the position references 77 | getEntry(v).setLocation(v); 78 | } 79 | 80 | /** Replaces the element of the given position with the given 81 | * location-aware entry. 82 | * @throws InvalidPositionException */ 83 | protected Position replaceEntry(Position v, LocationAwareEntry e) throws InvalidPositionException { 84 | heap.replace(v,e); // replace the entry in the tree 85 | return e.setLocation(v); // make the new entry aware of its position 86 | } 87 | 88 | /** Returns the entry stored at a heap node. */ 89 | protected LocationAwareEntry getEntry (Position p) { 90 | return (LocationAwareEntry) p.element(); 91 | } 92 | 93 | /** Check whether a given entry is valid. */ 94 | protected LocationAwareEntry checkEntry(Entry ent) 95 | throws InvalidEntryException { 96 | if(ent == null || !(ent instanceof LocationAwareEntry)) 97 | new InvalidEntryException("Invalid entry"); 98 | return (LocationAwareEntry)ent; 99 | } 100 | 101 | /** Inner class for a location-aware entry. */ 102 | protected static class LocationAwareEntry 103 | extends MyEntry implements Entry { 104 | protected Position loc; 105 | public LocationAwareEntry(K k, V v) { super(k, v); } 106 | public LocationAwareEntry(K k, V v, Position pos) { super(k, v); loc = pos; } 107 | protected Position location() { return loc; } 108 | protected Position setLocation(Position pos) { 109 | Position oldPosition = location(); 110 | loc = pos; 111 | return oldPosition; 112 | } 113 | protected K setKey(K k) { 114 | K oldKey = getKey(); 115 | key = k; 116 | return oldKey; 117 | } 118 | protected V setValue(V v) { 119 | V oldValue = getValue(); 120 | value = v; 121 | return oldValue; 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /MazeConstruct/src/HeapPriorityQueue.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Realization of a priority queue by means of a heap. A complete 3 | * binary tree realized by means of an array list is used to 4 | * represent the heap. 5 | * 6 | * From Data Structures and Algorithms 7 | * page 363 8 | */ 9 | 10 | import java.security.InvalidKeyException; 11 | import java.util.Comparator; 12 | 13 | public class HeapPriorityQueue implements PriorityQueue { 14 | protected ArrayListCompleteBinaryTree> heap; // underlying heap 15 | protected Comparator comp; // comparator for the keys 16 | 17 | /** Creates an empty heap with the default comparator */ 18 | public HeapPriorityQueue(){ 19 | heap = new ArrayListCompleteBinaryTree>(); // use an array list 20 | comp = new DefaultComparator(); // use the default comparator 21 | } 22 | 23 | /** Creates an empty heap with the given comparator */ 24 | public HeapPriorityQueue(Comparator c){ 25 | heap = new ArrayListCompleteBinaryTree>(); 26 | comp = c; 27 | } 28 | 29 | /** Returns the size of the heap. */ 30 | public int size() { return heap.size(); } 31 | 32 | /** Returns whether the heap is empty. */ 33 | public boolean isEmpty() { return heap.size() == 0; } 34 | 35 | /** Returns but does not remove an entry with minimum key */ 36 | public Entry min() throws EmptyPriorityQueueException, EmptyTreeException { 37 | if (isEmpty()) 38 | throw new EmptyPriorityQueueException("Priority queue is empty"); 39 | return heap.root().element(); 40 | } 41 | 42 | /** Inserts a key-value pair and returns the entry created */ 43 | public Entry insert(K k, V x) throws InvalidKeyException, 44 | InvalidPositionException, BoundaryViolationException { 45 | checkKey(k); // may throw an InvalidKeyException 46 | Entry entry = new MyEntry(k,x); 47 | upHeap(heap.add(entry)); 48 | return entry; 49 | } 50 | 51 | /** Removes and returns an entry with minimum key */ 52 | public Entry removeMin() throws EmptyPriorityQueueException, EmptyTreeException, 53 | InvalidPositionException, BoundaryViolationException { 54 | if (isEmpty()) 55 | throw new EmptyPriorityQueueException("Priority Queue is empty"); 56 | Entry min = heap.root().element(); 57 | if (size() == 1) 58 | heap.remove(); 59 | else{ 60 | heap.replace(heap.root(), heap.remove()); 61 | downHeap(heap.root()); 62 | } 63 | return min; 64 | } 65 | 66 | /** Determines whether a give key is valid. */ 67 | protected void checkKey(K key) throws InvalidKeyException { 68 | try { 69 | comp.compare(key, key); 70 | } 71 | catch(Exception e) { 72 | throw new InvalidKeyException("Invalid key"); 73 | } 74 | } 75 | 76 | /** Perform up-heap bubbling. */ 77 | protected void upHeap(Position> v) throws InvalidPositionException, BoundaryViolationException { 78 | Position> u; 79 | while(!heap.isRoot(v)) { 80 | u = heap.parent(v); 81 | if (comp.compare(u.element().getKey(), v.element().getKey()) <= 0) break; 82 | swap(u,v); 83 | v = u; 84 | } 85 | } 86 | 87 | /** Perform down-heap bubbling */ 88 | protected void downHeap(Position> r) throws InvalidPositionException, BoundaryViolationException { 89 | while (heap.isInternal(r)) { 90 | Position> s; // the position of the smaller child 91 | if(!heap.hasRight(r)) 92 | s = heap.left(r); 93 | else if (comp.compare(heap.left(r).element().getKey(), 94 | heap.right(r).element().getKey()) <= 0) 95 | s = heap.left(r); 96 | else 97 | s = heap.right(r); 98 | if (comp.compare(s.element().getKey(), r.element().getKey()) < 0) { 99 | swap(r,s); 100 | r = s; 101 | } 102 | else 103 | break; 104 | } 105 | } 106 | 107 | /** Swaps the entries of the two given positions. */ 108 | protected void swap(Position> x, Position> y) throws InvalidPositionException { 109 | Entry temp = x.element(); 110 | heap.replace(x,y.element()); 111 | heap.replace(y, temp); 112 | } 113 | 114 | /** returns a sorted Entry[] */ 115 | public MyEntry[] PQsort() throws EmptyPriorityQueueException, EmptyTreeException, 116 | InvalidPositionException, BoundaryViolationException { 117 | MyEntry[] sorted = new MyEntry[size()]; 118 | int i = 0; 119 | while(!isEmpty()){ 120 | sorted[i] = (MyEntry) this.removeMin(); 121 | i++; 122 | } 123 | return sorted; 124 | } 125 | 126 | /** Text visualisation for debugging purposes */ 127 | public String toString() { 128 | return heap.toString(); 129 | } 130 | } 131 | 132 | 133 | -------------------------------------------------------------------------------- /MazeConstruct/src/InvalidEntryException.java: -------------------------------------------------------------------------------- 1 | 2 | public class InvalidEntryException extends Exception { 3 | public InvalidEntryException(String err) { 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MazeConstruct/src/InvalidPositionException.java: -------------------------------------------------------------------------------- 1 | 2 | public class InvalidPositionException extends Exception { 3 | public InvalidPositionException(String err){ 4 | super(err); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /MazeConstruct/src/MazeConstruct.java: -------------------------------------------------------------------------------- 1 | import java.security.InvalidKeyException; 2 | import java.util.Scanner; 3 | /** 4 | * @author Steven Gerhard 5 | * ID: 1849880 6 | * December 2013 7 | * Maze Construct Creates a Maze from given inputs 8 | * 9 | */ 10 | 11 | public class MazeConstruct { 12 | private Cell start, finish; 13 | private int N; // Maze dimensions n*n 14 | 15 | public MazeConstruct() { 16 | start = null; 17 | finish = null; 18 | } 19 | 20 | /** Draws the given maze.*/ 21 | public void drawMaze(EdgeListGraph G) { 22 | System.out.println(); 23 | System.out.println("Edges:"); 24 | for( int e = 0; e < G.edges().size(); e++ ) { 25 | G.edges().get(e).print(); 26 | } 27 | 28 | int v = 0; // index for G.vertices() 29 | System.out.print(" _"); 30 | for(int i = 1; i < N-1; i++ ){ //for top line of maze 31 | if( (start.getX() == 0 && start.getY() == i) || 32 | (finish.getX() == 0 && finish.getY() == i) ) { // if start/finish 33 | System.out.print(" "); // do not print wall 34 | } 35 | else { 36 | System.out.print(" _"); 37 | } 38 | } 39 | System.out.print(" _"); 40 | // Top line of maze is correctly printed, now iterator through (rows,columns) 41 | for( int i = 0; i < N; i++ ) { // row iterator, row = i 42 | System.out.println(); 43 | if( (start.getX() == i && start.getY() == 0) || 44 | (finish.getX() == i && finish.getY() == 0) ) { // if start/finish at begin of row 45 | System.out.print(" "); // do not print wall 46 | } 47 | else { 48 | System.out.print("|"); 49 | } 50 | 51 | for( int j = 0; j < N; j++ ) { // column iterator, column = j 52 | if (i < N-1) { 53 | if( j < N-1) { 54 | if(G.areAdjacent(G.vertices().get(v),G.vertices().get(v+N))) { 55 | System.out.print(" "); 56 | } 57 | else { 58 | System.out.print("_"); 59 | } 60 | if( G.areAdjacent(G.vertices().get(v), G.vertices().get(v+1))) { 61 | System.out.print(" "); 62 | } 63 | else { 64 | System.out.print("|"); 65 | } 66 | v++; 67 | } 68 | else { 69 | if(G.areAdjacent(G.vertices().get(v),G.vertices().get(v+N))) { 70 | System.out.print(" "); 71 | } 72 | else { 73 | System.out.print("_"); 74 | } 75 | if ((start.getX() == i && start.getY() == N-1) || // if at end of row 76 | (finish.getX() == i && finish.getY() == N-1)) { // and start/finish 77 | System.out.print(" "); // do not print wall 78 | } 79 | else { 80 | System.out.print("|"); 81 | } 82 | v++; 83 | } 84 | 85 | } 86 | 87 | else { // (i == N-1) last row is handled differently 88 | if( j == 0 || j == N-1) { // if last row end columns, always print bottom wall 89 | System.out.print("_"); 90 | } 91 | else if ((start.getX() == i && start.getY() == j) || // else if in last row middle columns 92 | (finish.getX() == i && finish.getY() == j)) { // and start/finish 93 | System.out.print(" "); // do not print wall 94 | } 95 | else { 96 | System.out.print("_"); 97 | } 98 | if (j < N-1) { 99 | if( G.areAdjacent(G.vertices().get(v), G.vertices().get(v+1))) { 100 | System.out.print(" "); 101 | } 102 | else { 103 | System.out.print("|"); 104 | } 105 | v++; 106 | } 107 | else { // j == N-1 108 | if ((start.getX() == i && start.getY() == N-1) || // if in last row end columns 109 | (finish.getX() == i && finish.getY() == N-1)) { // and start/finish 110 | System.out.print(" "); // do not print wall 111 | } 112 | else { 113 | System.out.print("|"); 114 | } 115 | v++; 116 | } 117 | } 118 | } 119 | } 120 | System.out.println(); 121 | 122 | } 123 | 124 | 125 | 126 | /** Sets the start of maze. */ 127 | public void setStart(Cell Start) { 128 | start = Start; 129 | } 130 | 131 | /** Sets the end of maze. */ 132 | public void setFinish(Cell Finish) { 133 | finish = Finish; 134 | } 135 | 136 | /** Sets maze dimensions. */ 137 | public void setDimension(int n) { N = n; } 138 | 139 | /** Returns start Cell of maze. */ 140 | public Cell start() { return start; } 141 | 142 | /** Returns finish Cell of maze. */ 143 | public Cell finish() { return finish; } 144 | 145 | public static void main(String[] args) throws InvalidKeyException, 146 | InvalidPositionException, BoundaryViolationException, 147 | EmptyPriorityQueueException, EmptyTreeException, InvalidEntryException { 148 | Scanner input = new Scanner(System.in); 149 | MazeConstruct maze = new MazeConstruct(); 150 | EdgeListGraph dual = new EdgeListGraph(); 151 | System.out.println("Enter Maze Paramaters"); 152 | System.out.println("n r_start c_start r_finish c_finish"); 153 | System.out.println("wall weight line 1..."); 154 | int n = input.nextInt(); 155 | maze.setDimension(n); 156 | int x = 0; // index for vertices 157 | for (int i = 0; i < n; i++) { // x coordinate 158 | for (int j = 0; j < n; j++) { // y coordinate 159 | Vertex v = new Vertex(x, i, j); 160 | x++; 161 | dual.insertVertex(v); 162 | } 163 | } 164 | maze.setStart(new Cell(input.nextInt(),input.nextInt())); 165 | maze.setFinish(new Cell(input.nextInt(),input.nextInt())); 166 | int y = 0; // index for edges 167 | // The loops below add all the edges based off input weights 168 | // The vertices have indices 0 to (n*n)-1 169 | for (int i = 0; i < n-1; i++) { 170 | for (int j = i*n; j < ((i+1)*n)-1; j++) { 171 | dual.insertEdge(new Edge(y,input.nextInt(),dual.vertices().get(j), dual.vertices().get(j+1))); 172 | y++; 173 | } 174 | for (int k = i*n; k < (i+1)*n; k++) { 175 | dual.insertEdge(new Edge(y,input.nextInt(),dual.vertices().get(k),dual.vertices().get(k+n))); 176 | y++; 177 | } 178 | } 179 | for (int i = ((n*(n-1))); i < (n*n)-1; i++ ) { 180 | dual.insertEdge(new Edge(y,input.nextInt(),dual.vertices().get(i), dual.vertices().get(i+1))); 181 | y++; 182 | } 183 | EdgeListGraph MST = new PrimJarnikMST().MST(dual); 184 | maze.drawMaze(MST); 185 | System.out.println("Number of vertices: " + MST.vertices().size()); 186 | System.out.println("Number of edges: " + MST.edges().size()); 187 | input.close(); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /MazeConstruct/src/MyEntry.java: -------------------------------------------------------------------------------- 1 | /** Inner class for heap entries. */ 2 | public class MyEntry implements Entry{ 3 | protected K key; 4 | protected V value; 5 | public MyEntry(K k, V v) { key = k; value = v; } 6 | public K getKey() { return key; } 7 | public V getValue() { return value; } 8 | public String toString() { return "(" + key + "," + value + ")"; } 9 | } -------------------------------------------------------------------------------- /MazeConstruct/src/Position.java: -------------------------------------------------------------------------------- 1 | public interface Position { 2 | /** Return the element stored at this position. */ 3 | E element(); 4 | } -------------------------------------------------------------------------------- /MazeConstruct/src/PrimJarnikMST.java: -------------------------------------------------------------------------------- 1 | import java.security.InvalidKeyException; 2 | /** 3 | * Prim's Algorithm 4 | * Creates MST of a given Graph 5 | * @author SteveG 6 | * 7 | */ 8 | 9 | public class PrimJarnikMST { 10 | 11 | private Vertex[] vertices; 12 | private int[] distance; 13 | private Edge[] parent; 14 | private MyEntry[] entry; 15 | 16 | /** 17 | * @throws BoundaryViolationException 18 | * @throws InvalidPositionException 19 | * @throws InvalidKeyException 20 | * @throws EmptyTreeException 21 | * @throws EmptyPriorityQueueException */ 22 | 23 | 24 | public PrimJarnikMST() {} 25 | 26 | public EdgeListGraph MST(EdgeListGraph G) throws InvalidKeyException, 27 | InvalidPositionException, BoundaryViolationException, 28 | EmptyPriorityQueueException, EmptyTreeException, InvalidEntryException { 29 | 30 | HeapAdaptablePriorityQueue Q = 31 | new HeapAdaptablePriorityQueue(); 32 | int n = G.vertices().size(); 33 | vertices = new Vertex[n]; 34 | distance = new int[n]; 35 | parent = new Edge[n]; 36 | entry = new MyEntry[n]; 37 | 38 | for (int i = 0; i < G.vertices().size(); i++ ) { 39 | 40 | if( i == 0) { 41 | distance[i] = 0; // Root of cloud 42 | } 43 | else { 44 | distance[i] = Integer.MAX_VALUE; 45 | } 46 | parent[i] = null; 47 | vertices[i] = G.vertices().get(i); 48 | entry[i] = (MyEntry) Q.insert(distance[i], vertices[i]); 49 | } 50 | 51 | 52 | while(!Q.isEmpty()) { 53 | Vertex u = Q.removeMin().getValue(); 54 | 55 | for( int i = 0; i < G.incidentEdges(u).size(); i++ ) { 56 | Edge e = G.incidentEdges(u).get(i); 57 | Vertex z = G.opposite(u,e); 58 | int r = e.weight(); 59 | if ( r < distance[z.index()]) { 60 | distance[z.index()] = r; 61 | parent[z.index()] = e; 62 | Q.replaceKey(entry[z.index()], r); 63 | } 64 | 65 | 66 | } 67 | } 68 | 69 | 70 | EdgeListGraph ans = new EdgeListGraph(); 71 | for( int i = 0; i < vertices.length; i++ ) { 72 | ans.insertVertex(vertices[i]); 73 | } 74 | int x = 0; 75 | for( int j = 0; j < parent.length; j++ ) { 76 | if(parent[j] != (null)) { 77 | parent[j].setIndex(x); 78 | ans.insertEdge(parent[j]); 79 | x = x+1; 80 | } 81 | } 82 | return ans; 83 | 84 | } 85 | 86 | public Edge[] edges() { return parent; } 87 | public Vertex[] vertices() { return vertices; } 88 | 89 | 90 | } 91 | -------------------------------------------------------------------------------- /MazeConstruct/src/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | /** Interface for the priority queue ADT */ 2 | import java.security.InvalidKeyException; 3 | 4 | public interface PriorityQueue { 5 | /** Returns the number of items in the priority queue. */ 6 | public int size(); 7 | /** Returns whether the priority queue is empty. */ 8 | public boolean isEmpty(); 9 | /** Returns but does not remove an entry with minimum key. */ 10 | public Entry min() 11 | throws EmptyPriorityQueueException, EmptyTreeException; 12 | /** Inserts a key-value pair and return the entry created. */ 13 | public Entry insert(K key, V value) 14 | throws InvalidKeyException, BoundaryViolationException, InvalidPositionException; 15 | /** Removes and returns an entry with minimum key. */ 16 | public Entry removeMin() 17 | throws EmptyPriorityQueueException, EmptyTreeException, InvalidPositionException, 18 | BoundaryViolationException; 19 | } 20 | -------------------------------------------------------------------------------- /MazeConstruct/src/Vertex.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Vertex object 3 | * stores an element (cell object for maze) 4 | * and index for edge list structure graph 5 | * @author Steven Gerhard 6 | */ 7 | 8 | public class Vertex { 9 | 10 | private Cell element; 11 | private int index; 12 | 13 | 14 | public Vertex(int in, int X, int Y) { 15 | element = new Cell(X,Y); 16 | index = in; 17 | } 18 | 19 | public Cell element() { return element; } 20 | public int index() { return index; } 21 | public void setIndex(int i) { index = i; } 22 | public Cell setCell(int X, int Y) { 23 | Cell temp = element; 24 | element = new Cell(X,Y); 25 | return temp; 26 | } 27 | 28 | 29 | /** For testing purposes. */ 30 | public void print() { 31 | element.print(); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /PuzzleSolve/README.txt: -------------------------------------------------------------------------------- 1 | PuzzleSolve 2 | By Steven Gerhard 3 | 4 | compile src and run PuzzleSolve.class 5 | 6 | Recursively solves summation puzzles by finding integer values for each unique letter. 7 | 8 | Example Inputs: 9 | 10 | pot + pan = bib 11 | dog + cat = pig 12 | boy + girl = baby 13 | -------------------------------------------------------------------------------- /PuzzleSolve/src/Node.java: -------------------------------------------------------------------------------- 1 | // Creates a node class for 2 | // a singly linked list 3 | 4 | public class Node { 5 | private String element; // object this node stores 6 | private Node next; // next node in list 7 | 8 | // Creates a node with null references to its element and next node. 9 | public Node() { 10 | this(null); 11 | } 12 | 13 | // Creates a node with the given element and next node. 14 | public Node(String e) { 15 | element = e; 16 | //next = null; 17 | } 18 | 19 | // returns the object this node stores 20 | public String getElement() { 21 | return element; 22 | } 23 | 24 | // returns the next node in list 25 | public Node getNext() { 26 | return next; 27 | } 28 | 29 | // sets the object being stored 30 | public void setElement(String newElem) { 31 | element = newElem; 32 | } 33 | 34 | // sets the next node 35 | public void setNext(Node newNext) { 36 | next = newNext; 37 | } 38 | 39 | // prints this node 40 | public void printNode(){ 41 | System.out.println(element.toString()); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /PuzzleSolve/src/PuzzleSolve.java: -------------------------------------------------------------------------------- 1 | /* Steven Gerhard 2 | * ID: sjg10009 3 | * PuzzleSolve.java 4 | * CSE 2100 Lab 1 5 | */ 6 | 7 | import java.util.Scanner; 8 | 9 | // solves string summation puzzles 10 | public class PuzzleSolve{ 11 | private SLinkedList _strParts; 12 | private String _userInput,_alphabet; // the original puzzle input by user 13 | private int _k,_numSolutions; 14 | 15 | 16 | // constructor 17 | public PuzzleSolve(String s){ 18 | // To set up the SolvePuzzle parameters: 19 | _userInput = s; // saves unedited puzzle 20 | _strParts = readPuzzle(s); // creates a list, each node one part of puzzle, remove "+,=" 21 | _alphabet = removeDup(_strParts.getList()); // the unique letters of the puzzle 22 | _k = _alphabet.length(); // number of unique letters in puzzle 23 | SLinkedList U = new SLinkedList(); // Creates SList U of ints [0-9] 24 | for(int i = 0; i<10; i++) 25 | U.addFirst(String.valueOf(i)); 26 | SLinkedList S = new SLinkedList(); // SolvePuzzle Parameter 27 | _numSolutions = 0; // used to tell if solution found 28 | System.out.println("Unique Letters in Equation: " + _alphabet); 29 | if(_k > 10 || _k < 1){ 30 | // only have 10 digits to work with 31 | System.out.println("Puzzle Not Solvable For Integer Values 0-9"); 32 | } 33 | else{ 34 | SolvePuzzle(0,S,U); 35 | } 36 | if(_numSolutions == 0){ 37 | System.out.println("No Solutions Exist"); 38 | } 39 | } 40 | 41 | 42 | // Solve Puzzle Method 43 | // enumerates all k length permutations of U 44 | // tests those permutations to check if solution 45 | public void SolvePuzzle(int d, SLinkedList S, SLinkedList U){ 46 | SLinkedList subSet = S; 47 | SLinkedList unUsed = U; 48 | if(d == _k){ 49 | Solution(subSet); 50 | return; 51 | } 52 | for(int i = 0; i < unUsed.getSize(); i++){ 53 | subSet.addFirst(unUsed.getHead()); 54 | unUsed.removeFirst(); 55 | SolvePuzzle(d+1,subSet,unUsed); 56 | unUsed.addLast(subSet.getHead()); 57 | subSet.removeFirst(); 58 | 59 | } 60 | return; 61 | } 62 | 63 | 64 | // returns true 65 | // and prints 66 | // if the integers solve the puzzle 67 | public void Solution(SLinkedList sol){ 68 | 69 | String solution = sol.getList(); 70 | String output = ""; 71 | String result = _userInput; 72 | for(int i = 0; i < _k; i++){ // for 0 to < k 73 | String al = _alphabet.substring(i,i+1); // pick one letter from puzzle 74 | String so = solution.substring(i,i+1); // pick one number from soln 75 | result = result.replaceAll(al,so); // replace all of that letter with number solution 76 | } 77 | result = result.replaceAll("\\s", ""); 78 | 79 | // the rest of this method removes operators from result 80 | // converts to an int array 81 | // adds all elements except last together 82 | // and checks if they equal last 83 | String[] almost = result.split("[\\+=]"); 84 | int[] ans = new int[almost.length]; 85 | for(int i = 0; i < ans.length; i++){ 86 | ans[i] = Integer.parseInt(almost[i]); 87 | } 88 | int total = ans[ans.length-1]; 89 | int sums = 0; 90 | for(int i = 0; i < ans.length - 1;i++){ 91 | sums = sums + ans[i]; 92 | } 93 | if(sums == total){ 94 | if(_numSolutions == 0) 95 | System.out.println("Solution(s) Found:"); 96 | output = ""; 97 | for(int i = 0; i < solution.length(); i++) { 98 | output = output + _alphabet.substring(i,i+1) + "=" + solution.substring(i,i+1) + "; "; 99 | } 100 | System.out.println(output); 101 | _numSolutions++; 102 | } 103 | return; 104 | } 105 | 106 | 107 | // Reads puzzle string from input 108 | // Stores in a LinkedList 109 | public SLinkedList readPuzzle(String s){ 110 | SLinkedList result = new SLinkedList(); 111 | String[] read = s.split("\\s+"); 112 | for(int i=0; i=0; i--){ 137 | reverse = reverse + ans.charAt(i); 138 | } 139 | return reverse; 140 | } 141 | 142 | 143 | // PuzzleSolve.java 144 | public static void main(String[] args){ 145 | Scanner input = new Scanner(System.in); 146 | System.out.println("Enter Puzzle: (String + String = String)"); 147 | System.out.println("(It is possible to add more than two strings)"); 148 | PuzzleSolve puzzle = new PuzzleSolve(input.nextLine()); 149 | input.close(); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /PuzzleSolve/src/SLinkedList.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Singly linked list 3 | */ 4 | 5 | public class SLinkedList { 6 | protected Node head,tail; // head node of list 7 | protected int size; // number of nodes in list 8 | 9 | // Default constructor that creates an empty list 10 | public SLinkedList(){ 11 | head = tail = null; 12 | size = 0; 13 | 14 | } 15 | 16 | // add node to beginning of list 17 | public void addFirst(String s){ 18 | Node link = new Node(s); 19 | if(size==0){ 20 | tail = link; 21 | } 22 | 23 | link.setNext(head); 24 | head = link; 25 | size++; 26 | } 27 | 28 | // add node to end of list 29 | public void addLast(String s){ 30 | Node link = new Node(s); 31 | if(size==0){ 32 | addFirst(s); 33 | } 34 | else{ 35 | link.setNext(null); 36 | tail.setNext(link); 37 | tail = link; 38 | size++; 39 | } 40 | } 41 | 42 | // remove the first node 43 | public void removeFirst(){ 44 | if (head == null){ 45 | System.out.println("List is Empty"); 46 | return; 47 | } 48 | Node t = head; 49 | head = head.getNext(); 50 | t.setNext(null); 51 | size--; 52 | } 53 | 54 | // removes tail node 55 | // can be inefficient but 56 | // puzzle solve uses at most 10 nodes 57 | public void removeLast(){ 58 | Node current = head; 59 | Node mem = null; 60 | do{ 61 | mem = current; 62 | current = current.getNext(); 63 | } 64 | while(current.getNext() != null); 65 | mem.setNext(null); 66 | tail = mem; 67 | size--; 68 | } 69 | 70 | // returns element of head node 71 | public String getHead(){ 72 | return head.getElement(); 73 | } 74 | 75 | // returns the tail element 76 | public String getTail(){ 77 | return tail.getElement(); 78 | } 79 | 80 | // returns the number of nodes 81 | public int getSize(){ 82 | return size; 83 | } 84 | 85 | // returns true if the list is empty 86 | public boolean isEmpty(){ 87 | return head==null; 88 | } 89 | 90 | // turns the entire list into a single string 91 | public String getList(){ 92 | Node current = head; 93 | String result = ""; 94 | while(current != null){ 95 | result = result + String.valueOf(current.getElement()); 96 | current = current.getNext(); 97 | } 98 | return result; 99 | } 100 | 101 | // prints all elements of the list 102 | public void printList(){ 103 | Node current = head; 104 | System.out.println("Elements of List:"); 105 | while(current != null){ 106 | current.printNode(); 107 | current = current.getNext(); 108 | } 109 | } 110 | public static void main(String[] args){ 111 | SLinkedList test = new SLinkedList(); 112 | test.addFirst("1"); 113 | test.addFirst("2"); 114 | test.addFirst("3"); 115 | test.addFirst("4"); 116 | test.addFirst("5"); 117 | test.printList(); 118 | test.removeFirst(); 119 | test.printList(); 120 | System.out.println(test.getHead()); 121 | 122 | } 123 | } 124 | 125 | 126 | -------------------------------------------------------------------------------- /StockTran/README.txt: -------------------------------------------------------------------------------- 1 | StockTran 2 | By Steven Gerhard 3 | 4 | compile src and run StockTran.class 5 | 6 | A standard accounting principle for identifying which shares of a stock were sold in such a case is to use a FIFO protocol - the shares sold are the ones that have been held the longest 7 | 8 | Input Example: 9 | 10 | b 12 50 // buy 12 shares at $50 a share 11 | b 5 10 // buy 5 shares at $10 a share 12 | s 3 75 // sell 3 shares at $75 a share 13 | c // system outputs capital gains => (3*-50)+(3*75) = 75 14 | s 14 10 // sell 14 shares at $10 a share 15 | c // system outputs capital gains => (9*-50)+(5*-10)+(14*10)+75 = -285 16 | s 1 10 // system outputs Invalid Input: Not Enough Shares to Sell 17 | asffe // Bad input, system waits for next line 18 | q // quits the program 19 | -------------------------------------------------------------------------------- /StockTran/src/CircleQueue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Steven Gerhard 3 | * Creates a circle queue 4 | * for use with StockTran.java 5 | */ 6 | 7 | import java.math.BigDecimal; 8 | public class CircleQueue { 9 | static final int MAX_SIZE = 32; 10 | protected Node head,tail; // head points to first filled node 11 | // tail points to last filled node 12 | 13 | 14 | // Creates a list of 32 nodes 15 | // each with index day = [1,32] 16 | // (the index isn't actually used) 17 | // and connects them circularly 18 | 19 | public CircleQueue(){ 20 | Node current = new Node(); 21 | head = tail = current; 22 | current.setDay(1); 23 | for(int i = 2; i <= MAX_SIZE; i++ ){ 24 | Node next = new Node(); 25 | next.setDay(i); 26 | current.setNext(next); 27 | current = next; 28 | } 29 | current.setNext(head); 30 | } 31 | 32 | // returns the number of filled nodes 33 | public int size(){ 34 | return(tail.getDay() - head.getDay()); 35 | } 36 | 37 | // returns true if empty 38 | public boolean isEmpty(){ 39 | return(tail.getDay() == head.getDay()); 40 | } 41 | 42 | // returns head node 43 | public Node front(){ 44 | if(isEmpty()){ 45 | throw new EmptyQueueException("Queue is empty"); 46 | } 47 | Node temp = head; 48 | return temp; 49 | } 50 | 51 | // adds elements to end of queue 52 | public void enqueue(BigDecimal A, BigDecimal P){ 53 | if(size() == 31){ 54 | throw new FullQueueException("Queue is Full"); 55 | } 56 | BigDecimal amt = A; 57 | BigDecimal price = P; 58 | tail.setAmt(amt); 59 | tail.setPrice(price); 60 | tail = tail.next(); 61 | } 62 | 63 | // removes front of queue 64 | public Node dequeue(){ 65 | if(isEmpty()){ 66 | throw new EmptyQueueException("Queue is empty"); 67 | } 68 | Node temp = head; 69 | head.clearNode(); 70 | head = head.next(); 71 | return temp; 72 | } 73 | 74 | // this allows a specific amt subtracted 75 | // from head node without dequeuing 76 | public void sellShares(BigDecimal amt){ 77 | head.setAmt(head.getAmt().subtract(amt)); 78 | } 79 | 80 | // Prints all the nodes of the queue 81 | public void printList(){ 82 | Node current = head; 83 | System.out.println("Elements of List:"); 84 | for( int i = 0; i < size(); i++) { 85 | current.printNode(); 86 | current = current.next(); 87 | } 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /StockTran/src/EmptyQueueException.java: -------------------------------------------------------------------------------- 1 | 2 | public class EmptyQueueException extends RuntimeException { 3 | public EmptyQueueException(String err){ 4 | super(err); 5 | } 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /StockTran/src/FullQueueException.java: -------------------------------------------------------------------------------- 1 | public class FullQueueException extends RuntimeException{ 2 | public FullQueueException(String err){ 3 | super(err); 4 | } 5 | } -------------------------------------------------------------------------------- /StockTran/src/Node.java: -------------------------------------------------------------------------------- 1 | /* Steven Gerhard 2 | * Node Class 3 | * for StockTran 4 | */ 5 | 6 | import java.math.BigDecimal; 7 | 8 | public class Node { 9 | private BigDecimal price, amt; 10 | private int day; 11 | private Node next; 12 | 13 | public Node(){ 14 | next = null; 15 | price = null; 16 | amt = null; 17 | 18 | } 19 | 20 | // Accessor Methods 21 | public BigDecimal getPrice(){ 22 | return price; 23 | } 24 | 25 | public BigDecimal getAmt(){ 26 | return amt; 27 | } 28 | 29 | public int getDay(){ 30 | return day; 31 | } 32 | 33 | public Node next(){ 34 | return next; 35 | } 36 | 37 | // Mutator methods 38 | public void clearNode(){ 39 | price = null; 40 | amt = null; 41 | } 42 | 43 | public void setPrice(BigDecimal P){ 44 | price = P; 45 | } 46 | 47 | public void setAmt(BigDecimal A){ 48 | amt = A; 49 | } 50 | 51 | public void setDay(int D){ 52 | day = D; 53 | } 54 | 55 | public void setNext(Node N){ 56 | next = N; 57 | } 58 | 59 | public void printNode(){ 60 | System.out.println("Amt: " + String.valueOf(amt)+" Price: " + String.valueOf(price)); 61 | 62 | } 63 | 64 | public void printDay(){ 65 | System.out.println(day); 66 | } 67 | } -------------------------------------------------------------------------------- /StockTran/src/StockTran.java: -------------------------------------------------------------------------------- 1 | /** @author Steven Gerhard 2 | * ID: sjg10009 3 | * Stock Buy/Sell Simulator 4 | * Using First In First Out 5 | * to determine capital gains/losses 6 | * Implemented in java I/O console 7 | */ 8 | 9 | import java.util.Scanner; 10 | import java.math.BigDecimal; 11 | 12 | public class StockTran { 13 | private BigDecimal cg; 14 | private CircleQueue Q; 15 | private int numShares; 16 | 17 | public StockTran(){ 18 | Q = new CircleQueue(); 19 | cg = new BigDecimal("0"); // capital gains 20 | numShares = 0; // total number of shares 21 | } 22 | 23 | // buy shares 24 | public void buy(BigDecimal amt, BigDecimal price){ 25 | Q.enqueue(amt,price); 26 | numShares = numShares + amt.intValue(); 27 | } 28 | 29 | // sell shares 30 | public void sell(BigDecimal A, BigDecimal P){ 31 | BigDecimal amt = A; 32 | BigDecimal price = P; 33 | 34 | if(A.compareTo( new BigDecimal(numShares)) > 0){ 35 | throw new EmptyQueueException("not enough shares to sell"); 36 | } 37 | // if the amt of shares in head node 38 | // is less than amt being sold 39 | // compute the capital gains and dequeue 40 | while(Q.front().getAmt().compareTo(amt) < 0){ 41 | BigDecimal sp = price.subtract(Q.head.getPrice()); 42 | cg = cg.add(Q.head.getAmt().multiply(sp)); 43 | amt = amt.subtract(Q.head.getAmt()); 44 | Q.dequeue(); 45 | } 46 | 47 | BigDecimal spp = price.subtract(Q.head.getPrice()); 48 | cg = cg.add(amt.multiply(spp)); 49 | Q.sellShares(amt); 50 | numShares = numShares - A.intValue(); 51 | 52 | 53 | } 54 | 55 | // returns the capital gains 56 | public String gains(){ 57 | return String.valueOf(cg); 58 | } 59 | 60 | public static void main(String[] args){ 61 | System.out.println("enter b # #, s # #, or c for capital gains"); 62 | System.out.println("press q to quit"); 63 | StockTran trade = new StockTran(); 64 | boolean run = true; 65 | String in = ""; 66 | BigDecimal amt; 67 | BigDecimal price; 68 | Scanner input = new Scanner(System.in); 69 | while(run){ 70 | if(input.hasNext()){ 71 | in = input.next(); 72 | 73 | if(in.equals("q")){ 74 | run = false; 75 | } 76 | else if(in.equals("s") && input.hasNextBigDecimal()){ 77 | amt = input.nextBigDecimal(); 78 | if(input.hasNextBigDecimal()) { 79 | price = input.nextBigDecimal(); 80 | trade.sell(amt, price); 81 | } 82 | amt = null; 83 | price = null; 84 | } 85 | else if(in.equals("b") && input.hasNextBigDecimal()){ 86 | amt = input.nextBigDecimal(); 87 | if(input.hasNextBigDecimal()) { 88 | price = input.nextBigDecimal(); 89 | trade.buy(amt, price); 90 | } 91 | amt = null; 92 | price = null; 93 | } 94 | else if(in.equals("c")){ 95 | System.out.println(trade.gains()); 96 | } 97 | } 98 | } 99 | input.close(); 100 | } 101 | } 102 | --------------------------------------------------------------------------------