summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexander Pickering <alexandermpickering@gmail.com>2017-02-06 11:41:36 -0500
committerAlexander Pickering <alexandermpickering@gmail.com>2017-02-06 11:41:36 -0500
commit89cdf3efb49335e7c07a68a5a64657eeec2288a6 (patch)
treecdc0fd8165e65b1637fa54cac11c932acefc8a89
downloadcoe0445-89cdf3efb49335e7c07a68a5a64657eeec2288a6.tar.gz
coe0445-89cdf3efb49335e7c07a68a5a64657eeec2288a6.tar.bz2
coe0445-89cdf3efb49335e7c07a68a5a64657eeec2288a6.zip
Inital commitHEADmaster
-rw-r--r--labs/lab01_pair/.Pair.java.swpbin0 -> 12288 bytes
-rw-r--r--labs/lab01_pair/GraphComponent.java139
-rw-r--r--labs/lab01_pair/Pair.java83
-rw-r--r--labs/lab01_pair/PairInterface.java55
-rw-r--r--labs/lab01_pair/PairTester.java286
-rw-r--r--labs/lab01_pair/ParabolaFrame.java36
-rw-r--r--labs/lab01_pair/lab01_pair.pdfbin0 -> 133803 bytes
-rw-r--r--labs/lab02_simpleRGB/ImageViewer.java85
-rw-r--r--labs/lab02_simpleRGB/RGBComponent.java46
-rw-r--r--labs/lab02_simpleRGB/SimpleRGB.java190
-rw-r--r--labs/lab02_simpleRGB/SimpleRGBTester.java228
-rw-r--r--labs/lab02_simpleRGB/lab02_simpleRGB.pdfbin0 -> 358046 bytes
-rw-r--r--labs/lab02_simpleRGB/pgh_640x480.jpgbin0 -> 306595 bytes
-rw-r--r--labs/lab03_dll/DLinkedList.java190
-rw-r--r--labs/lab03_dll/DLinkedListTester.java168
-rw-r--r--labs/lab03_dll/lab03_dll.pdfbin0 -> 93176 bytes
-rw-r--r--labs/lab04_recurionll/RecursionLLTester.java232
-rw-r--r--labs/lab04_recurionll/RecursionLinkedList.java164
-rw-r--r--labs/lab04_recurionll/lab04_rll.pdfbin0 -> 74989 bytes
-rw-r--r--labs/lab05_permutation/Permutation.java51
-rw-r--r--labs/lab05_permutation/PermutationTester.java129
-rw-r--r--labs/lab05_permutation/lab05_permutation.pdfbin0 -> 76573 bytes
-rw-r--r--labs/lab07_tohSolver/THComponent.java113
-rw-r--r--labs/lab07_tohSolver/THFrame.java84
-rw-r--r--labs/lab07_tohSolver/THSolverFrame.java70
-rw-r--r--labs/lab07_tohSolver/TowerOfHanoi.java170
-rw-r--r--labs/lab07_tohSolver/lab07_solveTower.pdfbin0 -> 69300 bytes
-rw-r--r--labs/lab08_gnome_sort/SortingFrame.java106
-rw-r--r--labs/lab08_gnome_sort/VisualSortingComponent.java78
-rw-r--r--labs/lab08_gnome_sort/lab08_gnome_sort.pdfbin0 -> 101250 bytes
-rw-r--r--labs/lab09_iterator/Iterator.java7
-rw-r--r--labs/lab09_iterator/SListIterator.java88
-rw-r--r--labs/lab09_iterator/SListIteratorTester.java83
-rw-r--r--labs/lab09_iterator/lab09_iterator.pdfbin0 -> 60451 bytes
-rw-r--r--labs/lab10_tree/BinaryNode.java100
-rw-r--r--labs/lab10_tree/BinaryNodeInterface.java15
-rw-r--r--labs/lab10_tree/ShowPath.java293
-rw-r--r--labs/lab10_tree/SimpleQueue.java72
-rw-r--r--labs/lab10_tree/lab10_tree.pdfbin0 -> 61048 bytes
-rw-r--r--labs/lab6_toh/THComponent.java113
-rw-r--r--labs/lab6_toh/THFrame.java84
-rw-r--r--labs/lab6_toh/TowerOfHanoi.java164
-rw-r--r--labs/lab6_toh/TowersTester.java185
-rw-r--r--labs/lab6_toh/lab06_towers_of_hanoi.pdfbin0 -> 130942 bytes
-rw-r--r--projects/project1_frequencyBag/CharacterFrequency.java34
-rw-r--r--projects/project1_frequencyBag/FNode.java0
-rw-r--r--projects/project1_frequencyBag/FrequencyBag.java168
-rw-r--r--projects/project1_frequencyBag/FrequencyBagTester.java531
-rw-r--r--projects/project1_frequencyBag/FrequencyFrame.java72
-rw-r--r--projects/project1_frequencyBag/FrequencyGraphComponent.java71
-rw-r--r--projects/project1_frequencyBag/RandomDistribution.java77
-rw-r--r--projects/project1_frequencyBag/letter1.txt16
-rw-r--r--projects/project1_frequencyBag/project1_frequencyBag.pdfbin0 -> 165759 bytes
-rw-r--r--projects/project2_LInfiniteInteger/InfiniteInteger y was constructed using the following statement76
-rw-r--r--projects/project2_LInfiniteInteger/InfiniteInteger.pdfbin0 -> 123056 bytes
-rw-r--r--projects/project2_LInfiniteInteger/InfiniteIntegerCalculator.java14
-rw-r--r--projects/project2_LInfiniteInteger/InfiniteIntegerCalculatorFrame.java495
-rw-r--r--projects/project2_LInfiniteInteger/InfiniteIntegerInterface.java59
-rw-r--r--projects/project2_LInfiniteInteger/LInfiniteInteger.java562
-rw-r--r--projects/project2_LInfiniteInteger/LInfiniteIntegerTester.java1136
-rw-r--r--projects/project2_LInfiniteInteger/LStack.java66
-rw-r--r--projects/project2_LInfiniteInteger/StackInterface.java9
-rw-r--r--projects/project3_kenken/Cell.java30
-rw-r--r--projects/project3_kenken/KCage.java200
-rw-r--r--projects/project3_kenken/KPuzzle1
-rw-r--r--projects/project3_kenken/KPuzzle.java264
-rw-r--r--projects/project3_kenken/Operator.java4
-rw-r--r--projects/project3_kenken/Solver.java173
-rw-r--r--projects/project3_kenken/images/3x3_1.jpgbin0 -> 13165 bytes
-rw-r--r--projects/project3_kenken/images/3x3_1_solution.jpgbin0 -> 21147 bytes
-rw-r--r--projects/project3_kenken/images/3x3_2.jpgbin0 -> 12569 bytes
-rw-r--r--projects/project3_kenken/images/3x3_2_solution.jpgbin0 -> 21097 bytes
-rw-r--r--projects/project3_kenken/images/3x3_3.jpgbin0 -> 12763 bytes
-rw-r--r--projects/project3_kenken/images/3x3_3_solution.jpgbin0 -> 21280 bytes
-rw-r--r--projects/project3_kenken/images/4x4_1.jpgbin0 -> 18011 bytes
-rw-r--r--projects/project3_kenken/images/4x4_1_solution.jpgbin0 -> 32651 bytes
-rw-r--r--projects/project3_kenken/images/4x4_2.jpgbin0 -> 17740 bytes
-rw-r--r--projects/project3_kenken/images/4x4_2_solution.jpgbin0 -> 33116 bytes
-rw-r--r--projects/project3_kenken/images/4x4_3.jpgbin0 -> 18563 bytes
-rw-r--r--projects/project3_kenken/images/4x4_3_solution.jpgbin0 -> 32220 bytes
-rw-r--r--projects/project3_kenken/images/5x5_1.jpgbin0 -> 24117 bytes
-rw-r--r--projects/project3_kenken/images/5x5_1_solution.jpgbin0 -> 48101 bytes
-rw-r--r--projects/project3_kenken/images/5x5_2.jpgbin0 -> 23828 bytes
-rw-r--r--projects/project3_kenken/images/5x5_2_solution.jpgbin0 -> 47516 bytes
-rw-r--r--projects/project3_kenken/images/5x5_3.jpgbin0 -> 23998 bytes
-rw-r--r--projects/project3_kenken/images/5x5_3_solution.jpgbin0 -> 47475 bytes
-rw-r--r--projects/project3_kenken/images/6x6_1.jpgbin0 -> 31749 bytes
-rw-r--r--projects/project3_kenken/images/6x6_1_solution.jpgbin0 -> 65768 bytes
-rw-r--r--projects/project3_kenken/images/6x6_2.jpgbin0 -> 30975 bytes
-rw-r--r--projects/project3_kenken/images/6x6_2_solution.jpgbin0 -> 64968 bytes
-rw-r--r--projects/project3_kenken/images/7x7_1.jpgbin0 -> 39619 bytes
-rw-r--r--projects/project3_kenken/images/7x7_1_solution.jpgbin0 -> 86086 bytes
-rw-r--r--projects/project3_kenken/images/7x7_2.jpgbin0 -> 39906 bytes
-rw-r--r--projects/project3_kenken/images/7x7_2_solution.jpgbin0 -> 86140 bytes
-rw-r--r--projects/project3_kenken/images/8x8_1.jpgbin0 -> 49678 bytes
-rw-r--r--projects/project3_kenken/images/8x8_1_solution.jpgbin0 -> 109224 bytes
-rw-r--r--projects/project3_kenken/images/8x8_2.jpgbin0 -> 50034 bytes
-rw-r--r--projects/project3_kenken/images/8x8_2_solution.jpgbin0 -> 111310 bytes
-rw-r--r--projects/project3_kenken/images/9x9_1.jpgbin0 -> 60607 bytes
-rw-r--r--projects/project3_kenken/images/9x9_1_solution.jpgbin0 -> 140758 bytes
-rw-r--r--projects/project3_kenken/images/9x9_2.jpgbin0 -> 61128 bytes
-rw-r--r--projects/project3_kenken/images/9x9_2_solution.jpgbin0 -> 141084 bytes
-rw-r--r--projects/project3_kenken/images/9x9_3.jpgbin0 -> 59179 bytes
-rw-r--r--projects/project3_kenken/images/9x9_3_solution.jpgbin0 -> 139468 bytes
-rw-r--r--projects/project3_kenken/kenkensolver.java14
-rw-r--r--projects/project3_kenken/project3_kenken.pdfbin0 -> 406310 bytes
-rw-r--r--projects/project3_kenken/puzzle_files/3x3_1.txt17
-rw-r--r--projects/project3_kenken/puzzle_files/3x3_2.txt17
-rw-r--r--projects/project3_kenken/puzzle_files/3x3_3.txt17
-rw-r--r--projects/project3_kenken/puzzle_files/4x4_1.txt27
-rw-r--r--projects/project3_kenken/puzzle_files/4x4_2.txt27
-rw-r--r--projects/project3_kenken/puzzle_files/4x4_3.txt28
-rw-r--r--projects/project3_kenken/puzzle_files/5x5_1.txt41
-rw-r--r--projects/project3_kenken/puzzle_files/5x5_2.txt37
-rw-r--r--projects/project3_kenken/puzzle_files/5x5_3.txt39
-rw-r--r--projects/project3_kenken/puzzle_files/6x6_1.txt56
-rw-r--r--projects/project3_kenken/puzzle_files/6x6_2.txt55
-rw-r--r--projects/project3_kenken/puzzle_files/7x7_1.txt73
-rw-r--r--projects/project3_kenken/puzzle_files/7x7_2.txt74
-rw-r--r--projects/project3_kenken/puzzle_files/8x8_1.txt92
-rw-r--r--projects/project3_kenken/puzzle_files/8x8_2.txt92
-rw-r--r--projects/project3_kenken/puzzle_files/9x9_1.txt119
-rw-r--r--projects/project3_kenken/puzzle_files/9x9_2.txt119
-rw-r--r--projects/project3_kenken/puzzle_files/9x9_3.txt118
-rw-r--r--projects/project3_kenken/stab2/3x3_1.txt17
-rw-r--r--projects/project3_kenken/stab2/3x3_2.txt17
-rw-r--r--projects/project3_kenken/stab2/3x3_3.txt17
-rw-r--r--projects/project3_kenken/stab2/4x4_1.txt27
-rw-r--r--projects/project3_kenken/stab2/4x4_2.txt27
-rw-r--r--projects/project3_kenken/stab2/4x4_3.txt28
-rw-r--r--projects/project3_kenken/stab2/5x5_1.txt41
-rw-r--r--projects/project3_kenken/stab2/5x5_2.txt37
-rw-r--r--projects/project3_kenken/stab2/5x5_3.txt39
-rw-r--r--projects/project3_kenken/stab2/6x6_1.txt56
-rw-r--r--projects/project3_kenken/stab2/6x6_2.txt55
-rw-r--r--projects/project3_kenken/stab2/7x7_1.txt73
-rw-r--r--projects/project3_kenken/stab2/7x7_2.txt74
-rw-r--r--projects/project3_kenken/stab2/8x8_1.txt92
-rw-r--r--projects/project3_kenken/stab2/8x8_2.txt92
-rw-r--r--projects/project3_kenken/stab2/9x9_1.txt119
-rw-r--r--projects/project3_kenken/stab2/9x9_2.txt119
-rw-r--r--projects/project3_kenken/stab2/9x9_3.txt118
-rw-r--r--projects/project3_kenken/stab2/Constraint.java12
-rw-r--r--projects/project3_kenken/stab2/KNode.java18
-rw-r--r--projects/project3_kenken/stab2/KStack.java54
-rw-r--r--projects/project3_kenken/stab2/Position.java11
-rw-r--r--projects/project3_kenken/stab2/Solver.java865
-rw-r--r--projects/project3_kenken/stab2/kenkensolver.java141
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/3x3_1.txt17
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/3x3_2.txt17
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/3x3_3.txt17
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/Constraint.java12
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/KNode.java18
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/KStack.java54
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/Position.java11
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/Solver.java853
-rw-r--r--projects/project3_kenken/stab2/working3x3_1/kenkensolver.java159
-rw-r--r--projects/project4_huffman_tree/BinaryNode.java100
-rw-r--r--projects/project4_huffman_tree/BinaryNodeInterface.java15
-rw-r--r--projects/project4_huffman_tree/CompressDecompress.java189
-rw-r--r--projects/project4_huffman_tree/CompressDecompressGUI.java217
-rw-r--r--projects/project4_huffman_tree/CompressDecompressTester.java159
-rw-r--r--projects/project4_huffman_tree/HuffmanTree.java127
-rw-r--r--projects/project4_huffman_tree/MinHeap.java132
-rw-r--r--projects/project4_huffman_tree/MinHeapInterface.java11
-rw-r--r--projects/project4_huffman_tree/project4_huffman_tree.pdfbin0 -> 220769 bytes
166 files changed, 13284 insertions, 0 deletions
diff --git a/labs/lab01_pair/.Pair.java.swp b/labs/lab01_pair/.Pair.java.swp
new file mode 100644
index 0000000..6cd3b15
--- /dev/null
+++ b/labs/lab01_pair/.Pair.java.swp
Binary files differ
diff --git a/labs/lab01_pair/GraphComponent.java b/labs/lab01_pair/GraphComponent.java
new file mode 100644
index 0000000..089b76a
--- /dev/null
+++ b/labs/lab01_pair/GraphComponent.java
@@ -0,0 +1,139 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Line2D;
+import java.util.ArrayList;
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class GraphComponent extends JComponent
+{
+ private int leftMargin = 10;
+ private int rightMargin = 10;
+ private int topMargin = 10;
+ private int bottomMargin = 10;
+ private double largest;
+ private double largestX;
+ private double smallestX;
+ private double largestY;
+ private double smallestY;
+ private int numData;
+ private int width;
+ private int height;
+ private ArrayList<PairInterface<Double,Double>> data;
+
+ public GraphComponent(ArrayList<PairInterface<Double,Double>> aData)
+ {
+ data = aData;
+ numData = data.size();
+ PairInterface<Double,Double> tempData = data.get(0);
+
+ largestX = tempData.fst();
+ smallestX = largestX;
+ largestY = tempData.snd();
+ smallestY = largestY;
+
+ for(int i = 1; i < numData; i++)
+ {
+ tempData = data.get(i);
+
+ if(largestX < tempData.fst())
+ {
+ largestX = tempData.fst();
+ }
+
+ if(smallestX > tempData.fst())
+ {
+ smallestX = tempData.fst();
+ }
+
+ if(largestY < tempData.snd())
+ {
+ largestY = tempData.snd();
+ }
+
+ if(smallestY > tempData.snd())
+ {
+ smallestY = tempData.snd();
+ }
+ }
+
+ if(Math.abs(largestX) < Math.abs(smallestX))
+ {
+ largestX = Math.abs(smallestX);
+ }
+ else
+ {
+ largestX = Math.abs(largestX);
+ }
+
+ if(Math.abs(largestY) < Math.abs(smallestY))
+ {
+ largestY = Math.abs(smallestY);
+ }
+ else
+ {
+ largestY = Math.abs(largestY);
+ }
+
+ if(largestX > largestY)
+ {
+ largest = largestX;
+ }
+ else
+ {
+ largest = largestY;
+ }
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ width = this.getWidth();
+ height = this.getHeight();
+
+
+
+ Line2D.Double line = new Line2D.Double(0,0,0,0);
+
+ // Draw Axis;
+
+ g2.setColor(Color.BLACK);
+
+ line.setLine(getX(0),getY(0),getX(-largest),getY(0));
+ g2.draw(line);
+ line.setLine(getX(0),getY(0),getX(0),getY(largest));
+ g2.draw(line);
+ line.setLine(getX(0),getY(0),getX(largest),getY(0));
+ g2.draw(line);
+ line.setLine(getX(0),getY(0),getX(0),getY(-largest));
+ g2.draw(line);
+
+ // Draw frequency the graph
+
+ g2.setColor(Color.GREEN);
+
+ for(int i = 0; i < numData - 1; i++)
+ {
+ line.setLine(getX(data.get(i).fst()), getY(data.get(i).snd()), getX(data.get(i + 1).fst()), getY(data.get(i + 1).snd()));
+ g2.draw(line);
+ }
+ }
+
+ public int getX(double aValue)
+ {
+ int numberOfPixels = width - (leftMargin + rightMargin);
+ double range = largest + largest;
+ double deltaWidth = numberOfPixels / range;
+ return (int) ((aValue + largest) * deltaWidth) + leftMargin;
+ }
+
+ public int getY(double aValue)
+ {
+ int numberOfPixels = height - (topMargin + bottomMargin);
+ double range = largest + largest;
+ double deltaWidth = numberOfPixels / range;
+ return (int) ((-aValue + largest) * deltaWidth) + topMargin;
+ }
+}
diff --git a/labs/lab01_pair/Pair.java b/labs/lab01_pair/Pair.java
new file mode 100644
index 0000000..ef49c76
--- /dev/null
+++ b/labs/lab01_pair/Pair.java
@@ -0,0 +1,83 @@
+
+public class Pair<T1,T2> implements PairInterface<T1,T2>
+{
+ // TO DO: Instance Variables
+ T1 one;
+ T2 two;
+
+ public Pair(T1 aFirst, T2 aSecond)
+ {
+ one = aFirst;
+ two = aSecond;
+ }
+
+ /**
+ * Gets the first element of this pair.
+ * @return the first element of this pair.
+ */
+ public T1 fst()
+ {
+ return one;
+ }
+
+ /**
+ * Gets the second element of this pair.
+ * @return the second element of this pair.
+ */
+ public T2 snd()
+ {
+ return two;
+ }
+
+ /**
+ * Sets the first element to aFirst.
+ * @param aFirst the new first element
+ */
+ public void setFst(T1 aFirst)
+ {
+ one = aFirst;
+ }
+
+ /**
+ * Sets the second element to aSecond.
+ * @param aSecond the new second element
+ */
+ public void setSnd(T2 aSecond)
+ {
+ two = aSecond;
+ }
+
+ /**
+ * Checks whether two pairs are equal. Note that the pair
+ * (a,b) is equal to the pair (x,y) if and only if a is
+ * equal to x and b is equal to y.
+ * @return true if this pair is equal to aPair. Otherwise
+ * return false.
+ */
+ public boolean equals(Object otherObject)
+ {
+ if(otherObject == null)
+ {
+ return false;
+ }
+
+ if(getClass() != otherObject.getClass())
+ {
+ return false;
+ }
+ Pair pairObject = (Pair) otherObject;
+ return one.equals(pairObject.fst()) && two.equals(pairObject.snd());
+ }
+
+ /**
+ * Generates a string representing this pair. Note that
+ * the String representing the pair (x,y) is "(x,y)". There
+ * is no whitespace unless x or y or both contain whitespace
+ * themselves.
+ * @return a string representing this pair.
+ */
+ public String toString()
+ {
+ return "(" + one.toString() + "," + two.toString() + ")";
+ }
+}
diff --git a/labs/lab01_pair/PairInterface.java b/labs/lab01_pair/PairInterface.java
new file mode 100644
index 0000000..b3d78fa
--- /dev/null
+++ b/labs/lab01_pair/PairInterface.java
@@ -0,0 +1,55 @@
+
+public interface PairInterface<T1,T2>
+{
+ /**
+ * Gets the first element of this pair.
+ * @return the first element of this pair.
+ */
+ public T1 fst();
+
+ /**
+ * Gets the second element of this pair.
+ * @return the second element of this pair.
+ */
+ public T2 snd();
+
+ /**
+ * Sets the first element to aFirst.
+ * @param aFirst the new first element
+ */
+ public void setFst(T1 aFirst);
+
+ /**
+ * Sets the second element to aSecond.
+ * @param aSecond the new second element
+ */
+ public void setSnd(T2 aSecond);
+
+ /**
+ * Checks whether two pairs are equal. Note that the pair
+ * (a,b) is equal to the pair (x,y) if and only if a is
+ * equal to x and b is equal to y.
+ *
+ * Note that if you forget to implement this method, your
+ * compiler will not complain since your class inherits this
+ * method from the class Object.
+ *
+ * @return true if this pair is equal to aPair. Otherwise
+ * return false.
+ */
+ public boolean equals(Object otherObject);
+
+ /**
+ * Generates a string representing this pair. Note that
+ * the String representing the pair (x,y) is "(x,y)". There
+ * is no whitespace unless x or y or both contain whitespace
+ * themselves.
+ *
+ * Note that if you forget to implement this method, your
+ * compiler will not complain since your class inherits this
+ * method from the class Object.
+ *
+ * @return a string representing this pair.
+ */
+ public String toString();
+}
diff --git a/labs/lab01_pair/PairTester.java b/labs/lab01_pair/PairTester.java
new file mode 100644
index 0000000..a1d3d50
--- /dev/null
+++ b/labs/lab01_pair/PairTester.java
@@ -0,0 +1,286 @@
+import java.util.Random;
+
+public class PairTester
+{
+ public static void main(String[] args)
+ {
+ int point = 0;
+ Random rand = new Random();
+
+ // Test a pair of string and integer
+
+ System.out.print("Testing Pair<String,Integer>: ");
+
+ int l1 = rand.nextInt(10) + 10;
+ String s1 = randomString(l1);
+ PairInterface<String,Integer> p1 = new Pair<String,Integer>(s1,l1);
+
+ if(checkFromToString("(" + s1 + "," + l1 + ")", p1.toString()))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Test a pair of integer and string
+
+ System.out.print("Testing Pair<Integer,String>: ");
+ int l2 = rand.nextInt(10) + 10;
+ String s2 = randomString(l2);
+ PairInterface<Integer,String> p2 = new Pair<Integer,String>(l2,s2);
+ if(checkFromToString("(" + l2 + "," + s2 + ")", p2.toString()))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Test a pair of String and pair
+
+ System.out.print("Testing Pair<String,Pair<Integer,String>>: ");
+ int l3_1 = rand.nextInt(10) + 10;
+ int l3_2 = rand.nextInt(10) + 10;
+ String s3_1 = randomString(l3_1);
+ String s3_2 = randomString(l3_2);
+ PairInterface<Integer,String> p3_1 = new Pair<Integer,String>(l3_1 + l3_2, s3_1);
+ PairInterface<String, PairInterface<Integer,String>> p3_2 = new Pair<String, PairInterface<Integer,String>>(s3_2, p3_1);
+ if(checkFromToString("(" + s3_2 + ",(" + (l3_1 + l3_2) + "," + s3_1 + "))", p3_2.toString()))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Test a pair of pair and Integer
+
+ System.out.print("Testing Pair<String,Pair<Integer,String>>: ");
+ int l4_1 = rand.nextInt(10) + 10;
+ int l4_2 = rand.nextInt(10) + 10;
+ String s4 = randomString(l4_1 + l4_2);
+ PairInterface<String,Integer> p4_1 = new Pair<String,Integer>(s4,l4_1);
+ Pair<Integer, PairInterface<String,Integer>> p4_2 = new Pair<Integer, PairInterface<String,Integer>>(l4_2, p4_1);
+ if(checkFromToString("(" + l4_2 + ",(" + s4 + "," + l4_1 + "))", p4_2.toString()))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Test 5-tuple
+
+ System.out.print("Testing 5-tuple (e.g., (1,(2,(3,(4,5))))): ");
+ int[] l5 = new int[5];
+ for(int i = 0; i < 5; i++)
+ {
+ l5[i] = rand.nextInt(10) + 10;
+ }
+ String s5 = "(" + l5[0] + ",(" + l5[1] + ",(" + l5[2] + ",(" + l5[3] + "," + l5[4] + "))))";
+ PairInterface<Integer,Integer> p5_1 = new Pair<Integer,Integer>(l5[3],l5[4]);
+ PairInterface<Integer,PairInterface<Integer,Integer>> p5_2 = new Pair<Integer,PairInterface<Integer,Integer>>(l5[2],p5_1);
+ PairInterface<Integer,PairInterface<Integer,PairInterface<Integer,Integer>>> p5_3 =
+ new Pair<Integer,PairInterface<Integer,PairInterface<Integer,Integer>>>(l5[1],p5_2);
+ PairInterface<Integer,PairInterface<Integer,PairInterface<Integer,PairInterface<Integer,Integer>>>> p5_4 =
+ new Pair<Integer,PairInterface<Integer,PairInterface<Integer,PairInterface<Integer,Integer>>>>(l5[0],p5_3);
+ if(checkFromToString(s5, p5_4.toString()))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ if(point != 5)
+ {
+ System.out.println("This test class will use variables generated in");
+ System.out.println("previous tests. Your class Pair fails one or more");
+ System.out.println("test(s). This test class will terminated. Fix");
+ System.out.println("your class Pair first and run the test class again.");
+ System.out.println("Your current point is " + point + ".\n");
+ return;
+ }
+
+ // Testing the method equals()
+
+ System.out.println("Testing the method equals()");
+
+ PairInterface<String,Integer> p6 = new Pair<String,Integer>(s1,l1);
+
+ System.out.print("Test whether " + p1 + " is equals to " + p6 + ": ");
+ if(!p1.equals(p6))
+ {
+ System.out.println("FAIL");
+ System.out.println("The pair " + p1 + " and the pair " + p6 + " are equal.");
+ System.out.println("But your method equals() returned false.");
+ System.out.println("Fix your method equals() first and run the test class again.");
+ System.out.println("Your current point is " + point + ".\n");
+ return;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ PairInterface<String,Integer> p6_2 = new Pair<String,Integer>(s1.substring(1,s1.length()), l1);
+ System.out.print("Test whether " + p1 + " is equals to " + p6_2 + ": ");
+ if(p1.equals(p6_2))
+ {
+ System.out.println("FAIL");
+ System.out.println("The pair " + p1 + " and the pair " + p6_2 + " are not equal.");
+ System.out.println("But your method equals() returned true.");
+ System.out.println("Fix your method equals() first and run the test class again.");
+ System.out.println("Your current point is " + point + ".\n");
+ return;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ PairInterface<String,Integer> p6_3 = new Pair<String,Integer>(s1, l1 + 1);
+ System.out.print("Test whether " + p1 + " is equals to " + p6_3 + ": ");
+ if(p1.equals(p6_3))
+ {
+ System.out.println("FAIL");
+ System.out.println("The pair " + p1 + " and the pair " + p6_3 + " are not equal.");
+ System.out.println("But your method equals() returned true.");
+ System.out.println("Fix your method equals() first and run the test class again.");
+ System.out.println("Your current point is " + point + ".\n");
+ return;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ point++;
+ System.out.println("Your current point is " + point + ".\n");
+
+
+
+ System.out.print("Testing the method equals() (x,(y,z)) = (x,(y,z)): ");
+ PairInterface<Integer,String> p7_1 = new Pair<Integer,String>(l3_1 + l3_2, s3_1);
+ Pair<String, PairInterface<Integer,String>> p7_2 = new Pair<String, PairInterface<Integer,String>>(s3_2, p7_1);
+ if(!p3_2.equals(p7_2))
+ {
+ System.out.println("FAIL");
+ System.out.println("The pair " + p3_2 + " and the pair " + p7_2 + " are equal.");
+ System.out.println("But your method equals() returned false.");
+ System.out.println("Fix your method equals() first and run the test class again.");
+ System.out.println("Your current point is " + point + ".\n");
+ return;
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Testing the method fst()
+
+ System.out.print("Testing the method fst(): ");
+ if(!s1.equals(p1.fst()))
+ {
+ System.out.println("FAIL");
+ System.out.println("First element of the pair " + p1 + " is " + s1 + ".");
+ System.out.println("But the method fst() of your class returned " + p1.fst() + ".\n");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Testing the method snd()
+
+ System.out.print("Testing the method snd(): ");
+ if(!s2.equals(p2.snd()))
+ {
+ System.out.println("FAIL");
+ System.out.println("Second element of the pair " + p2 + " is " + s2 + ".");
+ System.out.println("But the method snd() of your class returned " + p2.fst() + ".\n");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Test setFst() and setSnd()
+
+ System.out.print("Testing the methods setFst() and setSnd(): ");
+ PairInterface<String,Integer> p10_1 = new Pair<String,Integer>("Hello",123);
+ PairInterface<String,Integer> p10_2 = new Pair<String,Integer>("How are you?",54321);
+
+ p10_1.setFst("How are you?");
+ p10_1.setSnd(54321);
+
+ if(!p10_1.equals(p10_2))
+ {
+ System.out.println("FAIL");
+ System.out.println("The pair p10_1 was constructed using the following statement:");
+ System.out.println(" PairInterface<String,Integer> p10_1 = new Pair<String,Integer>(\"Hello\",123);");
+ System.out.println("Then the folloiwng statements are executed:");
+ System.out.println(" p10_1.setFst(\"How are you?\");");
+ System.out.println(" p10_1.setSnd(54321);");
+ System.out.println("After above statements, the pair p10_1 should be " + p10_2 + ".");
+ System.out.println("But the method toString() of our pair p10_1 is returns " + p10_1 + ".\n");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+ System.out.println("Your final point is " + point + ".\n");
+
+ if(point == 10)
+ {
+ System.out.println("Contratulation! Your class Pair works perfectly (I guess).");
+ System.out.println("You can run ParabolaFrame to see how Pair can be used in a program.");
+ }
+ else
+ {
+ System.out.println("There is one or more errors in your class.");
+ System.out.println("Fix your bugs to get more points.");
+ }
+ }
+
+ public static boolean checkFromToString(String s1, String s2)
+ {
+ if(s1.equals(s2))
+ {
+ System.out.println("PASS");
+ return true;
+ }
+ else
+ {
+ System.out.println("FAILED");
+ System.out.println("The method toString() should to return: " + s1);
+ System.out.println("But your method toString() returns : " + s2);
+ return false;
+ }
+ }
+
+ public static String randomString(int length)
+ {
+ String result = "";
+
+ for(int i = 0; i < length; i++)
+ {
+ result = result + randomChar();
+ }
+
+ return result;
+ }
+
+ public static char randomChar()
+ {
+ Random rand = new Random();
+ int modifier = rand.nextInt(26);
+
+ if(rand.nextBoolean())
+ {
+ return (char) ('a' + modifier);
+ }
+ else
+ {
+ return (char) ('A' + modifier);
+ }
+ }
+}
diff --git a/labs/lab01_pair/ParabolaFrame.java b/labs/lab01_pair/ParabolaFrame.java
new file mode 100644
index 0000000..7d77c72
--- /dev/null
+++ b/labs/lab01_pair/ParabolaFrame.java
@@ -0,0 +1,36 @@
+import java.awt.BorderLayout;
+import java.util.ArrayList;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.SwingConstants;
+
+public class ParabolaFrame
+{
+ public static void main(String[] args)
+ {
+ // Create an empty list of points (x,y) using Pair<Double,Double>
+
+ ArrayList<PairInterface<Double,Double>> data = new ArrayList<PairInterface<Double,Double>>();
+
+ // Generate (x,y) points: y = (8/25)x^2 - 3 from -5.0 to 5.0 at
+ // at every 0.01.
+
+ for(double i = -5.0; i <= 5.0; i = i + 0.01)
+ {
+ data.add(new Pair<Double,Double>(i,(((i*i)*8)/25)-3));
+ }
+
+ // Show the Parabola graph
+
+ GraphComponent gc = new GraphComponent(data);
+ JLabel label = new JLabel("Good Job!!!");
+ label.setHorizontalAlignment(SwingConstants.CENTER);
+ JFrame frame = new JFrame();
+ frame.setTitle("Example of Using Pair");
+ frame.setSize(500,500);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.add(gc);
+ frame.add(label, BorderLayout.SOUTH);
+ frame.setVisible(true);
+ }
+}
diff --git a/labs/lab01_pair/lab01_pair.pdf b/labs/lab01_pair/lab01_pair.pdf
new file mode 100644
index 0000000..8cdc686
--- /dev/null
+++ b/labs/lab01_pair/lab01_pair.pdf
Binary files differ
diff --git a/labs/lab02_simpleRGB/ImageViewer.java b/labs/lab02_simpleRGB/ImageViewer.java
new file mode 100644
index 0000000..ecab621
--- /dev/null
+++ b/labs/lab02_simpleRGB/ImageViewer.java
@@ -0,0 +1,85 @@
+import java.io.File;
+import java.io.IOException;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.image.BufferedImage;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.GridLayout;
+import javax.imageio.ImageIO;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+
+public class ImageViewer
+{
+ public static void main(String[] args) throws IOException
+ {
+ File file = new File("pgh_640x480.jpg");
+ BufferedImage originalImage = ImageIO.read(file);
+
+ int width = originalImage.getWidth();
+ int height = originalImage.getHeight();
+
+ final SimpleRGB[] rgb = new SimpleRGB[5];
+ rgb[0] = new SimpleRGB(width, height);
+
+ for(int i = 0; i < height; i++)
+ {
+ for(int j = 0; j < width; j++)
+ {
+ Color c = new Color(originalImage.getRGB(j,i));
+ rgb[0].setRed(j, i, c.getRed());
+ rgb[0].setGreen(j, i, c.getGreen());
+ rgb[0].setBlue(j, i, c.getBlue());
+ }
+ }
+
+ rgb[1] = rgb[0].getRedImage();
+ rgb[2] = rgb[0].getGreenImage();
+ rgb[3] = rgb[0].getBlueImage();
+ rgb[4] = rgb[0].getGreyImage();
+
+ final RGBComponent rgbc = new RGBComponent(rgb[0]);
+
+ JPanel buttonPanel = new JPanel();
+ buttonPanel.setLayout(new GridLayout(1,5));
+
+ JButton[] button = new JButton[5];
+ button[0] = new JButton("RGB");
+ button[1] = new JButton("Red");
+ button[2] = new JButton("Green");
+ button[3] = new JButton("Blue");
+ button[4] = new JButton("Greyscale");
+
+ class colorButtonListener implements ActionListener
+ {
+ private int index;
+
+ public colorButtonListener(int anIndex)
+ {
+ index = anIndex;
+ }
+
+ public void actionPerformed(ActionEvent arg0)
+ {
+ rgbc.setImage(rgb[index]);
+ }
+ }
+
+ ActionListener[] cbl = new colorButtonListener[5];
+ for(int i = 0; i < 5; i++)
+ {
+ cbl[i] = new colorButtonListener(i);
+ button[i].addActionListener(cbl[i]);
+ buttonPanel.add(button[i]);
+ }
+
+ JFrame frame = new JFrame("Image Viewer");
+ frame.setSize(642,534);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.add(rgbc);
+ frame.add(buttonPanel, BorderLayout.SOUTH);
+ frame.setVisible(true);
+ }
+}
diff --git a/labs/lab02_simpleRGB/RGBComponent.java b/labs/lab02_simpleRGB/RGBComponent.java
new file mode 100644
index 0000000..8a1576e
--- /dev/null
+++ b/labs/lab02_simpleRGB/RGBComponent.java
@@ -0,0 +1,46 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Line2D;
+
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class RGBComponent extends JComponent
+{
+ private SimpleRGB image;
+ private int width;
+ private int height;
+
+ public RGBComponent(SimpleRGB anImage)
+ {
+ image = anImage;
+ width = image.getWidth();
+ height = image.getHeight();
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ Line2D.Double line = new Line2D.Double(0,0,0,0);
+
+ // Draw the Board
+
+ for(int w = 0; w < width; w++)
+ {
+ for(int h = 0; h < height; h++)
+ {
+ g2.setColor(new Color(image.getRed(w, h), image.getGreen(w, h), image.getBlue(w, h)));
+ line.setLine(w, h, w, h);
+ g2.draw(line);
+ }
+ }
+ }
+
+ public void setImage(SimpleRGB anImage)
+ {
+ image = anImage;
+ repaint();
+ }
+}
diff --git a/labs/lab02_simpleRGB/SimpleRGB.java b/labs/lab02_simpleRGB/SimpleRGB.java
new file mode 100644
index 0000000..5efc0bd
--- /dev/null
+++ b/labs/lab02_simpleRGB/SimpleRGB.java
@@ -0,0 +1,190 @@
+
+public class SimpleRGB
+{
+ // TO DO: Instant Variables
+ private int width;
+ private int height;
+ private int[] reds;
+ private int[] blues;
+ private int[] greens;
+
+ public SimpleRGB(int aWidth, int aHeight)
+ {
+ this.width = aWidth;
+ this.height = aHeight;
+ reds = new int[width*height];
+ blues = new int[width*height];
+ greens = new int[width*height];
+ }
+
+ /**
+ * Gets the width of this image.
+ * @return the width of this image.
+ */
+ public int getWidth()
+ {
+ return this.width;
+ }
+
+ /**
+ * Gets the height of this image.
+ * @return the height of this image.
+ */
+ public int getHeight()
+ {
+ return this.height;
+ }
+
+ /**
+ * Sets the red value at coordinate (x,y) to aRed.
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @param aRed the red value (0 - 255)
+ */
+ public void setRed(int x, int y, int aRed)
+ {
+ reds[(y*this.width) + x] = aRed;
+ }
+
+ /**
+ * Sets the green value at coordinate (x,y) to aGreen.
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @param aGreen the green value (0 - 255)
+ */
+ public void setGreen(int x, int y, int aGreen)
+ {
+ greens[(y*this.width)+x] = aGreen;
+ }
+
+ /**
+ * Sets the blue value at coordinate (x,y) to aBlue.
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @param aBlue the blue value (0 - 255)
+ */
+ public void setBlue(int x, int y, int aBlue)
+ {
+ blues[(y*this.width)+x] = aBlue;
+ }
+
+ /**
+ * Gets the red value at coordinate (x,y).
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @return the value of red at coordinate (x,y).
+ */
+ public int getRed(int x, int y)
+ {
+ return reds[(y*this.width) + x];
+ }
+
+ /**
+ * Gets the green value at coordinate (x,y).
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @return the value of green at coordinate (x,y).
+ */
+ public int getGreen(int x, int y)
+ {
+ return greens[(y*this.width)+x];
+ }
+
+ /**
+ * Gets the blue value at coordinate (x,y).
+ * @param x the x coordinate of this image.
+ * @param y the y coordinate of this image.
+ * @return the value of blue at coordinate (x,y).
+ */
+ public int getBlue(int x, int y)
+ {
+ return blues[(y*this.width) + x];
+ }
+
+ /**
+ * Get the NEW image containing only the red color.
+ * The red values of this new image should be exactly
+ * the same as red value of this image. The green and
+ * blue values of this new image should be 0s.
+ * @return the NEW image (SimpleRGB) containing only
+ * the red color of this image.
+ */
+ public SimpleRGB getRedImage()
+ {
+ SimpleRGB output = new SimpleRGB(this.width,this.height);
+ for(int i = 0; i < reds.length; i++)
+ {
+ output.setRed(i%this.width,(i/this.width),reds[i]);
+ }
+ return output;
+ }
+
+ /**
+ * Get the NEW image containing only the green color.
+ * The green values of this new image should be exactly
+ * the same as green value of this image. The red and
+ * blue values of this new image should be 0s.
+ * @return the NEW image (SimpleRGB) containing only
+ * the green color of this image.
+ */
+ public SimpleRGB getGreenImage()
+ {
+ SimpleRGB output = new SimpleRGB(this.width,this.height);
+ for(int i = 0; i < greens.length; i++)
+ {
+ output.setGreen(i%this.width,(i/this.width),greens[i]);
+ }
+ return output;
+ }
+
+ /**
+ * Get the NEW image containing only the blue color.
+ * The blue values of this new image should be exactly
+ * the same as blue value of this image. The red and
+ * green values of this new image should be 0s.
+ * @return the NEW image (SimpleRGB) containing only
+ * the blue color of this image.
+ */
+ public SimpleRGB getBlueImage()
+ {
+ SimpleRGB output = new SimpleRGB(this.width,this.height);
+ for(int i = 0; i < blues.length; i++)
+ {
+ output.setBlue(i%this.width,(i/this.width),blues[i]);
+ }
+ return output;
+ }
+
+ /**
+ * Get the NEW image representing the greyscale of this
+ * image. The grey colors are colors that the red, green
+ * and blue value are exactly the same. To convert an RGB
+ * image into a greyscale image, use the following formula
+ * to calculate the new value.
+ * (0.21 * red) + (0.72 * green) + (0.07 * blue)
+ * For example, suppose the (R,G,B) value of this image at
+ * coordinate (10,20) are (10,100,200), since
+ * (0.21 * 10) + (0.72 * 100) + (0.07 * 200) = 88
+ * the (R,G,B) value of the new greyscale image at (10,20)
+ * should be (88,88,88).
+ * @return the NEW image representing the greyscale of this
+ * image.
+ */
+ /**
+ *We're not british!
+ *It's grEy in England,
+ *and grAy in America!
+ */
+ public SimpleRGB getGreyImage()
+ {
+ SimpleRGB output = new SimpleRGB(this.width,this.height);
+ for(int i = 0; i < reds.length; i++)
+ {
+ int gray = (int) ((reds[i]*0.21) + (greens[i]*0.72) + (blues[i]*0.07));
+ output.setRed(i%this.width,(i/this.width),gray);
+ output.setGreen(i%this.width,(i/this.width),gray);
+ output.setBlue(i%this.width,(i/this.width),gray);
+ }
+ return output;
+ }
+}
diff --git a/labs/lab02_simpleRGB/SimpleRGBTester.java b/labs/lab02_simpleRGB/SimpleRGBTester.java
new file mode 100644
index 0000000..2357f52
--- /dev/null
+++ b/labs/lab02_simpleRGB/SimpleRGBTester.java
@@ -0,0 +1,228 @@
+
+public class SimpleRGBTester
+{
+ public static void main(String[] args)
+ {
+ int width = 500;
+ int height = 650;
+ int x = 123;
+ int y = 321;
+ int red = 1;
+ int green = 11;
+ int blue = 111;
+ int point = 0;
+ SimpleRGB rgb = new SimpleRGB(width, height);
+
+ System.out.println("Constructing an SimpleRGB object using the following statement:");
+ System.out.println(" SimpleRGB rgb = new SimpleRGB(" + width + "," + height + ");");
+
+ // Testing the method getWidth()
+
+ System.out.print("Testing the method getWidth(): ");
+
+ if(rgb.getWidth() != width)
+ {
+ System.out.println("FAIL");
+ System.out.println("You method getWidth() should return " + width + ".");
+ System.out.println("But your method getWidth() return " + rgb.getWidth() + ".\n");
+ }
+ else
+ {
+ point++;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // Testing the method getHeight()
+
+ System.out.print("Testing the method getHeight(): ");
+
+ if(rgb.getHeight() != height)
+ {
+ System.out.println("FAIL");
+ System.out.println("You method getHeight() should return " + height + ".");
+ System.out.println("But your method getHeight() return " + rgb.getHeight() + ".\n");
+ }
+ else
+ {
+ point++;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // Testing methods setRed() and getRed()
+
+ System.out.print("Testing method setRed() and getRed(): ");
+
+ rgb.setRed(x, y, red);
+
+ if(rgb.getRed(x,y) != red)
+ {
+ System.out.println("FAIL");
+ System.out.println("After calling rgb.setRed(" + x + "," + y + "," + red + ")");
+ System.out.println("The method rgb.getRed(" + x + "," + y + ") should return " + red + ".");
+ System.out.println("But your method rgb.getRed(" + x + "," + y + ") return " + rgb.getRed(x, y) + ".\n");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // Testing methods setGreen() and getGreen()
+
+ System.out.print("Testing method setGreen() and getGreen(): ");
+
+ rgb.setGreen(x, y, green);
+
+ if(rgb.getGreen(x,y) != green)
+ {
+ System.out.println("FAIL");
+ System.out.println("After calling rgb.setGreen(" + x + "," + y + "," + green + ")");
+ System.out.println("The method rgb.getGreen(" + x + "," + y + ") should return " + green + ".");
+ System.out.println("But your method rgb.getGreen(" + x + "," + y + ") return " + rgb.getGreen(x, y) + ".\n");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // Testing methods setBlue() and getBlue()
+
+ System.out.print("Testing method setBlue() and getBlue(): ");
+
+ rgb.setBlue(x, y, blue);
+
+ if(rgb.getBlue(x,y) != blue)
+ {
+ System.out.println("FAIL");
+ System.out.println("After calling rgb.setBlue(" + x + "," + y + "," + blue + ")");
+ System.out.println("The method rgb.getBlue(" + x + "," + y + ") should return " + blue + ".");
+ System.out.println("But your method rgb.getBlue(" + x + "," + y + ") return " + rgb.getBlue(x, y) + ".\n");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // getRedImage();
+
+ System.out.print("Testing method getRedImage(): ");
+
+ SimpleRGB redImage = rgb.getRedImage();
+
+ if(redImage.getRed(x, y) != red || redImage.getGreen(x,y) != 0 || redImage.getBlue(x,y) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("The variable redImage of type SimpleRGB was initialized using the following statement:");
+ System.out.println(" SimpleRGB redImage = rgb.getRedImage();");
+ System.out.println("The (R,G,B) values of the rgb image at (" + x + "," + y + ") are (" + red + "," + green + "," + blue + ").");
+ System.out.println("The (R,G,B) values of the redImage at (" + x + "," + y + ") should be (" + red + ",0,0).");
+ System.out.println("But your method");
+ System.out.println(" redImage.getRed(" + x + "," + y + ") returns " + redImage.getRed(x,y) + ".");
+ System.out.println(" redImage.getGreen(" + x + "," + y + ") returns " + redImage.getGreen(x,y) + ".");
+ System.out.println(" redImage.getBlue(" + x + "," + y + ") returns " + redImage.getBlue(x,y) + ".");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // getGreenImage();
+
+ System.out.print("Testing method getGreenImage(): ");
+
+ SimpleRGB greenImage = rgb.getGreenImage();
+
+ if(greenImage.getRed(x, y) != 0 || greenImage.getGreen(x,y) != green || greenImage.getBlue(x,y) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("The variable greenImage of type SimpleRGB was initialized using the following statement:");
+ System.out.println(" SimpleRGB greenImage = rgb.getGreenImage();");
+ System.out.println("The (R,G,B) values of the rgb image at (" + x + "," + y + ") are (" + red + "," + green + "," + blue + ").");
+ System.out.println("The (R,G,B) values of the greenImage at (" + x + "," + y + ") should be (0," + green + ",0).");
+ System.out.println("But your method");
+ System.out.println(" greenImage.getRed(" + x + "," + y + ") returns " + greenImage.getRed(x,y) + ".");
+ System.out.println(" greenImage.getGreen(" + x + "," + y + ") returns " + greenImage.getGreen(x,y) + ".");
+ System.out.println(" greenImage.getBlue(" + x + "," + y + ") returns " + greenImage.getBlue(x,y) + ".");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // getBlueImage();
+
+ System.out.print("Testing method getBlueImage(): ");
+
+ SimpleRGB blueImage = rgb.getBlueImage();
+
+ if(blueImage.getRed(x, y) != 0 || blueImage.getGreen(x,y) != 0 || blueImage.getBlue(x,y) != blue)
+ {
+ System.out.println("FAIL");
+ System.out.println("The variable blueImage of type SimpleRGB was initialized using the following statement:");
+ System.out.println(" SimpleRGB blueImage = rgb.getBlueImage();");
+ System.out.println("The (R,G,B) values of the rgb image at (" + x + "," + y + ") are (" + red + "," + green + "," + blue + ").");
+ System.out.println("The (R,G,B) values of the blueImage at (" + x + "," + y + ") should be (0,0," + blue + ").");
+ System.out.println("But your method");
+ System.out.println(" blueImage.getRed(" + x + "," + y + ") returns " + blueImage.getRed(x,y) + ".");
+ System.out.println(" blueImage.getGreen(" + x + "," + y + ") returns " + blueImage.getGreen(x,y) + ".");
+ System.out.println(" blueImage.getBlue(" + x + "," + y + ") returns " + blueImage.getBlue(x,y) + ".");
+ }
+ else
+ {
+ point += 1;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ // getGreyImage();
+
+ System.out.print("Testing method getGreyImage(): ");
+
+ SimpleRGB greyImage = rgb.getGreyImage();
+
+ int greyValue = (int) ((0.21 * rgb.getRed(x, y)) + (0.72 * rgb.getGreen(x,y)) + (0.07 * rgb.getBlue(x,y)));
+
+ if(greyImage.getRed(x, y) != greyValue || greyImage.getGreen(x,y) != greyValue || greyImage.getBlue(x,y) != greyValue)
+ {
+ System.out.println("FAIL");
+ System.out.println("The variable greyImage of type SimpleRGB was initialized using the following statement:");
+ System.out.println(" SimpleRGB greyImage = rgb.getGreyImage();");
+ System.out.println("The (R,G,B) values of the rgb image at (" + x + "," + y + ") is (" + red + "," + green + "," + blue + ").");
+ System.out.println("The (R,G,B) values of the greyImage at (" + x + "," + y + ") should be (" + greyValue + "," + greyValue + "," + greyValue + ").");
+ System.out.println("But your method");
+ System.out.println(" greyImage.getRed(" + x + "," + y + ") returns " + greyImage.getRed(x,y) + ".");
+ System.out.println(" greyImage.getGreen(" + x + "," + y + ") returns " + greyImage.getGreen(x,y) + ".");
+ System.out.println(" greyImage.getBlue(" + x + "," + y + ") returns " + greyImage.getBlue(x,y) + ".");
+ }
+ else
+ {
+ point += 2;
+ System.out.println("PASS");
+ }
+ System.out.println("You current point is " + point + ".\n");
+
+ System.out.println("Your final point is " + point + ".");
+
+ if(point == 10)
+ {
+ System.out.println("Contratulation! Your class SimpleRGB works perfectly (I guess).");
+ System.out.println("You can run ImageViewer to see how SimpleRGB can be used in a program.");
+ }
+ else
+ {
+ System.out.println("There is one or more errors in your class.");
+ System.out.println("Fix your bugs to get more points.");
+ }
+ }
+}
diff --git a/labs/lab02_simpleRGB/lab02_simpleRGB.pdf b/labs/lab02_simpleRGB/lab02_simpleRGB.pdf
new file mode 100644
index 0000000..8558e16
--- /dev/null
+++ b/labs/lab02_simpleRGB/lab02_simpleRGB.pdf
Binary files differ
diff --git a/labs/lab02_simpleRGB/pgh_640x480.jpg b/labs/lab02_simpleRGB/pgh_640x480.jpg
new file mode 100644
index 0000000..12894c8
--- /dev/null
+++ b/labs/lab02_simpleRGB/pgh_640x480.jpg
Binary files differ
diff --git a/labs/lab03_dll/DLinkedList.java b/labs/lab03_dll/DLinkedList.java
new file mode 100644
index 0000000..ef0f495
--- /dev/null
+++ b/labs/lab03_dll/DLinkedList.java
@@ -0,0 +1,190 @@
+
+public class DLinkedList<T>
+{
+ private Node firstNode;
+ private Node lastNode;
+ private Node middleNode;
+ private int numberOfEntries;
+ private int middlePosition;
+
+ public DLinkedList()
+ {
+ firstNode = null;
+ lastNode = null;
+ middleNode = null;
+ numberOfEntries = 0;
+ middlePosition = 0;
+ }
+
+ public void add(T newEntry)
+ {
+ if(firstNode == null)
+ {
+ firstNode = new Node(null, newEntry, null);
+ lastNode = firstNode;
+ }
+ else
+ {
+ Node newNode = new Node(lastNode, newEntry, null);
+ lastNode.next = newNode;
+ lastNode = newNode;
+ }
+
+ numberOfEntries++;
+
+ if(numberOfEntries % 2 == 1)
+ {
+ if(middleNode == null)
+ {
+ middleNode = firstNode;
+ }
+ else
+ {
+ middleNode = middleNode.next;
+ }
+ middlePosition++;
+ }
+ }
+
+ public T getEntry(int givenPosition)
+ {
+ T result = null;
+
+ if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
+ {
+ result = (getNodeAt(givenPosition)).data;
+ }
+
+ return result;
+ }
+
+ private Node getNodeAt(int givenPosition)
+ {
+ Node currentNode = firstNode;
+
+ for(int counter = 1; counter < givenPosition; counter++)
+ {
+ currentNode = currentNode.next;
+ }
+
+ return currentNode;
+ }
+
+ public T getEntry1(int givenPosition)
+ {
+ T result = null;
+
+ if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
+ {
+ result = (getNodeAt1(givenPosition)).data;
+ }
+
+ return result;
+ }
+
+ /**
+ * Modify this method according to the Solution 1
+ */
+ private Node getNodeAt1(int givenPosition)
+ {
+ if(givenPosition > middlePosition)
+ {
+ //start from end, go backwars
+ Node temp = lastNode;
+ for(int i = 0;i<numberOfEntries - givenPosition;i++)
+ {
+ temp = temp.previous;
+ }
+ return temp;
+ }
+ else
+ {
+ //start from front, forwards
+ Node temp = firstNode;
+ for(int i = 1; i < givenPosition;i++)
+ {
+ temp = temp.next;
+ }
+ return temp;
+ }
+ }
+
+ public T getEntry2(int givenPosition)
+ {
+ T result = null;
+
+ if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
+ {
+ result = (getNodeAt2(givenPosition)).data;
+ }
+
+ return result;
+ }
+
+ /**
+ * Modify this method according to the Solution 2
+ */
+ private Node getNodeAt2(int givenPosition)
+ {
+ if(givenPosition < middlePosition)
+ {
+ if(givenPosition < middlePosition/2)
+ {
+ //STart from the front, go forwards
+ Node temp = firstNode;
+ for(int i = 1;i < givenPosition;i++)
+ {
+ temp = temp.next;
+ }
+ return temp;
+ }
+ else
+ {
+ //Start from the middle, backwards
+ Node temp = middleNode;
+ for(int i = middlePosition; i > givenPosition;i--)
+ {
+ temp = temp.previous;
+ }
+ return temp;
+ }
+ }
+ else
+ {
+ if(givenPosition < numberOfEntries*(3.0/4))
+ {
+ //Start from the middle, go forwards
+ Node temp = middleNode;
+ for(int i = middlePosition; i < givenPosition; i++)
+ {
+ temp = temp.next;
+ }
+ return temp;
+ }
+ else
+ {
+ //Start from the end, go backwards
+ Node temp = lastNode;
+ for(int i = numberOfEntries; i >givenPosition; i--)
+ {
+ temp = temp.previous;
+ }
+ return temp;
+ }
+ }
+ }
+
+ private class Node
+ {
+ private Node previous;
+ private T data;
+ private Node next;
+
+ private Node(Node previousNode, T aData, Node nextNode)
+ {
+ previous = previousNode;
+ data = aData;
+ next = nextNode;
+ }
+ }
+}
diff --git a/labs/lab03_dll/DLinkedListTester.java b/labs/lab03_dll/DLinkedListTester.java
new file mode 100644
index 0000000..b583e84
--- /dev/null
+++ b/labs/lab03_dll/DLinkedListTester.java
@@ -0,0 +1,168 @@
+import java.util.Random;
+
+public class DLinkedListTester
+{
+ public static void main(String[] args)
+ {
+ // Construct a list and add entries
+
+ int numberOfData = 100000; // number of data to add to the list
+ int maxDataValue = 10000; // number of different values to add to the list
+ int numSampling = 10000; // number of calling the method getEntry
+ int dryRunReps = numSampling / 1000;
+
+ DLinkedList<Integer> list = new DLinkedList<Integer>();
+
+ Random rand = new Random();
+ rand.setSeed(System.nanoTime());
+
+ System.out.print("Adding data into the list: ");
+
+ for(int i = 0; i < numberOfData; i++)
+ {
+ list.add(rand.nextInt(maxDataValue));
+ }
+
+ System.out.println("DONE");
+
+ int[] positions = new int[numSampling];
+ int[] returnValues = new int[numSampling];
+
+ System.out.print("Dry run for the method getEntry(): ");
+
+ // Dry run for the method getEntry1 (no timer)
+ // Also store all result for testing the method getEntry2()
+
+ for(int i = 0; i < numSampling; i++)
+ {
+ int aPosition = rand.nextInt(numberOfData) + 1;
+ positions[i] = aPosition;
+ returnValues[i] = list.getEntry(aPosition);
+ }
+
+ System.out.println("DONE");
+
+ double startTime; // Start time millisecond
+ double endTime; // End time millisecond
+
+ System.out.print("Time the method getEntry(): ");
+
+ // Timing the method getEntry()
+
+ startTime = System.currentTimeMillis();
+
+ for(int i = 0; i < numSampling; i++)
+ {
+ if(returnValues[i] != list.getEntry(positions[i]))
+ {
+ System.out.println("There is something wrong.");
+ System.out.println("The entry in position " + positions[i] + " should be " + returnValues[i] + ".");
+ System.out.println("But the method getEntry(" + positions[i] + ") returns " + list.getEntry(positions[i]) + ".");
+ System.out.println("Fix the method getNodeAt() first.");
+ return;
+ }
+ }
+
+ endTime = System.currentTimeMillis();
+
+ double getEntryTime = endTime - startTime;
+
+ System.out.println("DONE");
+
+ // getEntry1() - Solution 1
+
+ // Dry run (no timer)
+
+ System.out.print("Dry run for the method getEntry1(): ");
+
+ for(int i = 0; i < dryRunReps; i++)
+ {
+ if(returnValues[i] != list.getEntry1(positions[i]))
+ {
+ System.out.println("There is something wrong.");
+ System.out.println("The entry in position " + positions[i] + " should be " + returnValues[i] + ".");
+ System.out.println("But the method getEntry1(" + positions[i] + ") returns " + list.getEntry1(positions[i]) + ".");
+ System.out.println("Fix the method getNodeAt1() first.");
+ return;
+ }
+ }
+
+ System.out.println("DONE");
+
+ // Timing the method getEntry1()
+
+ System.out.print("Time the method getEntry1(): ");
+
+ startTime = System.currentTimeMillis();
+
+ for(int i = 0; i < numSampling; i++)
+ {
+ if(returnValues[i] != list.getEntry1(positions[i]))
+ {
+ System.out.println("There is something wrong.");
+ System.out.println("The entry in position " + positions[i] + " should be " + returnValues[i] + ".");
+ System.out.println("But the method getEntry1(" + positions[i] + ") returns " + list.getEntry1(positions[i]) + ".");
+ System.out.println("Fix the method getNodeAt1() first.");
+ return;
+ }
+ }
+
+ endTime = System.currentTimeMillis();
+
+ double getEntry1Time = endTime - startTime;
+
+ System.out.println("DONE");
+
+ // getEntry2() - Solution 2
+
+ // Dry run (no timer)
+
+ System.out.print("Dry run for the method getEntry2(): ");
+
+ for(int i = 0; i < dryRunReps; i++)
+ {
+ if(returnValues[i] != list.getEntry2(positions[i]))
+ {
+ System.out.println("There is something wrong.");
+ System.out.println("The entry in position " + positions[i] + " should be " + returnValues[i] + ".");
+ System.out.println("But the method getEntry2(" + positions[i] + ") returns " + list.getEntry2(positions[i]) + ".");
+ System.out.println("Fix the method getNodeAt2() first.");
+ return;
+ }
+ }
+
+ System.out.println("DONE");
+
+ // Timing the method getEntry2()
+
+ System.out.print("Time the method getEntry2(): ");
+
+ startTime = System.currentTimeMillis();
+
+ for(int i = 0; i < numSampling; i++)
+ {
+ if(returnValues[i] != list.getEntry2(positions[i]))
+ {
+ System.out.println("There is something wrong.");
+ System.out.println("The entry in position " + positions[i] + " should be " + returnValues[i] + ".");
+ System.out.println("But the method getEntry2(" + positions[i] + ") returns " + list.getEntry2(positions[i]) + ".");
+ System.out.println("Fix the method getNodeAt2() first.");
+ return;
+ }
+ }
+
+ endTime = System.currentTimeMillis();
+
+ double getEntry2Time = endTime - startTime;
+
+ System.out.println("Done\n");
+
+
+ System.out.println("The method getEntry() took " + getEntryTime + " millisecond.");
+ System.out.println("The method getEntry1() took " + getEntry1Time + " millisecond.");
+ System.out.println("The method getEntry2() took " + getEntry2Time + " millisecond.\n");
+
+ System.out.println("If getEntry1() took roughly about half the time of getEntry(), you get 5 points.");
+ System.out.println("If getEntry2() took roughly about a quarter the time of getEntry(), you get 5 points.");
+ }
+}
diff --git a/labs/lab03_dll/lab03_dll.pdf b/labs/lab03_dll/lab03_dll.pdf
new file mode 100644
index 0000000..8789c66
--- /dev/null
+++ b/labs/lab03_dll/lab03_dll.pdf
Binary files differ
diff --git a/labs/lab04_recurionll/RecursionLLTester.java b/labs/lab04_recurionll/RecursionLLTester.java
new file mode 100644
index 0000000..e93ef3d
--- /dev/null
+++ b/labs/lab04_recurionll/RecursionLLTester.java
@@ -0,0 +1,232 @@
+import java.util.Random;
+
+
+public class RecursionLLTester
+{
+ public static void main(String[] args)
+ {
+ RecursionLinkedList rll = new RecursionLinkedList();
+ int point = 0;
+ boolean isError = false;
+
+ System.out.println("Create an empty RecursionLinkedList named rll.");
+
+ System.out.print("Test the method contains() on an empty RecursionLinkedList: ");
+ if(rll.contains(5) != false)
+ {
+ System.out.println("FAIL");
+ System.out.println("Nothing is added into RecursionLinkedList rll.");
+ System.out.println("rll.contains(5) should return 0.");
+ System.out.println("But your rll.contains(5) returns " + rll.contains(5) + ".");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ System.out.print("Test the method getFrequencyOf() on an empty RecursionLinkedList: ");
+ if(rll.getFrequencyOf(5) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("Nothing is added into RecursionLinkedList rll.");
+ System.out.println("rll.getFrequencyOf(5) should return 0.");
+ System.out.println("But your rll.getFrequencyOf(5) returns " + rll.getFrequencyOf(5) + ".");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ Random rand = new Random();
+ int num = 20;
+ int[] array = new int[5];
+ for(int i = 0; i < 5; i++)
+ {
+ array[i] = 0;
+ }
+
+ System.out.println("Add the following integer into rll:");
+ String s = "]";
+
+ for(int i = 0; i < num - 1; i++)
+ {
+ int temp = rand.nextInt(5);
+ System.out.print(temp + " ");
+ s = "," + temp + s;
+ array[temp]++;
+ rll.add(temp);
+ }
+ int temp = rand.nextInt(5);
+ System.out.println(temp);
+ s = "[" + temp + s;
+ array[temp]++;
+ rll.add(temp);
+
+
+ System.out.println("\nTest the method contains() on a non-empty RecursionLinkedList");
+ System.out.print(" - Test rll.contains(-1): ");
+ if(rll.contains(-1) != false)
+ {
+ System.out.println("FAIL");
+ System.out.println("No -1 has been added into the RecursionLinkedList rll.");
+ System.out.println("rll.contains(-1) should return 0.");
+ System.out.println("But your rll.contains(-1) returns " + rll.contains(-1));
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ for(int i = 0; i < 5; i++)
+ {
+ System.out.print(" - Test rll.contains(" + i + "): ");
+ if(rll.contains(i) != (array[i] != 0))
+ {
+ System.out.println("FAIL");
+ System.out.println("There are " + array[i] + " in RecursiveLinkedList rll.");
+ System.out.println("rll.contains(" + i + ") should return " + (array[i] != 0));
+ System.out.println("But your rll.contains(" + i + ") returns " + rll.contains(i));
+ isError = true;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ if(!isError)
+ {
+ point++;
+ isError = false;
+ }
+
+ System.out.print(" - Test rll.contains(5): ");
+ if(rll.contains(5) != false)
+ {
+ System.out.println("FAIL");
+ System.out.println("No 5 has been added into the RecursionLinkedList rll.");
+ System.out.println("rll.contains(5) should return 0.");
+ System.out.println("But your rll.contains(5) returns " + rll.contains(5));
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ System.out.println("Test the method getFrequencyOf() on a non-empty RecursionLinkedList");
+ System.out.print(" - Test rll.getFrequencyOf(-1): ");
+ if(rll.getFrequencyOf(-1) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("No -1 has been added into the RecursionLinkedList rll.");
+ System.out.println("rll.getFrequencyOf(-1) should return 0.");
+ System.out.println("But your rll.getFrequencyOf(-1) returns " + rll.getFrequencyOf(-1));
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ for(int i = 0; i < 5; i++)
+ {
+ System.out.print(" - Test rll.getFrequencyOf(" + i + "): ");
+ if(rll.getFrequencyOf(i) != array[i])
+ {
+ System.out.println("FAIL");
+ System.out.println(i + " has been added to the RecursionLinkedList " + array[i] + " times.");
+ System.out.println("rll.getFrequencyOf(" + i + ") should return " + array[i] + ".");
+ System.out.println("But your rll.getFrequencyOf(" + i + ") returns " + rll.getFrequencyOf(i));
+ isError = true;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ if(!isError)
+ {
+ point++;
+ isError = false;
+ }
+
+ System.out.print(" - Test rll.getFrequencyOf(5): ");
+ if(rll.getFrequencyOf(5) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("No 5 has been added into the RecursionLinkedList rll.");
+ System.out.println("rll.getFrequencyOf(5) should return 0.");
+ System.out.println("But your rll.getFrequencyOf(5) returns " + rll.getFrequencyOf(5));
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+ System.out.print("Test the method toString(): ");
+ if(!s.equals(rll.toString()))
+ {
+ System.out.println("FAIL");
+ System.out.println("rll.toString() should return the string \"" + s + "\".");
+ System.out.println("But your rll.toString() returns the string \"" + rll.toString() + "\".");
+ }
+ else
+ {
+ System.out.println("PASS");
+ point++;
+ }
+
+
+ System.out.println("Test the method getIndexOf()");
+ System.out.println("Currently the rll is " + rll + ".");
+
+ String[] str = rll.toString().split(",");
+ str[0] = str[0].substring(1);
+ str[str.length - 1] = str[str.length - 1].substring(0, 1);
+
+ for(int i = -1; i <= 5; i++)
+ {
+ System.out.print("Test the method getIndexOf(" + i + "): ");
+ if(getIndex(str,i) != rll.getIndexOf(i))
+ {
+ System.out.println("FAIL");
+ System.out.println("The index of " + i + " should be " + getIndex(str,i) + ".");
+ System.out.println("But your rll.getIndexOf(" + i + ") returns " + rll.getIndexOf(i) + ".");
+ isError = true;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ if(!isError)
+ {
+ point++;
+ isError = false;
+ }
+
+ System.out.println("Your current point is " + point + ".");
+ }
+
+ public static int getIndex(String[] str, int s)
+ {
+ int result = -1;
+
+ for(int i = 0; i < str.length; i++)
+ {
+ if(s == Integer.parseInt(str[i]))
+ {
+ return i;
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/labs/lab04_recurionll/RecursionLinkedList.java b/labs/lab04_recurionll/RecursionLinkedList.java
new file mode 100644
index 0000000..bd1f3c5
--- /dev/null
+++ b/labs/lab04_recurionll/RecursionLinkedList.java
@@ -0,0 +1,164 @@
+
+public class RecursionLinkedList
+{
+ private Node firstNode;
+ private int numberOfEntries;
+
+ public RecursionLinkedList()
+ {
+ firstNode = null;
+ numberOfEntries = 0;
+ }
+
+ public void add(int aData)
+ {
+ if(numberOfEntries == 0)
+ {
+ firstNode = new Node(aData);
+ }
+ else
+ {
+ firstNode = new Node(aData, firstNode);
+ }
+
+ numberOfEntries++;
+ }
+
+ /**
+ * boolean contains(int aData)
+ *
+ * See whether this RecursionLinkedList contains aData
+ * @param aData a data to be located
+ * @return true if this RecursionLinkedList contains aData,
+ * or false otherwise.
+ */
+ public boolean contains(int aData)
+ {
+ return containsHelper(firstNode,aData);
+ }
+ private boolean containsHelper(Node thisnode, int aData)
+ {
+ if(thisnode == null)
+ {
+ return false;
+ }
+ else if(thisnode.data == aData)
+ {
+ return true;
+ }
+ else
+ {
+ return containsHelper(thisnode.next, aData);
+ }
+ }
+
+ /**
+ * int getFrequencyOf(int aData)
+ *
+ * Counts the number of times a given data appears in this
+ * RecursionLinkedList.
+ *
+ * @param aData the data to be counted
+ * @return the number of times aData appears in this RecursionLinkedList
+ */
+ public int getFrequencyOf(int aData)
+ {
+ return getFrequencyOfHelper(firstNode,aData);
+ }
+ private int getFrequencyOfHelper(Node thisnode, int aData)
+ {
+ if(thisnode == null)
+ {
+ return 0;
+ }
+ else if(thisnode.data == aData)
+ {
+ return getFrequencyOfHelper(thisnode.next, aData) + 1;
+ }
+ else
+ {
+ return getFrequencyOfHelper(thisnode.next, aData);
+ }
+ }
+
+ /**
+ * String toString()
+ *
+ * Return a string representation of this RecursionLinkedList. For example,
+ * if this RecursionLinkedList contains 1, 2, 3, 5, 2 and 3 from the first
+ * index to the last index, the returned string should be
+ * "[1,2,3,5,2,3]"
+ * @return the string representation of this RecursionLinkedList.
+ */
+ public String toString()
+ {
+ return "[" + firstNode.data + toStringHelper(firstNode.next) + "]";
+ }
+ private String toStringHelper(Node thisnode)
+ {
+ if(thisnode == null)
+ {
+ return "";
+ }
+ else
+ {
+ return "," + thisnode.data + toStringHelper(thisnode.next);
+ }
+ }
+ /**
+ * int getIndexOf(int aData)
+ *
+ * Return the index of the first aData where the first index of
+ * the first item in this RecursionLinkedList is 0.
+ *
+ * @param aData the data to be located
+ * @return the index of the first aData.
+ */
+ public int getIndexOf(int aData)
+ {
+ int p = getIndexOfHelper(firstNode,aData);
+ /*
+ if(p==numberOfEntries+1)
+ {
+ return -1;
+ }
+ else
+ {
+ return p;
+ }
+ */
+ return p==numberOfEntries+1?-1:p;
+ }
+ private int getIndexOfHelper(Node thisnode, int aData)
+ {
+ if(thisnode == null)
+ {
+ return 1;
+ }
+ else if(thisnode.data == aData)
+ {
+ return 0;
+ }
+ else
+ {
+ return getIndexOfHelper(thisnode.next,aData) + 1;
+ }
+ }
+
+ private class Node
+ {
+ private int data;
+ private Node next;
+
+ private Node(int aData, Node nextNode)
+ {
+ data = aData;
+ next = nextNode;
+ }
+
+ private Node(int aData)
+ {
+ this(aData, null);
+ }
+ }
+}
diff --git a/labs/lab04_recurionll/lab04_rll.pdf b/labs/lab04_recurionll/lab04_rll.pdf
new file mode 100644
index 0000000..0ec1faa
--- /dev/null
+++ b/labs/lab04_recurionll/lab04_rll.pdf
Binary files differ
diff --git a/labs/lab05_permutation/Permutation.java b/labs/lab05_permutation/Permutation.java
new file mode 100644
index 0000000..b0cc541
--- /dev/null
+++ b/labs/lab05_permutation/Permutation.java
@@ -0,0 +1,51 @@
+import java.util.ArrayList;
+
+
+public class Permutation
+{
+ public static ArrayList<ArrayList<Integer>> permutation(final ArrayList<Integer> olist)
+ {
+ ArrayList<Integer> list = new ArrayList<Integer>();
+ for(Integer i : olist)
+ {
+ list.add(i);
+ }
+ //System.out.println("[ME]Permutateing " + list);
+ ArrayList<ArrayList<Integer>> output = new ArrayList<ArrayList<Integer>>();
+ //System.out.println("[ME] Size is " + list.size());
+ if(list.size() <= 1)
+ {
+ output.add(list);
+ }
+
+ else
+ {
+ ArrayList<Integer> newlist = list;
+ for(Integer i=0; i < list.size(); i++)
+ {
+ //System.out.println("[ME]First element for this permutation is " + newlist.get(0));
+ Integer firstEntry = newlist.remove(0);
+ for(ArrayList<Integer> l : permutation(newlist))
+ {
+ //System.out.println("[ME]This arraylist" + l);
+ ArrayList<Integer> tmp1 = new ArrayList<Integer>();
+ //ArrayList<Integer> tmp2 = new ArrayList<Integer>();
+ tmp1.add(firstEntry);
+ for(Integer i2 : l)
+ {
+ tmp1.add(i2);
+ //tmp2.add(i2);
+ }
+ //tmp2.add(firstEntry);
+ //System.out.println("[ME] This full permutation is " + tmp1 + ", i is " + i + " and size is " + list.size());
+ output.add(tmp1);
+ //output.add(tmp2);
+ }
+ newlist.add(firstEntry);
+ }
+ }
+
+ //System.out.println("[ME] Returning " + output);
+ return output;
+ }
+}
diff --git a/labs/lab05_permutation/PermutationTester.java b/labs/lab05_permutation/PermutationTester.java
new file mode 100644
index 0000000..2c56d3b
--- /dev/null
+++ b/labs/lab05_permutation/PermutationTester.java
@@ -0,0 +1,129 @@
+import java.util.ArrayList;
+
+
+public class PermutationTester
+{
+ public static void main(String[] args)
+ {
+ int point = 0;
+ ArrayList<Integer> list = new ArrayList<Integer>();
+ ArrayList<ArrayList<Integer>> result;
+
+ for(int i = 1; i <= 5; i++)
+ {
+ System.out.println("Testing permutation with " + i + " element(s)");
+ list.add(i);
+ /*Take this out*///System.out.println("[ME]Before" + list);
+ result = Permutation.permutation(list);
+ /*Take this out*///System.out.println("[ME]After" + list);
+ System.out.println("Your code said, the permutation of " + list + " is as follows:");
+ System.out.println(result);
+
+ boolean result1 = checkPermutationSize(list, result);
+ boolean result2 = checkPermutation(list, result);
+ if(result1 && result2)
+ {
+ point += 2;
+ System.out.println("Your current point is " + point + ".");
+ System.out.println();
+ }
+ else
+ {
+ System.out.println("Your current point is " + point + ".");
+ System.out.println("There is someting wrong with your method permutation().");
+ System.out.println("Fix your code and run this tester class again.");
+ break;
+ }
+ }
+ }
+
+ private static int factorial(int n)
+ {
+ if(n == 0)
+ return 1;
+ else
+ return n * factorial(n - 1);
+ }
+
+ private static boolean checkPermutation(ArrayList<Integer> list, ArrayList<ArrayList<Integer>> result)
+ {
+ int numberOfElements = list.size();
+ int numberOfResults = result.size();
+
+ System.out.print("Check the size of each element: ");
+ for(int i = 0; i < numberOfResults; i++)
+ {
+ if(result.get(i).size() != list.size())
+ {
+ System.out.println("FAIL");
+ System.out.println("Every element in your result should contains " + numberOfElements + " elements.");
+ System.out.println("But an element of your result contains " + result.get(i).size() + " elements.");
+ return false;
+ }
+ }
+
+ System.out.println("PASS");
+
+ System.out.print("Check for duplicate elements: ");
+
+ for(int i = 0; i < numberOfResults; i++)
+ {
+ ArrayList<Integer> temp = result.get(i);
+
+ for(int j = i + 1; j < numberOfResults; j++)
+ {
+ if(temp.equals(result.get(j)))
+ {
+ System.out.println("FAIL");
+ System.out.println("Your result contains duplicate items which is " + temp + ".");
+ return false;
+ }
+ }
+ }
+
+ System.out.println("PASS");
+
+ System.out.print("Check each element: ");
+ for(int i = 0; i < numberOfResults; i++)
+ {
+ ArrayList<Integer> temp = result.get(i);
+
+ for(int j = 0; j < numberOfElements; j++)
+ {
+ int aNumber = list.get(j);
+
+ if(!temp.contains(aNumber))
+ {
+ System.out.println("FAIL");
+ System.out.println("The element " + temp + " in your result does not contain every element in " + list + ".");
+ }
+ }
+ }
+
+ System.out.println("PASS");
+
+ return true;
+ }
+
+ private static boolean checkPermutationSize(ArrayList<Integer> list, ArrayList<ArrayList<Integer>> result)
+ {
+ System.out.print("Check the size of the result: ");
+
+ int numberOfElements = list.size();
+ int numberOfResults = result.size();
+
+ if(factorial(numberOfElements) != numberOfResults)
+ {
+ System.out.println("FAIL");
+ System.out.println(" The list " + list + " contains " + numberOfElements + " elements.");
+ System.out.println(" Permutation of " + list + " should contains " + factorial(numberOfElements) + "elements.");
+ System.out.println(" But your result contains " + numberOfResults + " elements.");
+ return false;
+ }
+ else
+ {
+ System.out.println("PASS");
+ return true;
+ }
+ }
+} \ No newline at end of file
diff --git a/labs/lab05_permutation/lab05_permutation.pdf b/labs/lab05_permutation/lab05_permutation.pdf
new file mode 100644
index 0000000..fffd055
--- /dev/null
+++ b/labs/lab05_permutation/lab05_permutation.pdf
Binary files differ
diff --git a/labs/lab07_tohSolver/THComponent.java b/labs/lab07_tohSolver/THComponent.java
new file mode 100644
index 0000000..3a61dc5
--- /dev/null
+++ b/labs/lab07_tohSolver/THComponent.java
@@ -0,0 +1,113 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Rectangle2D;
+import java.util.Random;
+
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class THComponent extends JComponent
+{
+ private int width;
+ private int height;
+ private int leftMargin = 10;
+ private int rightMargin = 10;
+ private int topMargin = 10;
+ private int bottomMargin = 10;
+ private int baseHeight = 10;
+ private double poleWidth = 10;
+ private TowerOfHanoi towers;
+ private int numberOfDiscs;
+ private double largestDiscSize;
+ private double smallestDiscSize = 20;
+ private double defaultReductionSize = 20.0;
+ private double defaultDiscHeight = 20.0;
+ private double[] discSizes;
+
+ public THComponent(TowerOfHanoi aTowers)
+ {
+ towers = aTowers;
+ numberOfDiscs = towers.getNumberOfDiscs();
+ discSizes = new double[numberOfDiscs];
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ width = this.getWidth();
+ height = this.getHeight();
+
+ int drawingWidth = width - (leftMargin + rightMargin);
+ int drawingHeight = height - (topMargin + bottomMargin);
+
+ // draw the base;
+
+ Rectangle2D.Double rect = new Rectangle2D.Double(leftMargin , height - (bottomMargin + baseHeight), drawingWidth, baseHeight);
+ g2.draw(rect);
+
+ // draw poles;
+
+ double halfDistance = ((double) drawingWidth / 6);
+ largestDiscSize = (halfDistance * 2) - poleWidth;
+
+ for(int i = 1; i <= 5; i = i + 2)
+ {
+ rect.setRect((leftMargin + (halfDistance * i)) - (poleWidth / 2), topMargin, poleWidth, drawingHeight - baseHeight);
+ g2.draw(rect);
+ }
+
+ // draw discs
+
+ double totalReduction = (largestDiscSize - smallestDiscSize) / (numberOfDiscs - 1);
+ double actualReduction;
+
+ if(totalReduction > defaultReductionSize)
+ {
+ actualReduction = defaultReductionSize;
+ }
+ else
+ {
+ actualReduction = totalReduction;
+ }
+
+ double totalHeight = drawingHeight - baseHeight;
+ double tempDiscHeight = totalHeight / (numberOfDiscs + 1);
+ double actualDiscHeight;
+
+ if(tempDiscHeight > defaultDiscHeight)
+ {
+ actualDiscHeight = defaultDiscHeight;
+ }
+ else
+ {
+ actualDiscHeight = tempDiscHeight;
+ }
+
+ for(int i = 0; i < numberOfDiscs; i++)
+ {
+ discSizes[i] = largestDiscSize - (actualReduction * ((numberOfDiscs - 1) - i));
+ }
+
+ int[][] t = new int[3][];
+ for(int i = 0; i < 3; i++)
+ {
+ t[i] = towers.getArrayOfDiscs(i);
+ }
+
+ for(int i = 0; i <= 2; i++)
+ {
+ for(int j = 0; j < t[i].length; j++)
+ {
+ double x = (leftMargin + (halfDistance * (1 + (2 * i)))) - (discSizes[t[i][j]] / 2);
+ double y = ((topMargin + drawingHeight) - baseHeight) - (actualDiscHeight * (j + 1));
+ rect.setRect(x,y,discSizes[t[i][j]],actualDiscHeight);
+ g2.setColor(Color.GREEN);
+ g2.fill(rect);
+ g2.setColor(Color.BLACK);
+ g2.draw(rect);
+ }
+ }
+ }
+}
diff --git a/labs/lab07_tohSolver/THFrame.java b/labs/lab07_tohSolver/THFrame.java
new file mode 100644
index 0000000..0c672e2
--- /dev/null
+++ b/labs/lab07_tohSolver/THFrame.java
@@ -0,0 +1,84 @@
+import javax.swing.JFrame;
+
+public class THFrame
+{
+ public static void main(String[] args) throws InterruptedException
+ {
+ int numDiscs = 4;
+ TowerOfHanoi towers = new TowerOfHanoi(numDiscs);
+ THComponent thc = new THComponent(towers);
+
+
+ JFrame frame = new JFrame();
+ frame.setTitle("Tower of Hanoi");
+ frame.setSize(500,500);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ frame.add(thc);
+
+ frame.setVisible(true);
+
+ Thread.sleep(5000);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ }
+}
diff --git a/labs/lab07_tohSolver/THSolverFrame.java b/labs/lab07_tohSolver/THSolverFrame.java
new file mode 100644
index 0000000..53a15bb
--- /dev/null
+++ b/labs/lab07_tohSolver/THSolverFrame.java
@@ -0,0 +1,70 @@
+/*Alexander Pickering
+ *Data Structures Mon. Wed. @ 09:30
+ *Lab 7
+ */
+import javax.swing.JFrame;
+
+public class THSolverFrame
+{
+ public static void main(String[] args) throws InterruptedException
+ {
+ int numberOfDiscs = 10;
+ TowerOfHanoi towers = new TowerOfHanoi(numberOfDiscs);
+ THComponent thc = new THComponent(towers);
+
+
+ JFrame frame = new JFrame();
+ frame.setTitle("Tower of Hanoi");
+ frame.setSize(500,500);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ frame.add(thc);
+
+ frame.setVisible(true);
+
+ //Thread.sleep(5000);
+
+ solveTower(towers, thc,numberOfDiscs);
+
+ System.out.println("DONE!!!");
+ }
+
+ public static void solveTower(TowerOfHanoi towers, THComponent thc, int numPlates) throws InterruptedException
+ {
+ movePlateAndUp(towers,0,numPlates,2,thc);
+ }
+ private static void movePlateAndUp(TowerOfHanoi towers, int towerfrom, int depth, int towerto, THComponent thc) throws InterruptedException
+ {
+ if(depth == 1)
+ {
+ //We are the top block
+ towers.moveTopDisc(towerfrom,towerto);
+ animate(thc);
+ }
+ else
+ {
+ //Find a tower to put everything on top of
+ int unusedTower = 0;
+ if(towerfrom == 0 || towerto == 0)
+ {
+ unusedTower = 1;
+ if(towerfrom == 1 || towerto == 1)
+ {
+ unusedTower = 2;
+ }
+ }
+ //Move everything on top of what we want to move somewhere else
+ movePlateAndUp(towers,towerfrom,depth-1,unusedTower,thc);
+ //Move us
+ towers.moveTopDisc(towerfrom,towerto);
+ animate(thc);
+ //Move everything that was on top of use back on top of us
+ movePlateAndUp(towers,unusedTower,depth-1,towerto,thc);
+ }
+ }
+ private static void animate(THComponent thc) throws InterruptedException
+ {
+ thc.repaint();
+ Thread.sleep(50);
+ }
+}
diff --git a/labs/lab07_tohSolver/TowerOfHanoi.java b/labs/lab07_tohSolver/TowerOfHanoi.java
new file mode 100644
index 0000000..76b673d
--- /dev/null
+++ b/labs/lab07_tohSolver/TowerOfHanoi.java
@@ -0,0 +1,170 @@
+
+public class TowerOfHanoi
+{
+ // TO DO: Instance Variables
+ private HStack towers[] = new HStack[3];
+ private int numDiscs;
+ /* Construct the Towers of Hanoi (3 towers) with aNumDisc
+ * on the first tower. Each tower can be identified by an
+ * integer number (0 for the first tower, 1 for the second
+ * tower, and 2 for the third tower). Each disc can be identified
+ * by an integer number starting from 0 (for the smallest disc)
+ * and (aNumDisc - 1) for the largest disc.
+ */
+ public TowerOfHanoi(int aNumDiscs)
+ {
+ towers[0] = new HStack();
+ towers[1] = new HStack();
+ towers[2] = new HStack();
+ for(int i = 1; i <= aNumDiscs; i++)
+ {
+ towers[0].push(aNumDiscs-i);
+ }
+ numDiscs = aNumDiscs;
+ }
+
+ /* Returns an array of integer representing the order of
+ * discs on the tower (from bottom up). The bottom disc should
+ * be the first element in the array and the top disc should be
+ * the last element of the array. The size of the array MUST
+ * be the number of discs on the tower. For example, suppose
+ * the tower 0 contains the following discs 0,1,4,6,7,8 (from top
+ * to bottom). This method should return the array [8,7,6,4,1,0]
+ * (from first to last).
+ * @param tower the integer identify the tower number.
+ * @return an array of integer representing the order of discs.
+ */
+ public int[] getArrayOfDiscs(int tower)
+ {
+ return towers[tower].toArray();
+ }
+
+ /* Gets the total number of discs in this Towers of Hanoi
+ * @return the total number of discs in this Towers of Hanoi
+ */
+ public int getNumberOfDiscs()
+ {
+ // TO DO
+ return numDiscs;
+ }
+
+ /* Gets the number of discs on a tower.
+ * @param tower the tower identifier (0, 1, or 2)
+ * @return the number of discs on the tower.
+ */
+ public int getNumberOfDiscs(int tower)
+ {
+ return towers[tower].getLength();
+ }
+
+ /* Moves the top disc from fromTower to toTower. Note that
+ * this operation has to follow the rule of the Tower of Hanoi
+ * puzzle. First fromTower must have at least one disc and second
+ * the top disc of toTower must not be smaller than the top disc
+ * of the fromTower.
+ * @param fromTower the source tower
+ * @param toTower the destination tower
+ * @return ture if successfully move the top disc from
+ * fromTower to toTower.
+ */
+ public boolean moveTopDisc(int fromTower, int toTower)
+ {
+ if(towers[fromTower].getLength() == 0)
+ {
+ return false;
+ }
+ if(towers[toTower].getLength() == 0)
+ {
+ towers[toTower].push(towers[fromTower].pop());
+ return true;
+ }
+ else if(towers[fromTower].peek() < towers[toTower].peek())
+ {
+ towers[toTower].push(towers[fromTower].pop());
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ public String toString()
+ {
+ String s = "[" + towers[0].toString() + "," + towers[1].toString() + "," + towers[2].toString() + "]";
+ return s;
+ }
+
+ public class HStack
+ {
+ private HNode head;
+ private int length;
+ public HStack()
+ {
+ length = 0;
+ }
+ public int peek()
+ {
+ return head.getData();
+ }
+ public int pop()
+ {
+ int output = head.getData();
+ head = head.getNext();
+ length--;
+ return output;
+ }
+ public void push(int i)
+ {
+ head = new HNode(i,head);
+ length++;
+ }
+ public boolean hasNext()
+ {
+ return head != null;
+ }
+ public int getLength()
+ {
+ return length;
+ }
+ public String toString()
+ {
+ String output = "";
+ for(HNode tmp = head; tmp != null; tmp=tmp.getNext())
+ {
+ output += tmp.getData() + " ";
+ }
+ return output;
+ }
+ public int[] toArray()
+ {
+ int[] output = new int[length];
+ int i = length-1;
+ for(HNode tmp = head; tmp != null; tmp = tmp.getNext())
+ {
+ output[i] = tmp.getData();
+ i--;
+ }
+ return output;
+ }
+
+ }
+ public class HNode
+ {
+ private HNode next = null;
+ private int data;
+ public HNode(int d, HNode n)
+ {
+ data = d;
+ next = n;
+ }
+ public int getData()
+ {
+ return data;
+ }
+ public HNode getNext()
+ {
+ return next;
+ }
+ }
+}
diff --git a/labs/lab07_tohSolver/lab07_solveTower.pdf b/labs/lab07_tohSolver/lab07_solveTower.pdf
new file mode 100644
index 0000000..c8d02f9
--- /dev/null
+++ b/labs/lab07_tohSolver/lab07_solveTower.pdf
Binary files differ
diff --git a/labs/lab08_gnome_sort/SortingFrame.java b/labs/lab08_gnome_sort/SortingFrame.java
new file mode 100644
index 0000000..6ceb49e
--- /dev/null
+++ b/labs/lab08_gnome_sort/SortingFrame.java
@@ -0,0 +1,106 @@
+import java.util.Random;
+
+import javax.swing.JFrame;
+
+public class SortingFrame
+{
+ public static void main(String[] args) throws InterruptedException
+ {
+ JFrame frame = new JFrame();
+
+ int[] data = randomIntArray(40);
+ VisualSortingComponent vsc = new VisualSortingComponent(data);
+ frame.setTitle("Sorting Visualization");
+ frame.setSize(500,500);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.add(vsc);
+ frame.setVisible(true);
+
+ Thread.sleep(50);
+
+ //bubbleSort(data,vsc);
+ gnomeSort(data,vsc);
+
+ }
+
+ public static void bubbleSort(int[] data, VisualSortingComponent vsc) throws InterruptedException
+ {
+ int size = data.length;
+
+ for(int i = 0; i < size; i++)
+ {
+ for(int j = 0; j < size - 1; j++)
+ {
+ if(data[j] > data[j + 1])
+ {
+ int temp = data[j];
+ data[j] = data[j + 1];
+ data[j + 1] = temp;
+ vsc.repaint();
+ Thread.sleep(10);
+ }
+ }
+ }
+ }
+
+ public static void gnomeSort(int[] data, VisualSortingComponent vsc) throws InterruptedException
+ {
+ int last = data[0];
+ for(int i = 1; i < data.length; i++)
+ {
+ //System.out.println("Sorting " + i);
+ if(data[i] < last)
+ {
+ //System.out.println("\tDoing work");
+ //The data is out of order, do some work
+ int j = i;
+ while(j>0)
+ {
+ if(data[j-1]>data[j])
+ {
+ //System.out.println("\tSwaping " + (j-1) + " and " + j);
+ data = swap(data,j-1,j);
+ j--;
+ vsc.repaint();
+ Thread.sleep(10);
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+ last = data[i];
+ }
+ }
+ private static int[] swap(int[] data, int ind1, int ind2)
+ {
+ int tmp = data[ind1];
+ data[ind1] = data[ind2];
+ data[ind2] = tmp;
+ return data;
+ }
+
+ public static int[] randomIntArray(int size)
+ {
+ int[] result = new int[size];
+
+ for(int i = 1; i <= size; i++)
+ {
+ result[i - 1] = i;
+ }
+
+ Random rand = new Random();
+
+ for(int i = 0; i < size * 100; i++)
+ {
+ int first = rand.nextInt(size);
+ int second = rand.nextInt(size);
+ int temp = result[first];
+ result[first] = result[second];
+ result[second] = temp;
+ }
+
+ return result;
+ }
+}
diff --git a/labs/lab08_gnome_sort/VisualSortingComponent.java b/labs/lab08_gnome_sort/VisualSortingComponent.java
new file mode 100644
index 0000000..92152b8
--- /dev/null
+++ b/labs/lab08_gnome_sort/VisualSortingComponent.java
@@ -0,0 +1,78 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Line2D;
+import java.awt.geom.Rectangle2D;
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class VisualSortingComponent extends JComponent
+{
+ private int leftMargin = 10;
+ private int rightMargin = 10;
+ private int topMargin = 10;
+ private int bottomMargin = 10;
+ private int max;
+ private int min;
+ private int width;
+ private int height;
+ private int[] data;
+ private int numData;
+
+ public VisualSortingComponent(int[] aData)
+ {
+ data = aData;
+ numData = data.length;
+
+ if(numData > 0)
+ {
+ max = data[0];
+ min = data[0];
+
+ for(int i = 1; i < numData; i++)
+ {
+ if(data[i] > max)
+ {
+ max = data[i];
+ }
+
+ if(min > data[i])
+ {
+ min = data[i];
+ }
+ }
+ }
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ width = this.getWidth();
+ height = this.getHeight();
+
+ double dataWidth = (width - (leftMargin + rightMargin)) / numData;
+ double heightFactor = (height - (topMargin + bottomMargin)) / numData;
+
+ // draw the base;
+
+ Line2D.Double line = new Line2D.Double(leftMargin, height - bottomMargin, width - leftMargin, height - bottomMargin);
+ g2.draw(line);
+
+ // draw aata
+
+ Rectangle2D.Double rect = new Rectangle2D.Double(0,0,0,0);
+
+ for(int i = 0; i < numData; i++)
+ {
+ double x = leftMargin + (dataWidth * i);
+ double y = (height - bottomMargin) - (heightFactor * data[i]);
+ rect.setRect(x,y,dataWidth,data[i] * heightFactor);
+
+ g2.setColor(Color.GREEN);
+ g2.fill(rect);
+ g2.setColor(Color.BLACK);
+ g2.draw(rect);
+ }
+ }
+}
diff --git a/labs/lab08_gnome_sort/lab08_gnome_sort.pdf b/labs/lab08_gnome_sort/lab08_gnome_sort.pdf
new file mode 100644
index 0000000..24d7d01
--- /dev/null
+++ b/labs/lab08_gnome_sort/lab08_gnome_sort.pdf
Binary files differ
diff --git a/labs/lab09_iterator/Iterator.java b/labs/lab09_iterator/Iterator.java
new file mode 100644
index 0000000..4d64f9e
--- /dev/null
+++ b/labs/lab09_iterator/Iterator.java
@@ -0,0 +1,7 @@
+
+public interface Iterator<T>
+{
+ public boolean hasNext();
+ public T next();
+ public T remove();
+}
diff --git a/labs/lab09_iterator/SListIterator.java b/labs/lab09_iterator/SListIterator.java
new file mode 100644
index 0000000..e58ea6d
--- /dev/null
+++ b/labs/lab09_iterator/SListIterator.java
@@ -0,0 +1,88 @@
+import java.util.NoSuchElementException;
+
+
+public class SListIterator<T>
+{
+ private Node firstNode;
+ private int numberOfEntries;
+
+ public SListIterator()
+ {
+ firstNode = null;
+ numberOfEntries = 0;
+ }
+
+ public void addToFirst(T aData)
+ {
+ firstNode = new Node(aData, firstNode);
+ numberOfEntries++;
+ }
+
+ public T getEntry(int givenPosition)
+ {
+ T result = null;
+
+ if((givenPosition >= 1) && (givenPosition <= numberOfEntries))
+ {
+ result = (getNodeAt(givenPosition)).data;
+ }
+
+ return result;
+ }
+
+ private Node getNodeAt(int givenPosition)
+ {
+ Node currentNode = firstNode;
+
+ for(int counter = 1; counter < givenPosition; counter++)
+ {
+ currentNode = currentNode.next;
+ }
+
+ return currentNode;
+ }
+
+ public Iterator<T> getIterator()
+ {
+ return new IteratorForSList();
+ }
+
+ private class IteratorForSList implements Iterator<T>
+ {
+ Node node;
+
+ private IteratorForSList()
+ {
+ node = firstNode;
+ }
+
+ public boolean hasNext()
+ {
+ return node != null;
+ }
+
+ public T next()
+ {
+ T temp = node.data;
+ node = node.next;
+ return temp;
+ }
+
+ public T remove()
+ {
+ throw new UnsupportedOperationException("remove() is not supported by this iterator");
+ }
+ }
+
+ private class Node
+ {
+ private T data;
+ private Node next;
+
+ private Node(T aData, Node nextNode)
+ {
+ data = aData;
+ next = nextNode;
+ }
+ }
+}
diff --git a/labs/lab09_iterator/SListIteratorTester.java b/labs/lab09_iterator/SListIteratorTester.java
new file mode 100644
index 0000000..b6960b5
--- /dev/null
+++ b/labs/lab09_iterator/SListIteratorTester.java
@@ -0,0 +1,83 @@
+import java.util.Random;
+
+public class SListIteratorTester
+{
+ public static void main(String[] args)
+ {
+ // Construct a list and add entries
+
+ int numberOfData = 50000; // number of data to add to the list
+ int maxDataValue = 10; // number of different values to add to the list
+ int[] getEntryArray = new int[numberOfData];
+ int[] iteratorArray = new int[numberOfData];
+
+ SListIterator<Integer> list = new SListIterator<Integer>();
+
+ Random rand = new Random();
+ rand.setSeed(System.nanoTime());
+
+ System.out.print("Adding data into the list: ");
+
+ for(int i = 0; i < numberOfData; i++)
+ {
+ list.addToFirst(rand.nextInt(maxDataValue));
+ }
+
+ System.out.println("Done");
+
+ System.out.print("Dry run for the method getEntry(): ");
+ for(int i = 1; i <= 10; i++)
+ {
+ list.getEntry(i);
+ }
+ System.out.println("Done");
+
+
+ double startTime; // Start time millisecond
+ double endTime; // End time millisecond
+
+ System.out.print("Time the method getEntry(): ");
+
+ // Timing the method getEntry()
+
+ startTime = System.currentTimeMillis();
+
+ for(int i = 1; i <= numberOfData; i++)
+ {
+ getEntryArray[i - 1] = list.getEntry(i);
+ }
+
+ endTime = System.currentTimeMillis();
+ System.out.println("Done");
+ double getEntryTime = endTime - startTime;
+
+ System.out.print("Time the iterator: ");
+
+ Iterator<Integer> iterator = list.getIterator();
+
+ startTime = System.currentTimeMillis();
+
+ int index = 0;
+
+ while(iterator.hasNext())
+ {
+ iteratorArray[index] = iterator.next();
+ index++;
+ }
+
+ endTime = System.currentTimeMillis();
+ System.out.println("Done");
+ double iteratorTime = endTime - startTime;
+
+ for(int i = 0; i < numberOfData; i++)
+ {
+ if(getEntryArray[i] != iteratorArray[i])
+ {
+ System.out.println("There is something wrong with your iterator.");
+ }
+ }
+
+ System.out.println("The method getEntry() took " + getEntryTime + " milliseconds.");
+ System.out.println("Using iterator took " + iteratorTime + " milliseconds.");
+ }
+} \ No newline at end of file
diff --git a/labs/lab09_iterator/lab09_iterator.pdf b/labs/lab09_iterator/lab09_iterator.pdf
new file mode 100644
index 0000000..c9a43f1
--- /dev/null
+++ b/labs/lab09_iterator/lab09_iterator.pdf
Binary files differ
diff --git a/labs/lab10_tree/BinaryNode.java b/labs/lab10_tree/BinaryNode.java
new file mode 100644
index 0000000..d498b8e
--- /dev/null
+++ b/labs/lab10_tree/BinaryNode.java
@@ -0,0 +1,100 @@
+
+public class BinaryNode<T> implements BinaryNodeInterface<T>
+{
+ private T data;
+ private BinaryNode<T> left;
+ private BinaryNode<T> right;
+
+ public BinaryNode(T dataPortion, BinaryNode<T> leftChild, BinaryNode<T> rightChild)
+ {
+ data = dataPortion;
+ left = leftChild;
+ right = rightChild;
+ }
+
+ public BinaryNode(T dataPortion)
+ {
+ this(dataPortion, null, null);
+ }
+
+ public BinaryNode()
+ {
+ this(null);
+ }
+
+ public T getData()
+ {
+ return data;
+ }
+
+ public void setData(T newData)
+ {
+ data = newData;
+ }
+
+ public BinaryNodeInterface<T> getLeftChild()
+ {
+ return left;
+ }
+
+ public BinaryNodeInterface<T> getRightChild()
+ {
+ return right;
+ }
+
+ public void setLeftChild(BinaryNodeInterface<T> leftChild)
+ {
+ left = (BinaryNode<T>) leftChild;
+ }
+
+ public void setRightChild(BinaryNodeInterface<T> rightChild)
+ {
+ right = (BinaryNode<T>) rightChild;
+ }
+
+ public boolean hasLeftChild()
+ {
+ return left != null;
+ }
+
+ public boolean hasRightChild()
+ {
+ return right != null;
+ }
+
+ public boolean isLeaf()
+ {
+ return left == null && right == null;
+ }
+
+ public int getNumberOfNodes()
+ {
+ int leftNumber = 0;
+ int rightNumber = 0;
+
+ if(left != null)
+ leftNumber = left.getNumberOfNodes();
+
+ if(right != null)
+ rightNumber = right.getNumberOfNodes();
+
+ return 1 + leftNumber + rightNumber;
+ }
+
+ public int getHeight()
+ {
+ return getHeight(this);
+ }
+
+ private int getHeight(BinaryNode<T> node)
+ {
+ int height = 0;
+
+ if(node != null)
+ {
+ height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
+ }
+
+ return height;
+ }
+}
diff --git a/labs/lab10_tree/BinaryNodeInterface.java b/labs/lab10_tree/BinaryNodeInterface.java
new file mode 100644
index 0000000..f3ac7c1
--- /dev/null
+++ b/labs/lab10_tree/BinaryNodeInterface.java
@@ -0,0 +1,15 @@
+
+public interface BinaryNodeInterface<T>
+{
+ public T getData();
+ public void setData(T newData);
+ public BinaryNodeInterface<T> getLeftChild();
+ public BinaryNodeInterface<T> getRightChild();
+ public void setLeftChild(BinaryNodeInterface<T> leftChild);
+ public void setRightChild(BinaryNodeInterface<T> rightChild);
+ public boolean hasLeftChild();
+ public boolean hasRightChild();
+ public boolean isLeaf();
+ public int getNumberOfNodes();
+ public int getHeight();
+}
diff --git a/labs/lab10_tree/ShowPath.java b/labs/lab10_tree/ShowPath.java
new file mode 100644
index 0000000..d7ad05f
--- /dev/null
+++ b/labs/lab10_tree/ShowPath.java
@@ -0,0 +1,293 @@
+/*Alexander Pickering
+ *Doctor Tan
+ *4-10-15
+*/
+
+import java.util.Random;
+
+
+public class ShowPath
+{
+ public static void main(String[] args)
+ {
+ int point = 0;
+ BinaryNodeInterface<Character> root = generateTree();
+
+ System.out.println("Your string returned from the method getAllPaths() is as follows:");
+ String str = getAllPaths(root);
+ System.out.println(str);
+
+ System.out.println("Your result of using the method getPathTo() for every character is as follows:");
+ for(int i = 0; i < 52; i++)
+ {
+ if(i < 26)
+ {
+ System.out.println("Path to " + (char) ('a' + i) + " " + getPathTo(root, (char) ('a' + i)));
+ }
+ else
+ {
+ System.out.println("Path to " + (char) ('A' + (i - 26)) + " " + getPathTo(root, (char) ('A' + (i - 26))));
+ }
+ }
+
+ System.out.println();
+
+ if(!checkGetAllPaths(root, str))
+ {
+ point = point + 5;
+ }
+
+ System.out.println("Your current point is " + point + ".");
+
+ if(!checkGetPathTo(root))
+ {
+ point = point + 5;
+ }
+
+ System.out.println("Your total point is " + point + ".");
+ }
+
+ private static String getAllPaths(final BinaryNodeInterface<Character> root)
+ {
+ return getAllPathsHelper(root,"");
+ }
+ private static String getAllPathsHelper(final BinaryNodeInterface<Character> root,String pre)
+ {
+ String output = "\n";
+ if(root != null)
+ {
+ output += root.getData() + " " + pre;
+ }
+ if(root.hasLeftChild())
+ {
+ output += getAllPathsHelper(root.getLeftChild(),pre+"0");
+ }
+ if(root.hasRightChild())
+ {
+ output += getAllPathsHelper(root.getRightChild(),pre+"1");
+ }
+ return output;
+ }
+
+ private static String getPathTo(final BinaryNodeInterface<Character> root, char c)
+ {
+ return getPathToHelper(root,c,"");
+ }
+ private static String getPathToHelper(final BinaryNodeInterface<Character> root, char c,String cur)
+ {
+ String output = "";
+ if(root != null)
+ {
+ if(root.getData() == c)
+ {
+ return cur;
+ }
+ }
+ if(root.hasLeftChild())
+ {
+ output = getPathToHelper(root.getLeftChild(),c,cur+"0");
+ if(output != "")
+ {
+ return output;
+ }
+ }
+ if(root.hasRightChild())
+ {
+ output = getPathToHelper(root.getRightChild(),c,cur+"1");
+ if(output != "")
+ {
+ return output;
+ }
+ }
+ return output;
+ }
+
+ private static boolean checkGetAllPaths(BinaryNodeInterface<Character> root, String str)
+ {
+ boolean error = false;
+ String[] list = str.split("\n");
+
+ // check for duplicate characters and number of character
+
+ for(int i = 0; i < list.length; i++)
+ {
+ if(!list[i].equals(""))
+ {
+ char c = list[i].charAt(0);
+
+ for(int j = i + 1; j < list.length; j++)
+ {
+ if(!list[j].equals(""))
+ {
+ if(c == list[j].charAt(0))
+ {
+ System.out.println("There are more than one character '" + c + "' in your output string.");
+ error = true;
+ }
+ }
+ }
+ }
+ }
+
+ // Check paths
+
+ for(int i = 0; i < list.length; i++)
+ {
+ String temp = list[i];
+
+ if(!temp.equals(""))
+ {
+ char c = temp.charAt(0);
+ String path = temp.substring(2);
+ BinaryNodeInterface<Character> currentNode = root;
+
+ for(int j = 0; j < path.length(); j++)
+ {
+ if(path.charAt(j) == '0')
+ {
+ currentNode = currentNode.getLeftChild();
+ }
+ else
+ {
+ currentNode = currentNode.getRightChild();
+ }
+ }
+
+ char nodeCharacter = currentNode.getData();
+
+ if(c != nodeCharacter)
+ {
+ System.out.println("The line \"" + list[i] + "\" says the path to the character " + c + " is " + path + ".");
+ System.out.println("But the path " + path + " goes to the node containing the character " + nodeCharacter + ".");
+ error = true;
+ }
+ }
+ }
+
+ System.out.print("Testing the method getAllPath(): ");
+
+ if(!error)
+ {
+ System.out.println("PASS");
+ }
+ else
+ {
+ System.out.println("FAIL");
+ }
+
+ return error;
+ }
+
+ private static boolean checkGetPathTo(BinaryNodeInterface<Character> root)
+ {
+ boolean error = false;
+
+ for(int i = 0; i < 52; i++)
+ {
+ char c;
+
+ if(i < 26)
+ {
+ c = (char) ('a' + i);
+ }
+ else
+ {
+ c = (char) ('A' + (i - 26));
+ }
+
+ String path = getPathTo(root, c);
+ BinaryNodeInterface<Character> currentNode = root;
+
+ for(int j = 0; j < path.length(); j++)
+ {
+ if(path.charAt(j) == '0')
+ {
+ currentNode = currentNode.getLeftChild();
+ }
+ else
+ {
+ currentNode = currentNode.getRightChild();
+ }
+ }
+
+ char nodeCharacter = currentNode.getData();
+
+ if(c != nodeCharacter)
+ {
+ System.out.println("Your method getPathTo() says the path to the character " + c + " is " + path + ".");
+ System.out.println("But the path " + path + " goes to the node containing the character " + nodeCharacter + ".");
+ error = true;
+ }
+ }
+
+ System.out.print("Testing the method getPathTo(): ");
+
+ if(!error)
+ {
+ System.out.println("PASS");
+ }
+ else
+ {
+ System.out.println("FAIL");
+ }
+
+ return error;
+ }
+
+ private static BinaryNodeInterface<Character> generateTree()
+ {
+ char[] charList = new char[52];
+
+ for(int i = 0; i < 52; i++)
+ {
+ if(i < 26)
+ {
+ charList[i] = (char) ('a' + i);
+ }
+ else
+ {
+ charList[i] = (char) ('A' + (i - 26));
+ }
+ }
+
+ Random rand = new Random();
+ rand.setSeed(System.currentTimeMillis());
+
+ for(int i = 0; i < 1000; i++)
+ {
+ int index1 = rand.nextInt(52);
+ int index2 = rand.nextInt(52);
+ char temp = charList[index1];
+ charList[index1] = charList[index2];
+ charList[index2] = temp;
+ }
+
+ BinaryNodeInterface<Character> root = new BinaryNode<Character>(charList[0]);
+ SimpleQueue<BinaryNodeInterface<Character>> queue = new SimpleQueue<BinaryNodeInterface<Character>>();
+ queue.enqueue(root);
+
+ for(int i = 1; i < 52; i++)
+ {
+ BinaryNodeInterface<Character> currentNode = queue.getFront();
+ BinaryNodeInterface<Character> newNode = new BinaryNode<Character>(charList[i]);
+
+ if(!currentNode.hasLeftChild())
+ {
+ currentNode.setLeftChild(newNode);
+ }
+ else if(!currentNode.hasRightChild())
+ {
+ currentNode.setRightChild(newNode);
+ }
+ else
+ {
+ queue.dequeue();
+ currentNode = queue.getFront();
+ currentNode.setLeftChild(newNode);
+ }
+ queue.enqueue(newNode);
+ }
+
+ return root;
+ }
+}
diff --git a/labs/lab10_tree/SimpleQueue.java b/labs/lab10_tree/SimpleQueue.java
new file mode 100644
index 0000000..64d7c11
--- /dev/null
+++ b/labs/lab10_tree/SimpleQueue.java
@@ -0,0 +1,72 @@
+
+public class SimpleQueue<T>
+{
+ private Node firstNode;
+ private Node lastNode;
+
+ public SimpleQueue()
+ {
+ firstNode = null;
+ lastNode = null;
+ }
+
+ public void enqueue(T newEntry)
+ {
+ Node newNode = new Node(newEntry);
+
+ if(firstNode == null)
+ {
+ firstNode = newNode;
+ lastNode = newNode;
+ }
+ else
+ {
+ lastNode.next = newNode;
+ lastNode = newNode;
+ }
+ }
+
+ public T dequeue()
+ {
+ T result = null;
+
+ if(firstNode != null)
+ {
+ result = firstNode.data;
+ if(lastNode == firstNode)
+ {
+ lastNode = null;
+ }
+ firstNode = firstNode.next;
+ }
+
+ return result;
+ }
+
+ public T getFront()
+ {
+ if(firstNode != null)
+ {
+ return firstNode.data;
+ }
+
+ return null;
+ }
+
+ private class Node
+ {
+ private T data;
+ private Node next;
+
+ public Node(T aData, Node nextNode)
+ {
+ data = aData;
+ next = nextNode;
+ }
+
+ public Node(T aData)
+ {
+ this(aData, null);
+ }
+ }
+}
diff --git a/labs/lab10_tree/lab10_tree.pdf b/labs/lab10_tree/lab10_tree.pdf
new file mode 100644
index 0000000..06dcb2a
--- /dev/null
+++ b/labs/lab10_tree/lab10_tree.pdf
Binary files differ
diff --git a/labs/lab6_toh/THComponent.java b/labs/lab6_toh/THComponent.java
new file mode 100644
index 0000000..3a61dc5
--- /dev/null
+++ b/labs/lab6_toh/THComponent.java
@@ -0,0 +1,113 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Rectangle2D;
+import java.util.Random;
+
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class THComponent extends JComponent
+{
+ private int width;
+ private int height;
+ private int leftMargin = 10;
+ private int rightMargin = 10;
+ private int topMargin = 10;
+ private int bottomMargin = 10;
+ private int baseHeight = 10;
+ private double poleWidth = 10;
+ private TowerOfHanoi towers;
+ private int numberOfDiscs;
+ private double largestDiscSize;
+ private double smallestDiscSize = 20;
+ private double defaultReductionSize = 20.0;
+ private double defaultDiscHeight = 20.0;
+ private double[] discSizes;
+
+ public THComponent(TowerOfHanoi aTowers)
+ {
+ towers = aTowers;
+ numberOfDiscs = towers.getNumberOfDiscs();
+ discSizes = new double[numberOfDiscs];
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ width = this.getWidth();
+ height = this.getHeight();
+
+ int drawingWidth = width - (leftMargin + rightMargin);
+ int drawingHeight = height - (topMargin + bottomMargin);
+
+ // draw the base;
+
+ Rectangle2D.Double rect = new Rectangle2D.Double(leftMargin , height - (bottomMargin + baseHeight), drawingWidth, baseHeight);
+ g2.draw(rect);
+
+ // draw poles;
+
+ double halfDistance = ((double) drawingWidth / 6);
+ largestDiscSize = (halfDistance * 2) - poleWidth;
+
+ for(int i = 1; i <= 5; i = i + 2)
+ {
+ rect.setRect((leftMargin + (halfDistance * i)) - (poleWidth / 2), topMargin, poleWidth, drawingHeight - baseHeight);
+ g2.draw(rect);
+ }
+
+ // draw discs
+
+ double totalReduction = (largestDiscSize - smallestDiscSize) / (numberOfDiscs - 1);
+ double actualReduction;
+
+ if(totalReduction > defaultReductionSize)
+ {
+ actualReduction = defaultReductionSize;
+ }
+ else
+ {
+ actualReduction = totalReduction;
+ }
+
+ double totalHeight = drawingHeight - baseHeight;
+ double tempDiscHeight = totalHeight / (numberOfDiscs + 1);
+ double actualDiscHeight;
+
+ if(tempDiscHeight > defaultDiscHeight)
+ {
+ actualDiscHeight = defaultDiscHeight;
+ }
+ else
+ {
+ actualDiscHeight = tempDiscHeight;
+ }
+
+ for(int i = 0; i < numberOfDiscs; i++)
+ {
+ discSizes[i] = largestDiscSize - (actualReduction * ((numberOfDiscs - 1) - i));
+ }
+
+ int[][] t = new int[3][];
+ for(int i = 0; i < 3; i++)
+ {
+ t[i] = towers.getArrayOfDiscs(i);
+ }
+
+ for(int i = 0; i <= 2; i++)
+ {
+ for(int j = 0; j < t[i].length; j++)
+ {
+ double x = (leftMargin + (halfDistance * (1 + (2 * i)))) - (discSizes[t[i][j]] / 2);
+ double y = ((topMargin + drawingHeight) - baseHeight) - (actualDiscHeight * (j + 1));
+ rect.setRect(x,y,discSizes[t[i][j]],actualDiscHeight);
+ g2.setColor(Color.GREEN);
+ g2.fill(rect);
+ g2.setColor(Color.BLACK);
+ g2.draw(rect);
+ }
+ }
+ }
+}
diff --git a/labs/lab6_toh/THFrame.java b/labs/lab6_toh/THFrame.java
new file mode 100644
index 0000000..0c672e2
--- /dev/null
+++ b/labs/lab6_toh/THFrame.java
@@ -0,0 +1,84 @@
+import javax.swing.JFrame;
+
+public class THFrame
+{
+ public static void main(String[] args) throws InterruptedException
+ {
+ int numDiscs = 4;
+ TowerOfHanoi towers = new TowerOfHanoi(numDiscs);
+ THComponent thc = new THComponent(towers);
+
+
+ JFrame frame = new JFrame();
+ frame.setTitle("Tower of Hanoi");
+ frame.setSize(500,500);
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ frame.add(thc);
+
+ frame.setVisible(true);
+
+ Thread.sleep(5000);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(2, 0);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 1);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(0, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ towers.moveTopDisc(1, 2);
+ thc.repaint();
+ Thread.sleep(500);
+
+ }
+}
diff --git a/labs/lab6_toh/TowerOfHanoi.java b/labs/lab6_toh/TowerOfHanoi.java
new file mode 100644
index 0000000..51a394c
--- /dev/null
+++ b/labs/lab6_toh/TowerOfHanoi.java
@@ -0,0 +1,164 @@
+
+public class TowerOfHanoi
+{
+ // TO DO: Instance Variables
+ private HStack towers[] = new HStack[3];
+ private int numDiscs;
+ /* Construct the Towers of Hanoi (3 towers) with aNumDisc
+ * on the first tower. Each tower can be identified by an
+ * integer number (0 for the first tower, 1 for the second
+ * tower, and 2 for the third tower). Each disc can be identified
+ * by an integer number starting from 0 (for the smallest disc)
+ * and (aNumDisc - 1) for the largest disc.
+ */
+ public TowerOfHanoi(int aNumDiscs)
+ {
+ towers[0] = new HStack();
+ towers[1] = new HStack();
+ towers[2] = new HStack();
+ for(int i = 1; i <= aNumDiscs; i++)
+ {
+ towers[0].push(aNumDiscs-i);
+ }
+ numDiscs = aNumDiscs;
+ }
+
+ /* Returns an array of integer representing the order of
+ * discs on the tower (from bottom up). The bottom disc should
+ * be the first element in the array and the top disc should be
+ * the last element of the array. The size of the array MUST
+ * be the number of discs on the tower. For example, suppose
+ * the tower 0 contains the following discs 0,1,4,6,7,8 (from top
+ * to bottom). This method should return the array [8,7,6,4,1,0]
+ * (from first to last).
+ * @param tower the integer identify the tower number.
+ * @return an array of integer representing the order of discs.
+ */
+ public int[] getArrayOfDiscs(int tower)
+ {
+ return towers[tower].toArray();
+ }
+
+ /* Gets the total number of discs in this Towers of Hanoi
+ * @return the total number of discs in this Towers of Hanoi
+ */
+ public int getNumberOfDiscs()
+ {
+ // TO DO
+ return numDiscs;
+ }
+
+ /* Gets the number of discs on a tower.
+ * @param tower the tower identifier (0, 1, or 2)
+ * @return the number of discs on the tower.
+ */
+ public int getNumberOfDiscs(int tower)
+ {
+ return towers[tower].getLength();
+ }
+
+ /* Moves the top disc from fromTower to toTower. Note that
+ * this operation has to follow the rule of the Tower of Hanoi
+ * puzzle. First fromTower must have at least one disc and second
+ * the top disc of toTower must not be smaller than the top disc
+ * of the fromTower.
+ * @param fromTower the source tower
+ * @param toTower the destination tower
+ * @return ture if successfully move the top disc from
+ * fromTower to toTower.
+ */
+ public boolean moveTopDisc(int fromTower, int toTower)
+ {
+ if(towers[fromTower].getLength() == 0)
+ {
+ return false;
+ }
+ if(towers[toTower].getLength() == 0)
+ {
+ towers[toTower].push(towers[fromTower].pop());
+ return true;
+ }
+ else if(towers[fromTower].peek() < towers[toTower].peek())
+ {
+ towers[toTower].push(towers[fromTower].pop());
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ public class HStack
+ {
+ private HNode head;
+ private int length;
+ public HStack()
+ {
+ length = 0;
+ }
+ public int peek()
+ {
+ return head.getData();
+ }
+ public int pop()
+ {
+ int output = head.getData();
+ head = head.getNext();
+ length--;
+ return output;
+ }
+ public void push(int i)
+ {
+ head = new HNode(i,head);
+ length++;
+ }
+ public boolean hasNext()
+ {
+ return head != null;
+ }
+ public int getLength()
+ {
+ return length;
+ }
+ public String toString()
+ {
+ String output = "";
+ for(HNode tmp = head; tmp != null; tmp=tmp.getNext())
+ {
+ output += tmp.getData() + " ";
+ }
+ return output;
+ }
+ public int[] toArray()
+ {
+ int[] output = new int[length];
+ int i = length-1;
+ for(HNode tmp = head; tmp != null; tmp = tmp.getNext())
+ {
+ output[i] = tmp.getData();
+ i--;
+ }
+ return output;
+ }
+
+ }
+ public class HNode
+ {
+ private HNode next = null;
+ private int data;
+ public HNode(int d, HNode n)
+ {
+ data = d;
+ next = n;
+ }
+ public int getData()
+ {
+ return data;
+ }
+ public HNode getNext()
+ {
+ return next;
+ }
+ }
+}
diff --git a/labs/lab6_toh/TowersTester.java b/labs/lab6_toh/TowersTester.java
new file mode 100644
index 0000000..c8aed2f
--- /dev/null
+++ b/labs/lab6_toh/TowersTester.java
@@ -0,0 +1,185 @@
+
+public class TowersTester
+{
+ public static void main(String[] args)
+ {
+ int numDiscs = 7;
+ int point = 0;
+
+ TowerOfHanoi t = new TowerOfHanoi(numDiscs);
+
+ // Testing the method getNumberOfDiscs()
+
+ System.out.println("Construct the Table of Hanoi puzzle with 7 disks using the following statement:");
+ System.out.println(" TowerOfHanoi t = new TowerOfHanoi(7);");
+ System.out.println("All test will be base on results of manipulating TowerOfHanoi t.\n");
+
+ System.out.print("Testing the method getNumberOfDiscs(): ");
+
+ if(t.getNumberOfDiscs() != numDiscs)
+ {
+ System.out.println("FAIL");
+ System.out.println("The method getNumberOfDiscs() should return " + numDiscs + ".");
+ System.out.println("But your method getNumberOfDiscs() returns " + t.getNumberOfDiscs() + ".\n");
+ }
+ else
+ {
+ point++;
+ System.out.println("PASS");
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Testing initial puzzle
+
+ System.out.println("Testing initial puzzle");
+
+ int[][] tower0 = {{6,5,4,3,2,1,0},{},{}};
+
+ int[] nd0 = {7,0,0};
+
+ if(testPuzzle(t, nd0, tower0))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ System.out.println("Move top disc from tower 0 to tower 1");
+ if(testMTD(t.moveTopDisc(0, 1), true, 0, 1))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+ System.out.println("Testing the current puzzle");
+ int[][] tower1 = {{6,5,4,3,2,1},{0},{}};
+ int[] nd1 = {6,1,0};
+ if(testPuzzle(t, nd1, tower1))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Move
+
+ System.out.println("Move top disc from tower 0 to tower 2");
+ if(testMTD(t.moveTopDisc(0, 2), true, 0, 2))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+ System.out.println("Testing the current puzzle");
+ int[][] tower2 = {{6,5,4,3,2},{0},{1}};
+ int[] nd2 = {5,1,1};
+ if(testPuzzle(t, nd2, tower2))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Move
+
+ System.out.println("Move top disc from tower 1 to tower 2");
+ if(testMTD(t.moveTopDisc(1, 2), true, 1, 2))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+ System.out.println("Testing the current puzzle");
+ int[][] tower3 = {{6,5,4,3,2},{},{1,0}};
+ int[] nd3 = {5,0,2};
+ if(testPuzzle(t, nd3, tower3))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ // Move (false)
+
+ System.out.println("Move top disc from tower 0 to tower 2 (MUST RETURN FALSE)");
+ if(testMTD(t.moveTopDisc(0, 2), false, 0, 2))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+ System.out.println("Testing the current puzzle (MUST REMAIN UNCHANGED FROM PREVIOUS TEST)");
+ if(testPuzzle(t, nd3, tower3))
+ {
+ point++;
+ }
+ System.out.println("Your current point is " + point + ".\n");
+
+ }
+
+ private static boolean testMTD(boolean aResult, boolean eResult, int fromTower, int toTower)
+ {
+ System.out.print("Test return value of the method moveTopDisc(): ");
+ if(aResult != eResult)
+ {
+ System.out.println("FAIL");
+ System.out.println("t.moveTopDisc(" + fromTower + "," + toTower + ") should return " + eResult + ".");
+ System.out.println("But your method moveTopDisc(" + fromTower + "," + toTower + ") return " + aResult + ".");
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ return aResult == eResult;
+ }
+
+ private static boolean testPuzzle(TowerOfHanoi t, int[] numDiscs, int[][] tower)
+ {
+ boolean result = true;
+
+ for(int i = 0; i < 3; i++)
+ {
+ System.out.print("Testing the method getNumberOfDiscs(" + i + "): ");
+
+ if(t.getNumberOfDiscs(i) != numDiscs[i])
+ {
+ System.out.println("FAIL");
+ System.out.println("The method getNumberOfDiscs(" + i + ") should return " + numDiscs[i] + ".");
+ System.out.println("But your method getNumberOfDiscs(" + i + ") returns " + t.getNumberOfDiscs(i) + ".\n");
+ result = false;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getArrayOfDiscs(0)
+
+ System.out.print("Testing the method getArrayOfDiscs(" + i + "): ");
+
+ if(!arrayToString(tower[i]).equals(arrayToString(t.getArrayOfDiscs(i))))
+ {
+ System.out.println("FAIL");
+ System.out.println("The method getArrayOfDiscs(" + i + ") should return the array " + arrayToString(tower[i]) + ".");
+ System.out.println("But your method getArrayOfDiscs(" + i + ") returns the array " + arrayToString(t.getArrayOfDiscs(i)) + ".\n");
+ result = false;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ return result;
+ }
+
+ private static String arrayToString(int[] array)
+ {
+ String result = "[";
+
+ if(array.length > 0)
+ {
+ for(int i = 0; i < array.length - 1; i++)
+ {
+ result = result + array[i] + ",";
+ }
+
+ result = result + array[array.length - 1];
+ }
+
+ return result + "]";
+ }
+}
diff --git a/labs/lab6_toh/lab06_towers_of_hanoi.pdf b/labs/lab6_toh/lab06_towers_of_hanoi.pdf
new file mode 100644
index 0000000..6ae3eb0
--- /dev/null
+++ b/labs/lab6_toh/lab06_towers_of_hanoi.pdf
Binary files differ
diff --git a/projects/project1_frequencyBag/CharacterFrequency.java b/projects/project1_frequencyBag/CharacterFrequency.java
new file mode 100644
index 0000000..4bf4a78
--- /dev/null
+++ b/projects/project1_frequencyBag/CharacterFrequency.java
@@ -0,0 +1,34 @@
+import java.util.*;
+import java.io.*;
+
+public class CharacterFrequency
+{
+ public static void main(String[] args)
+ {
+ File f = new File("letter1.txt");
+ Scanner s;
+ try
+ {
+ s = new Scanner(f);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Big error!");
+ return;
+ }
+ FrequencyBag<Character> fb = new FrequencyBag<Character>();
+ while(s.hasNextLine())
+ {
+ String s1 = s.nextLine();
+ for(char c : s1.toCharArray())
+ {
+ fb.add(new Character((char)(c<='Z'&&c>='A'?c+0x20:c)));
+ }
+ }
+ System.out.println("Character: Frequency\n===================");
+ for(int i=0x61;i<=0x7A;i++)
+ {
+ System.out.println((char)i+": "+fb.getFrequencyOf(new Character((char)i)));
+ }
+ }
+} \ No newline at end of file
diff --git a/projects/project1_frequencyBag/FNode.java b/projects/project1_frequencyBag/FNode.java
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/projects/project1_frequencyBag/FNode.java
diff --git a/projects/project1_frequencyBag/FrequencyBag.java b/projects/project1_frequencyBag/FrequencyBag.java
new file mode 100644
index 0000000..3545ff9
--- /dev/null
+++ b/projects/project1_frequencyBag/FrequencyBag.java
@@ -0,0 +1,168 @@
+
+public class FrequencyBag<T>
+{
+ // TO DO: Instance Variables
+ private FNode head;
+ private boolean hasChanged = true;
+ private int max;
+ //Tracks the number of times add has been called
+ private int total;
+ /**
+ * Constructor
+ * Constructs an empty frequency bag.
+ */
+ public FrequencyBag()
+ {
+ head = null;
+ }
+
+ /**
+ * Adds new entry into this frequency bag.
+ * @param aData the data to be added into this frequency bag.
+ */
+ public void add(T aData)
+ {
+ //Add to the start to make add an O(1) operation
+ if(!addhelper(head,aData))
+ {
+ hasChanged = true;
+ FNode n = new FNode(aData,head);
+ head = n;
+ }
+ total++;
+ }
+ public boolean addhelper(FNode head, T data)
+ {
+ if(head == null)
+ {
+ //We haven't found the item in the list, return false
+ return false;
+ }
+ if(head.getObject().equals(data))
+ {
+ head.add();
+ return true;
+ }
+ return addhelper(head.getNext(),data);
+ }
+
+ /**
+ * Gets the number of occurrences of aData in this frequency bag.
+ * @param aData the data to be checked for its number of occurrences.
+ * @return the number of occurrences of aData in this frequency bag.
+ */
+ public int getFrequencyOf(T aData)
+ {
+ return getFrequencyOfHelper(head,aData);
+ }
+
+ public int getFrequencyOfHelper(FNode<T> node,T data)
+ {
+ //If we've hit a null node, the object isn't in the list
+ if(node == null)
+ {
+ return 0;
+ }
+ if(node.getObject().equals(data))
+ {
+ return node.getFrequency();
+ }
+ else
+ {
+ return getFrequencyOfHelper(node.getNext(),data);
+ }
+ }
+ /**
+ * Gets the maximum number of occurrences in this frequency bag.
+ * @return the maximum number of occurrences of an entry in this
+ * frequency bag.
+ */
+ public int getMaxFrequency()
+ {
+ if(hasChanged)
+ {
+ hasChanged = false;
+ max = getMaxFrequencyHelper(head);
+ return max;
+ }
+ else
+ {
+ return max;
+ }
+ }
+ private int getMaxFrequencyHelper(FNode<T> node)
+ {
+ if(node == null) //Were at the end
+ return 0;
+ int nmax = getMaxFrequencyHelper(node.getNext());
+ return node.getFrequency() > nmax?node.getFrequency():nmax;
+ }
+
+ /**
+ * Gets the probability of aData
+ * @param aData the specific data to get its probability.
+ * @return the probability of aData
+ */
+ public double getProbabilityOf(T aData)
+ {
+ return getFrequencyOf(aData)/(total*1.0);
+ }
+
+ /**
+ * Empty this bag.
+ */
+ public void clear()
+ {
+ head = null;
+ hasChanged = true;
+ total = 0;
+ }
+
+ /**
+ * Gets the number of entries in this bag.
+ * @return the number of entries in this bag.
+ */
+ public int size()
+ {
+ return total;
+ }
+ public class FNode<T>
+ {
+ private T object = null;
+ private int frequency = 1;
+ private FNode next = null;
+
+ public FNode()
+ {
+ }
+ public FNode(T obj,FNode n)
+ {
+ object = obj;
+ next = n;
+ }
+ public void setObject(T obj)
+ {
+ object = obj;
+ }
+ public T getObject()
+ {
+ return object;
+ }
+ public void add()
+ {
+ frequency++;
+ }
+ public int getFrequency()
+ {
+ return frequency;
+ }
+ public FNode getNext()
+ {
+ return next;
+ }
+ public void setNext(FNode n)
+ {
+ next = n;
+ }
+ }
+}
diff --git a/projects/project1_frequencyBag/FrequencyBagTester.java b/projects/project1_frequencyBag/FrequencyBagTester.java
new file mode 100644
index 0000000..db1ae99
--- /dev/null
+++ b/projects/project1_frequencyBag/FrequencyBagTester.java
@@ -0,0 +1,531 @@
+import java.util.Random;
+import java.util.Scanner;
+
+public class FrequencyBagTester
+{
+ public static void main(String[] args)
+ {
+ int numberOfData = 20;
+ int maxValueEx = 5;
+ boolean wrongFrequency = false;
+ int failed = 0;
+ Scanner in = new Scanner(System.in);
+ //CHANGE THIS BACK----------------------------------CHANGE THIS BACK-------
+ int option = 1;
+ //CHANGE THIS BACK----------------------------------CHANGE THIS BACK-------
+
+ while(option == 0)
+ {
+ System.out.println("Please select a test option");
+ System.out.println(" 1. Stop the test as soon as an error is detected");
+ System.out.println(" 2. Do not stop the test when an error is detected");
+ System.out.print("Enter an option (1 or 2): ");
+ option = in.nextInt();
+
+ if(option != 1 && option != 2)
+ {
+ System.out.println(option + " is not a valid choice.\n");
+ option = 0;
+ }
+ }
+
+ in.close();
+
+ FrequencyBag<Integer> fb = new FrequencyBag<Integer>();
+
+ // getFrequencyOf() empty bag
+
+ System.out.print("Checking the method getFrequencyOf() of an empty frequency bag: ");
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ if(fb.getFrequencyOf(i) != 0)
+ {
+ if(!wrongFrequency)
+ {
+ System.out.println("FAIL");
+ failed++;
+ }
+ System.out.println("The method getFrequencyOf(" + i + ") of an empty bag should return 0.");
+ System.out.println("But your method getFrequencyOf(" + i + ") returns " + fb.getFrequencyOf(i) + ".");
+ wrongFrequency = true;
+ }
+ }
+
+ if(!wrongFrequency)
+ {
+ System.out.println("PASS");
+ }
+ else if(option == 1)
+ {
+ return;
+ }
+
+
+ // size() of empty bag.
+
+ System.out.print("Checking the method size() of an empty bag: ");
+ if(fb.size() != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The size of an empty bag should be 0.");
+ System.out.println("But your method size() returns " + fb.size() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getMaxFrequency() of empty bag
+
+ System.out.print("Checking the method getMaxFrequency() of an empty frequency bag: ");
+ if(fb.getMaxFrequency() != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The method getMaxFrequency() of an empty bag should return 0.");
+ System.out.println("But your method getMaxFrequency() returns " + fb.getMaxFrequency() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // Adding data into empty bag
+
+ int dataSet[] = new int[5];
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ dataSet[i] = 0;
+ }
+
+ Random rand = new Random();
+
+ System.out.println("Add the following data into your frequency bag (in that order):");
+
+ for(int i = 0; i < numberOfData; i++)
+ {
+ int temp = rand.nextInt(maxValueEx);
+
+ System.out.print(temp + " ");
+ fb.add(temp);
+ dataSet[temp]++;
+ }
+ System.out.println();
+
+ // getFrequencyOf()
+
+ System.out.println("Checking the method getFrequencyOf() of each data in this frequency bag: ");
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ System.out.print("Frequency of " + i + ": ");
+ if(fb.getFrequencyOf(i) != dataSet[i])
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The frequency of " + i + " is " + dataSet[i] + ".");
+ System.out.println("But the method getFrequencyOf(" + i + ") returns " + fb.getFrequencyOf(i) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ // getFrequencyOf()
+
+ System.out.print("Checking the method getFrequencyOf() of a data that is not in this frequency bag: ");
+
+ if(fb.getFrequencyOf(-1) != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The frequency of -1 is 0.");
+ System.out.println("But the method getFrequencyOf(-1) returns " + fb.getFrequencyOf(-1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getProbabilityOf()
+
+ System.out.println("Checking the method getProbabilityOf() of each data in this frequency bag: ");
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ System.out.print("Probability of " + i + ": ");
+ if(Math.abs(fb.getProbabilityOf(i) - ((double) dataSet[i]/numberOfData)) > 0.000001)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The probability of " + i + " is " + ((double) dataSet[i]/numberOfData) + ".");
+ System.out.println("But the method getProbabilityOf(" + i + ") returns " + fb.getProbabilityOf(i) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+ }
+
+ // getProbabilityOf()
+
+ System.out.print("Checking the method getProbabilityOf() of a data that is not in this frequency bag: ");
+
+ if(fb.getProbabilityOf(-1) != 0.0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The probability of -1 is 0.");
+ System.out.println("But the method getProbabilityOf(-1) returns " + fb.getProbabilityOf(-1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // size()
+
+ System.out.print("Checking the method size() of this non-empty frequency bag: ");
+ if(fb.size() != numberOfData)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After adding " + numberOfData + " entries, the method size() should return " + numberOfData + ".");
+ System.out.println("But your method size() returns " + fb.size() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getMaxFrequency()
+
+ System.out.print("Checking the method getMaxFrequency() of this non-empty frequency bag: ");
+
+ int tempMax = 0;
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ if(tempMax < dataSet[i])
+ {
+ tempMax = dataSet[i];
+ }
+ }
+
+ if(fb.getMaxFrequency() != tempMax)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The method getMaxFrequency() of this non-empty frequency bag should return " + tempMax + ".");
+ System.out.println("But your method getMaxFrequency() of this non-empty frequency bag returns " + fb.getMaxFrequency() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // clear();
+
+ fb.clear();
+
+ System.out.println("Checking the method clear()");
+ System.out.print("Checking the method size() after clear(): ");
+ if(fb.size() != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After the bag is cleared, the method size() should return 0.");
+ System.out.println("But your method size() returns " + fb.size() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getFrequencyOf() after clear()
+
+ System.out.print("Checking the method getFrequencyOf(3) after clear(): ");
+ if(fb.getFrequencyOf(3) != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After the bag is cleared, the method getFrequencyOf(3) should return 0.");
+ System.out.println("But your method getFrequencyOf(3) returns " + fb.getFrequencyOf(3) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getMaxFrequency() after clear()
+
+ System.out.print("Checking the method getMaxFrequency() after clear(): ");
+ if(fb.getMaxFrequency() != 0)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After the bag is cleared, the method getMaxFrequency() should return 0.");
+ System.out.println("But your method getMaxFrequency() returns " + fb.getMaxFrequency() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Generate large bag
+
+ numberOfData = 1000000;
+ maxValueEx = 1000;
+
+ dataSet = new int[maxValueEx];
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ dataSet[i] = 0;
+ }
+
+ System.out.println("\nSo far so good.");
+ System.out.println("Let's try adding " + numberOfData + " data into your frequency bag.");
+
+ for(int i = 0; i < numberOfData; i++)
+ {
+ int temp = rand.nextInt(maxValueEx);
+
+ fb.add(temp);
+ dataSet[temp]++;
+ }
+
+ // size() of large bag.
+
+ System.out.print("Checking the method size() of this non-empty frequency bag: ");
+ if(fb.size() != numberOfData)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After adding " + numberOfData + " entries, the method size() should return " + numberOfData + ".");
+ System.out.println("But your method size() returns " + fb.size() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getFrequencyOf() of large bag
+
+ System.out.print("Checking the method getFrequencyOf() of each data in this frequency bag: ");
+
+ wrongFrequency = false;
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ if(fb.getFrequencyOf(i) != dataSet[i])
+ {
+ wrongFrequency = true;
+ }
+ }
+
+ if(wrongFrequency)
+ {
+ failed++;
+ System.out.println("FAIL");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getProbabilityOf() of large bag
+
+ System.out.print("Checking the method getProbabilityOf() of each data in this frequency bag: ");
+
+ boolean wrongProbability = false;
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ if(Math.abs(fb.getProbabilityOf(i) - ((double) dataSet[i]/numberOfData)) > 0.000001)
+ {
+ wrongProbability = true;
+ }
+ }
+
+ if(wrongProbability)
+ {
+ failed++;
+ System.out.println("FAIL");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // getMaxFrequency() of large bag
+
+ System.out.print("Checking the method getMaxFrequency() of this non-empty frequency bag: ");
+
+ tempMax = 0;
+
+ for(int i = 0; i < maxValueEx; i++)
+ {
+ if(tempMax < dataSet[i])
+ {
+ tempMax = dataSet[i];
+ }
+ }
+
+ if(fb.getMaxFrequency() != tempMax)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The method getMaxFrequency() of this non-empty frequency bag should return " + tempMax + ".");
+ System.out.println("But your method getMaxFrequency() of this non-empty frequency bag returns " + fb.getMaxFrequency() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Frequency Bag of String
+
+ System.out.println("\nSo far so good.");
+ System.out.println("Let's construct a frequency bag of String.");
+
+ FrequencyBag<String> sfb = new FrequencyBag<String>();
+
+ String s = "hello how are you i am find thank you and you i am fine thank you";
+ String[] str = s.split(" ");
+
+ for(int i = 0; i < str.length; i++)
+ {
+ sfb.add(str[i]);
+ }
+
+ System.out.println("Adding the following strings into an empty frequency bag:");
+ System.out.println(s + "\n");
+
+ System.out.print("Checking the method size() of this non-empty frequency bag: ");
+ if(sfb.size() != 16)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("After adding 16 entries, the method size() should return 16.");
+ System.out.println("But your method size() returns " + sfb.size() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Checking the method getFrequencyOf(\"am\"): ");
+ if(sfb.getFrequencyOf("am") != 2)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("There are two strings \"am\" added into this bag.");
+ System.out.println("But your method getFrequencyOf(\"am\") returns " + sfb.getFrequencyOf("am") + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Checking the method getMaxFrequency(): ");
+ if(sfb.getMaxFrequency() != 4)
+ {
+ failed++;
+ System.out.println("FAIL");
+ System.out.println("The maximum frequency should be 4 (the string \"you\").");
+ System.out.println("But your method getMaxFrequency() returns " + sfb.getMaxFrequency() + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.println();
+
+ if(failed != 0)
+ {
+ System.out.println("Threre are " + failed + " in this test. Fix your program.");
+ }
+ else
+ {
+ System.out.println("Congratulation!!! Your FrequencyBag works perfectly (I hope).");
+ System.out.println("Run the program FrequencyFrame and compare its result.");
+ }
+ }
+}
diff --git a/projects/project1_frequencyBag/FrequencyFrame.java b/projects/project1_frequencyBag/FrequencyFrame.java
new file mode 100644
index 0000000..bc26e1a
--- /dev/null
+++ b/projects/project1_frequencyBag/FrequencyFrame.java
@@ -0,0 +1,72 @@
+import java.awt.BorderLayout;
+import java.awt.GridLayout;
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.border.TitledBorder;
+
+
+public class FrequencyFrame
+{
+ public static void main(String[] args) throws InterruptedException
+ {
+ JFrame frame = new JFrame();
+
+ FrequencyBag<Integer> normal = new FrequencyBag<Integer>();
+ FrequencyBag<Integer> laplace = new FrequencyBag<Integer>();
+ FrequencyBag<Integer> uniform = new FrequencyBag<Integer>();
+ FrequencyBag<Integer> clock = new FrequencyBag<Integer>();
+
+ FrequencyGraphComponent normalFC = new FrequencyGraphComponent(normal, -500, 500, 1);
+ FrequencyGraphComponent laplaceFC = new FrequencyGraphComponent(laplace, -500, 500, 1);
+ FrequencyGraphComponent uniformFC = new FrequencyGraphComponent(uniform, -500, 500, 1);
+ FrequencyGraphComponent clockFC = new FrequencyGraphComponent(clock, 0, 1000, 1);
+
+ JPanel normalPanel = new JPanel();
+ normalPanel.setLayout(new BorderLayout());
+ normalPanel.setBorder(new TitledBorder("Normal Distribution"));
+ normalPanel.add(normalFC);
+
+ JPanel laplacePanel = new JPanel();
+ laplacePanel.setLayout(new BorderLayout());
+ laplacePanel.setBorder(new TitledBorder("Laplace Distribution"));
+ laplacePanel.add(laplaceFC);
+
+ JPanel uniformPanel = new JPanel();
+ uniformPanel.setLayout(new BorderLayout());
+ uniformPanel.setBorder(new TitledBorder("Uniform Distribution"));
+ uniformPanel.add(uniformFC);
+
+ JPanel clockPanel = new JPanel();
+ clockPanel.setLayout(new BorderLayout());
+ clockPanel.setBorder(new TitledBorder("Clock Distributioin"));
+ clockPanel.add(clockFC);
+
+ frame.setSize(800,800);
+ frame.setTitle("Probability Distributions");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setLayout(new GridLayout(2,2));
+ frame.add(normalPanel);
+ frame.add(laplacePanel);
+ frame.add(uniformPanel);
+ frame.add(clockPanel);
+ frame.setVisible(true);
+
+ for(int i = 0; i < 20000; i++)
+ {
+ for(int j = 0; j < 10; j++)
+ {
+ normal.add(RandomDistribution.normalDistributionInt(-500, 500));
+ laplace.add(RandomDistribution.laplaceDistributionInt(-500, 500));
+ uniform.add(RandomDistribution.uniformDistributionInt(-500, 500));
+ clock.add(RandomDistribution.clockDistribution(0, 1000, 50, 50));
+ }
+ normalFC.repaint();
+ laplaceFC.repaint();
+ uniformFC.repaint();
+ clockFC.repaint();
+ Thread.sleep(1);
+ }
+ }
+
+}
diff --git a/projects/project1_frequencyBag/FrequencyGraphComponent.java b/projects/project1_frequencyBag/FrequencyGraphComponent.java
new file mode 100644
index 0000000..3d48c74
--- /dev/null
+++ b/projects/project1_frequencyBag/FrequencyGraphComponent.java
@@ -0,0 +1,71 @@
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.geom.Line2D;
+
+import javax.swing.JComponent;
+
+@SuppressWarnings("serial")
+public class FrequencyGraphComponent extends JComponent
+{
+ private FrequencyBag<Integer> fb;
+ private int min;
+ private int max;
+ private int delta;
+ private int width;
+ private int height;
+ private int leftMargin = 10;
+ private int rightMargin = 10;
+ private int topMargin = 10;
+ private int bottomMargin = 10;
+
+ public FrequencyGraphComponent(FrequencyBag<Integer> afb, int aMin, int aMax, int aDelta)
+ {
+ fb = afb;
+ min = aMin;
+ max = aMax;
+ delta = aDelta;
+ }
+
+ public void paintComponent(Graphics g)
+ {
+ Graphics2D g2 = (Graphics2D) g;
+
+ g2.setColor(Color.BLACK);
+
+ width = this.getWidth();
+ height = this.getHeight();
+
+ int maxFrequency = fb.getMaxFrequency();
+ double deltaWidth = (double) (width - (leftMargin + rightMargin)) / ((max - min) / delta);
+ double deltaHeight = (double) (height - (topMargin + bottomMargin)) / maxFrequency;
+
+ Line2D.Double line = new Line2D.Double(0,0,0,0);
+
+ for(int i = min; i < max; i = i + delta)
+ {
+ double sx = ((i - min) * deltaWidth) + leftMargin;
+ double ex = (((i + delta) - min) * deltaWidth) + leftMargin;
+ double sy = (height - bottomMargin) - (fb.getFrequencyOf(i) * deltaHeight);
+ double ey = (height - bottomMargin) - (fb.getFrequencyOf(i + delta) * deltaHeight);
+ line.setLine(sx,sy,ex,ey);
+ g2.draw(line);
+ }
+
+ g2.setColor(Color.GREEN);
+ double accProp = 0.0;
+
+ for(int i = min; i < max; i = i + delta)
+ {
+ accProp = accProp + fb.getProbabilityOf(i);
+ double nextProp = fb.getProbabilityOf(i + delta);
+
+ double sx = ((i - min) * deltaWidth) + leftMargin;
+ double ex = (((i + delta) - min) * deltaWidth) + leftMargin;
+ double sy = (height - bottomMargin) * (1 - accProp);
+ double ey = (height - bottomMargin) * (1 - (accProp + nextProp));
+ line.setLine(sx,sy,ex,ey);
+ g2.draw(line);
+ }
+ }
+}
diff --git a/projects/project1_frequencyBag/RandomDistribution.java b/projects/project1_frequencyBag/RandomDistribution.java
new file mode 100644
index 0000000..4e8bc0f
--- /dev/null
+++ b/projects/project1_frequencyBag/RandomDistribution.java
@@ -0,0 +1,77 @@
+import java.util.Random;
+
+
+public class RandomDistribution
+{
+ public static int normalDistributionInt(int min, int max)
+ {
+ int result;
+ do
+ {
+ result = (int) Math.round(boxMuller() * 100);
+ }
+ while(result < min || result > max);
+
+ return result;
+ }
+
+ private static double boxMuller()
+ {
+ Random rand = new Random();
+ double u = rand.nextDouble();
+ double v = rand.nextDouble();
+ return Math.sqrt(-2 * (Math.log(u)/Math.log(Math.E))) * Math.cos(2 * Math.PI * v);
+ }
+
+ public static int laplaceDistributionInt(int min, int max)
+ {
+ int result;
+ do
+ {
+ result = (int) Math.round(laplaceDistribution() * 100);
+ }
+ while(result < min || result > max);
+
+ return result;
+ }
+
+ private static double laplaceDistribution()
+ {
+ Random rand = new Random();
+ double u = rand.nextDouble() - 0.5;
+
+ return 0 - (Math.signum(u) * Math.log(1 - (2 * Math.abs(u))));
+ }
+
+ public static int uniformDistributionInt(int min, int max)
+ {
+ Random rand = new Random();
+
+ return rand.nextInt((max - min) + 1) + min;
+ }
+
+ public static int clockDistribution(int min, int max, int hWidth, int lWidth)
+ {
+ int result;
+
+ do
+ {
+ result = uniformDistributionInt(min, max);
+ int modResult = result % (hWidth + lWidth);
+ if(modResult < hWidth)
+ {
+ break;
+ }
+ else
+ {
+ if(uniformDistributionInt(0,1) == 1)
+ {
+ break;
+ }
+ }
+ }
+ while(true);
+
+ return result;
+ }
+}
diff --git a/projects/project1_frequencyBag/letter1.txt b/projects/project1_frequencyBag/letter1.txt
new file mode 100644
index 0000000..f9d942a
--- /dev/null
+++ b/projects/project1_frequencyBag/letter1.txt
@@ -0,0 +1,16 @@
+To whom it may concern,
+
+As the Director of the Department of Computer Sciences of North Pole University of Technology, which is one of the most prestigious engineering universities in north pole, I deem it a pleasure to recommend John Smith, one of the outstanding students in our department for admission and assistantship you are your graduate program.
+
+Since his enrollment into our department with remarkable entrance scores, John has embodied the fine character of strong inquisition and industriousness in learning, which has gained him significant academic success during his college years. I am aware of his distinctive academic performance as reflected in his transcripts. He maintains a very high grade point average that places him in the top five percent out of one hundred and fifty through the past three years, winning scholarships of the department almost every year. In the College English Speech Contest organized by the Teaching Committee of North Pole Province, he excelled most of other contestants, winning the first prize in the Region wide preliminary contest, and the third prize in the final of the provincial level, being the sole participant representing our university.
+
+I have also discovered him to be perseverant and enthusiastic in studies and extracurricular activities. During the Military Life Experiencing period, a compulsory training program for all North Pole college freshmen upon their immediate entrance, he was granted the title of Excellent Trainee thanks to his painstaking training efforts, though the training was extraordinarily rigorous and demanding. In the past college years, he has enthusiastically taken part in many students societies, such as Computer Society, Road to American English and Literature Garden, which has both seen his versatility and organizing ability by serving in quite a few positions.
+
+Speaking of his organizing ability, I have to mention two well known events under his active involvement and organization. One is the College Computer Festival of North Pole Province and the other is the Science and Culture Week of our school. In the first one, he was one of the chief representatives from our department to undertake this provincial level activity. His enthusiastic involvements in liaison, coordination and the contestants performance evaluation had won him the honorable title of Active Organizing Participant specially granted by our department for this important occasion. In the second one of Science and Culture Week, organized in our school in nineteen ninety nine, he was a chief organizer. And it was so successful that it attracted more than one thousand students to participate, who were all satisfied with this event for the opportunity of a better understanding of the past and future of science in north pole.
+
+As the Director, I am deeply impressed and moved by his capability of organizing and his sense of involvement, which have been explicitly demonstrated through all his participation in these activities
+
+A bright young man, with blazing intelligence, energy, and determination, John deserves my first rate recommendation. Thus, I would unqualifiedly recommend him for admission into the Doctor of Philosophy program at your university and I will appreciate your sincere assistance to his admission.
+
+
+Sincerely yours,
diff --git a/projects/project1_frequencyBag/project1_frequencyBag.pdf b/projects/project1_frequencyBag/project1_frequencyBag.pdf
new file mode 100644
index 0000000..d7af0aa
--- /dev/null
+++ b/projects/project1_frequencyBag/project1_frequencyBag.pdf
Binary files differ
diff --git a/projects/project2_LInfiniteInteger/InfiniteInteger y was constructed using the following statement b/projects/project2_LInfiniteInteger/InfiniteInteger y was constructed using the following statement
new file mode 100644
index 0000000..658ce14
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/InfiniteInteger y was constructed using the following statement
@@ -0,0 +1,76 @@
+ LInfiniteInteger thattemp = new LInfiniteInteger(anInfiniteInteger.toString());
+ thattemp.isNegative = false;
+ thistemp.isNegative = false;
+ if(thattemp.compareTo(thistemp) > 0)
+ {
+ negateAtEnd = true;
+ }
+ System.out.println("[ME] Attempting to detect if final answer should be negitive: " + negateAtEnd + " : " + thattemp.compareTo(thistemp) + " : When compareing " + thattemp.toString() + " with " + thistemp.toString());
+ //find the 9's complement of the this number
+ LInfiniteInteger ninesc = new LInfiniteInteger("");
+ Node thisnode = thistemp.lastNode;
+ Node thatnode = thattemp.lastNode;
+ while(thisnode != null || thatnode != null)
+ {
+ if(thatnode != null)
+ {
+ ninesc.addfirst(9-thatnode.data);
+ thatnode = thatnode.previous;
+ }
+ else
+ {
+ ninesc.addfirst(9);
+ }
+ if(thisnode != null)
+ {
+ thisnode = thisnode.previous;
+ }
+
+ }
+ ninesc.removeLast();
+ System.out.println("[ME] Calculated 9's complement: " + ninesc);
+ LInfiniteInteger answer =(LInfiniteInteger) ninesc.plus(thistemp);
+ answer = (LInfiniteInteger) answer.plus(new LInfiniteInteger(1));
+ //Remove carry
+ System.out.println("[ME] Answer's number of digits: " + answer.getNumberOfDigits() + " Ninesc's number of digits: " + ninesc.getNumberOfDigits());
+ if(answer.getNumberOfDigits() > ninesc.getNumberOfDigits())
+ {
+ answer.removeFirst();
+ }
+ System.out.println("[ME] 9's complement + other + 1 number = " + answer.toString());
+
+ ninesc = new LInfiniteInteger("");
+ for(Node tmp = answer.lastNode; tmp != null; tmp = tmp.previous)
+ {
+ ninesc.addfirst(9-tmp.data);
+ }
+ ninesc.removeLast();
+ System.out.println("[ME] After reverseing again, number = " + ninesc.toString());
+ answer = (LInfiniteInteger) ninesc.plus(new LInfiniteInteger(1));
+ //Remove leading 0's if nessessary
+ System.out.println("[ME] Answer's number of digits: " + answer.getNumberOfDigits() + "(" + answer.toString() +") Ninesc's number of digits: " + ninesc.getNumberOfDigits() + "(" + ninesc.toString() + ")");
+ if(answer.getNumberOfDigits() > ninesc.getNumberOfDigits())
+ {
+ answer.removeFirst();
+ }
+ for(Node tmp = answer.firstNode; tmp != null; tmp = tmp.next)
+ {
+ if(tmp.data == 0)
+ {
+ System.out.println("[ME] Removeing a leading 0");
+ answer.removeFirst();
+ }
+ else
+ {
+ break;
+ }
+ }
+ System.out.println("[ME] After removeing padded 0's number is " + answer.toString());
+ if(answer.firstNode == null)
+ {
+ answer.addfirst(0);
+ }
+ //If the final answer has no numbers, add a 0
+ answer.isNegative = negateAtEnd;
+ System.out.println("[ME] Reversed back, final answer is " + answer.toString());
+ return answer; \ No newline at end of file
diff --git a/projects/project2_LInfiniteInteger/InfiniteInteger.pdf b/projects/project2_LInfiniteInteger/InfiniteInteger.pdf
new file mode 100644
index 0000000..12ce885
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/InfiniteInteger.pdf
Binary files differ
diff --git a/projects/project2_LInfiniteInteger/InfiniteIntegerCalculator.java b/projects/project2_LInfiniteInteger/InfiniteIntegerCalculator.java
new file mode 100644
index 0000000..540706d
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/InfiniteIntegerCalculator.java
@@ -0,0 +1,14 @@
+import javax.swing.JFrame;
+
+
+public class InfiniteIntegerCalculator
+{
+ public static void main(String[] args)
+ {
+ JFrame frame = new InfiniteIntegerCalculatorFrame();
+ frame.setTitle("Infinite Integer Calculator");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setSize(600,300);
+ frame.setVisible(true);
+ }
+}
diff --git a/projects/project2_LInfiniteInteger/InfiniteIntegerCalculatorFrame.java b/projects/project2_LInfiniteInteger/InfiniteIntegerCalculatorFrame.java
new file mode 100644
index 0000000..6e88ff8
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/InfiniteIntegerCalculatorFrame.java
@@ -0,0 +1,495 @@
+import java.awt.BorderLayout;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.KeyListener;
+import java.util.ArrayList;
+
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+
+@SuppressWarnings("serial")
+public class InfiniteIntegerCalculatorFrame extends JFrame
+{
+ private JButton[] numberButtons; // number buttons (0 to 9)
+ private JButton plusButton; // plus button (+)
+ private JButton minusButton; // minus button (-)
+ private JButton multiplyButton; // multiply button (*)
+ private JButton backButton; // back button (<-)
+ private JButton equalButton; // equal button (=)
+ private JButton clearButton; //clear button (C)
+ private JTextArea textArea; // Text area for expression and result
+ private JPanel buttonPanel; // panel for all buttons
+ private ArrayList<String> ppString; // Pretty printing string
+ private KeyListener kListener;
+
+ public InfiniteIntegerCalculatorFrame()
+ {
+ textArea = new JTextArea();
+ textArea.setText("0");
+ textArea.setEditable(false);
+ textArea.setLineWrap(true);
+
+ kListener = new KeyEvent();
+ textArea.addKeyListener(kListener);
+
+ Font font = new Font(Font.SERIF, Font.BOLD, 20);
+ textArea.setFont(font);
+
+ setButtonsAndPanel();
+
+ add(buttonPanel, BorderLayout.EAST);
+ add(textArea, BorderLayout.CENTER);
+
+ ppString = new ArrayList<String>();
+ ppString.add("0");
+ }
+
+ public class KeyEvent implements KeyListener
+ {
+ public void keyPressed(java.awt.event.KeyEvent arg0)
+ {
+ int keyCode = arg0.getKeyCode();
+ char keyChar = arg0.getKeyChar();
+
+ if(keyCode >= 48 && keyCode <=57 && keyChar != '*')
+ {
+ ButtonListener bl = new ButtonListener(keyCode - 48);
+ bl.actionPerformed(new ActionEvent(numberButtons[keyCode - 48], 1001, "" + (keyCode - 48)));
+ }
+ else if(keyCode >= 96 && keyCode <= 105)
+ {
+ ButtonListener bl = new ButtonListener(keyCode - 96);
+ bl.actionPerformed(new ActionEvent(numberButtons[keyCode - 96], 1001, "" + (keyCode - 96)));
+ }
+ else if(keyCode == 61 && keyChar == '+')
+ {
+ ButtonListener bl = new ButtonListener(10);
+ bl.actionPerformed(new ActionEvent(equalButton, 1001, "+"));
+ }
+ else if(keyCode == 107)
+ {
+ ButtonListener bl = new ButtonListener(10);
+ bl.actionPerformed(new ActionEvent(equalButton, 1001, "+"));
+ }
+ else if(keyCode == 45 && keyChar == '-')
+ {
+ ButtonListener bl = new ButtonListener(11);
+ bl.actionPerformed(new ActionEvent(minusButton, 1001, "-"));
+ }
+ else if(keyCode == 109)
+ {
+ ButtonListener bl = new ButtonListener(11);
+ bl.actionPerformed(new ActionEvent(minusButton, 1001, "-"));
+ }
+ else if(keyCode == 56 && keyChar == '*')
+ {
+ ButtonListener bl = new ButtonListener(12);
+ bl.actionPerformed(new ActionEvent(multiplyButton, 1001, "*"));
+ }
+ else if(keyCode == 106)
+ {
+ ButtonListener bl = new ButtonListener(12);
+ bl.actionPerformed(new ActionEvent(multiplyButton, 1001, "*"));
+ }
+ else if(keyCode == 8)
+ {
+ ButtonListener bl = new ButtonListener(13);
+ bl.actionPerformed(new ActionEvent(backButton, 1001, "<-"));
+ }
+ else if(keyCode == 61 && keyChar == '=')
+ {
+ ButtonListener bl = new ButtonListener(14);
+ bl.actionPerformed(new ActionEvent(equalButton, 1001, "="));
+ }
+ else if(keyCode == 10)
+ {
+ ButtonListener bl = new ButtonListener(14);
+ bl.actionPerformed(new ActionEvent(equalButton, 1001, "="));
+ }
+ else if(keyCode == 67)
+ {
+ ButtonListener bl = new ButtonListener(15);
+ bl.actionPerformed(new ActionEvent(clearButton, 1001, "C"));
+ }
+ }
+
+ public void keyReleased(java.awt.event.KeyEvent arg0)
+ {
+ }
+
+ public void keyTyped(java.awt.event.KeyEvent arg0)
+ {
+ }
+ }
+
+ /**
+ * setButtonsAndPanel
+ *
+ * Initialize all buttons, initialize the button panel,
+ * and add all buttons into button panel.
+ */
+ private void setButtonsAndPanel()
+ {
+ numberButtons = new JButton[10];
+ ButtonListener[] nbls = new ButtonListener[16];
+ for(int i = 0; i <= 9; i++)
+ {
+ numberButtons[i] = new JButton("" + i);
+ nbls[i] = new ButtonListener(i);
+ numberButtons[i].addActionListener(nbls[i]);
+ }
+
+ plusButton = new JButton("+");
+ nbls[10] = new ButtonListener(10);
+ plusButton.addActionListener(nbls[10]);
+
+ minusButton = new JButton("-");
+ nbls[11] = new ButtonListener(11);
+ minusButton.addActionListener(nbls[11]);
+
+ multiplyButton = new JButton("*");
+ nbls[12] = new ButtonListener(12);
+ multiplyButton.addActionListener(nbls[12]);
+
+ backButton = new JButton("<-");
+ nbls[13] = new ButtonListener(13);
+ backButton.addActionListener(nbls[13]);
+
+ equalButton = new JButton("=");
+ nbls[14] = new ButtonListener(14);
+ equalButton.addActionListener(nbls[14]);
+
+ clearButton = new JButton("C");
+ nbls[15] = new ButtonListener(15);
+ clearButton.addActionListener(nbls[15]);
+
+ buttonPanel = new JPanel();
+ buttonPanel.setLayout(new GridLayout(4,4));
+
+ buttonPanel.add(numberButtons[7]);
+ buttonPanel.add(numberButtons[8]);
+ buttonPanel.add(numberButtons[9]);
+ buttonPanel.add(plusButton);
+ buttonPanel.add(numberButtons[4]);
+ buttonPanel.add(numberButtons[5]);
+ buttonPanel.add(numberButtons[6]);
+ buttonPanel.add(minusButton);
+ buttonPanel.add(numberButtons[1]);
+ buttonPanel.add(numberButtons[2]);
+ buttonPanel.add(numberButtons[3]);
+ buttonPanel.add(multiplyButton);
+ buttonPanel.add(numberButtons[0]);
+ buttonPanel.add(equalButton);
+ buttonPanel.add(clearButton);
+ buttonPanel.add(backButton);
+ }
+
+ private class ButtonListener implements ActionListener
+ {
+ private int number;
+
+ private ButtonListener(int aNumber)
+ {
+ /* Number associated with each button as follows:
+ * - 0 to 9 for number buttons
+ * - 10 for +
+ * - 11 for -
+ * - 12 for *
+ * - 13 for <-
+ * - 14 for =
+ * - 15 for C
+ */
+ number = aNumber;
+ }
+
+ public void actionPerformed(ActionEvent arg0)
+ {
+ int ppSize = ppString.size();
+ boolean error = false;
+
+ if(number < 10)
+ {
+ if(ppSize == 1)
+ {
+ String temp = ppString.get(0);
+
+ if(temp.equals("+") || temp.equals("*"))
+ {
+ ppString.add("" + number);
+ }
+ else if(temp.equals("0"))
+ {
+ ppString.set(0, "" + number);
+ }
+ else
+ {
+ ppString.set(0,temp + number);
+ }
+ }
+ else
+ {
+ String temp = ppString.get(ppSize - 1);
+
+ if(temp.equals("+") || temp.equals("*"))
+ {
+ ppString.add("" + number);
+ }
+ else if(temp.equals("-"))
+ {
+ if(ppString.get(ppSize - 2).equals("+") || ppString.get(ppSize - 2).equals("*"))
+ {
+ ppString.set(ppSize - 1, temp + number);
+ }
+ else
+ {
+ ppString.add("" + number);
+ }
+ }
+ else
+ {
+ ppString.set(ppSize - 1, temp + number);
+ }
+ }
+ }
+ else if(number == 10)
+ {
+ ppString.add("+");
+ }
+ else if(number == 11)
+ {
+ ppString.add("-");
+ }
+ else if(number == 12)
+ {
+ ppString.add("*");
+ }
+ else if(number == 13)
+ {
+ if(ppSize > 0)
+ {
+ String temp = ppString.get(ppSize - 1);
+
+ if(temp.length() > 1)
+ {
+ ppString.set(ppSize - 1, temp.substring(0, temp.length() - 1));
+ }
+ else
+ {
+ ppString.remove(ppSize - 1);
+ }
+ }
+ }
+ else if(number == 14)
+ {
+ InfiniteIntegerInterface result = calculateResult();
+
+ if(result == null)
+ {
+ error = true;
+ }
+ else
+ {
+ ppString.clear();
+ ppString.add(result.toString());
+ }
+ }
+ else if(number == 15)
+ {
+ ppString.clear();
+ ppString.add("0");
+ }
+
+ // Set textArea according to ppString
+
+ ppSize = ppString.size();
+ String displayString = "";
+
+ if(ppSize > 0)
+ {
+ for(int i = 0; i < ppSize; i++)
+ {
+ displayString = displayString + ppString.get(i) + " ";
+ }
+ }
+ else
+ {
+ displayString = "0";
+ }
+
+ if(error)
+ {
+ displayString = displayString + "\nInvalid Expression";
+ }
+
+ textArea.setText(displayString);
+ }
+ }
+
+ /**
+ * calculateResult()
+ *
+ * This method constructs a postfix expression base on the infix expression
+ * stored in the array list of string ppString using stack as explained in
+ * class. Then evaluate the postfix expression using stack.
+ *
+ * @return an infinite integer as a result if the expression is valid.
+ * Otherwise, return null to indicate invalid expression.
+ */
+ private InfiniteIntegerInterface calculateResult()
+ {
+ ArrayList<String> postFix = new ArrayList<String>(); // Postfix expression
+ StackInterface<String> operators = new LStack<String>(); // Stack to store operators
+
+ // Convert infix expression into postfix expression
+
+ int expSize = ppString.size();
+
+ for(int i = 0; i < expSize; i++)
+ {
+ String temp = ppString.get(i);
+
+ if(temp.length() > 1)
+ {
+ postFix.add(temp);
+ }
+ else if(isOperator(temp.charAt(0)))
+ {
+ if(temp.equals("+") || temp.equals("-"))
+ {
+ while(!operators.isEmpty())
+ {
+ postFix.add(operators.pop());
+ }
+ operators.push(temp);
+ }
+ else
+ {
+ while(!operators.isEmpty() && operators.peek().equals("*"))
+ {
+ postFix.add(operators.pop());
+ }
+ operators.push(temp);
+ }
+ }
+ else
+ {
+ postFix.add(temp);
+ }
+ }
+
+ while(!operators.isEmpty())
+ {
+ postFix.add(operators.pop());
+ }
+
+ // Display postfix expression
+
+ System.out.print("Postfix: ");
+
+ for(int i = 0; i < postFix.size(); i++)
+ {
+ System.out.print(postFix.get(i) + " ");
+ }
+ System.out.println();
+
+ // Evaluate postfix expression
+
+ StackInterface<InfiniteIntegerInterface> resultStack = new LStack<InfiniteIntegerInterface>();
+
+ int postFixSize = postFix.size();
+
+ for(int i = 0; i < postFixSize; i++)
+ {
+ String temp = postFix.get(i);
+
+ if(temp.length() == 1 && isOperator(temp.charAt(0)))
+ {
+ /* Encounter an operator, pop the top of the stack
+ * twice to use those numbers as operand, calculate
+ * the result, and push the result back onto the
+ * stack.
+ */
+ InfiniteIntegerInterface op1, op2; // operand 1 and 2
+
+ if(resultStack.isEmpty())
+ {
+ return null; // if the stack is empty, invalid expression
+ }
+ else
+ {
+ op2 = resultStack.pop(); // Pop the second operand
+ }
+
+ if(resultStack.isEmpty())
+ {
+ return null; // if the stack is empty, invalid expression
+ }
+ else
+ {
+ op1 = resultStack.pop(); // Pop the first operand
+ }
+
+ /* Calculating result of "op1 operator op2"
+ * and push the result back onto the stack.
+ */
+ if(temp.equals("+"))
+ {
+ resultStack.push(op1.plus(op2));
+ }
+ else if(temp.equals("-"))
+ {
+ resultStack.push(op1.minus(op2));
+ }
+ else
+ {
+ resultStack.push(op1.multiply(op2));
+ }
+ }
+ else
+ {
+ // Encounter a number, push the number onto the stack.
+
+ resultStack.push(new LInfiniteInteger(temp));
+ }
+ }
+
+ /* The expression is valid if the stack contain exactly
+ * one item. That one single item is the result of evaluating
+ * the arithmetic expression.
+ */
+
+ InfiniteIntegerInterface result = null;
+
+ if(resultStack.isEmpty())
+ {
+ return null; // The stack is empty, invalid expression
+ }
+ else
+ {
+ result = resultStack.pop(); // Pop the result out of the stack
+
+ if(!resultStack.isEmpty())
+ {
+ result = null; // The stack is NOT empty, invalid expression
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * isOperator: Return true if the character c is an
+ * operator, +, -, or *. Otherwise, return false.
+ * @param c the character to be tested whether it is
+ * an operator.
+ * @return true if c is an operator. Otherwise, return false.
+ */
+ private boolean isOperator(char c)
+ {
+ return c == '+' || c == '-' || c == '*';
+ }
+}
diff --git a/projects/project2_LInfiniteInteger/InfiniteIntegerInterface.java b/projects/project2_LInfiniteInteger/InfiniteIntegerInterface.java
new file mode 100644
index 0000000..5cd9944
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/InfiniteIntegerInterface.java
@@ -0,0 +1,59 @@
+
+public interface InfiniteIntegerInterface
+{
+ /**
+ * Gets the number of digits of this infinite integer.
+ * @return an integer representing the number of digits
+ * of this infinite integer.
+ */
+ public int getNumberOfDigits();
+
+ /**
+ * Checks whether this infinite integer is a negative number.
+ * @return true if this infinite integer is a negative number.
+ * Otherwise, return false.
+ */
+ public boolean isNegative();
+
+ /**
+ * Calculates the result of this infinite integer plus anInfiniteInteger
+ * @param anInfiniteInteger the infinite integer to be added.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer plus anInfiniteInteger
+ */
+ public InfiniteIntegerInterface plus(final InfiniteIntegerInterface anInfiniteInteger);
+
+ /**
+ * Calculates the result of this infinite integer subtracted by anInfiniteInteger
+ * @param anInfiniteInteger the infinite integer to subtract.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer subtracted by anInfiniteInteger
+ */
+ public InfiniteIntegerInterface minus(final InfiniteIntegerInterface anInfiniteInteger);
+
+ /**
+ * Calculates the result of this infinite integer multiplied by anInfiniteInteger
+ * @param anInfiniteInteger the multiplier.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer multiplied by anInfiniteInteger.
+ */
+ public InfiniteIntegerInterface multiply(final InfiniteIntegerInterface anInfiniteInteger);
+
+ /**
+ * Generates a string representing this infinite integer. If this infinite integer
+ * is a negative number a minus symbol should be in the front of numbers. For example,
+ * "-12345678901234567890". But if the infinite integer is a positive number, no symbol
+ * should be in the front of the numbers (e.g., "12345678901234567890").
+ * @return a string representing this infinite integer number.
+ */
+ public String toString();
+
+ /**
+ * Compares this infinite integer with anInfiniteInteger
+ * @return either -1, 0, or 1 as follows:
+ * If this infinite integer is less than anInfiniteInteger, return -1.
+ * If this infinite integer is equal to anInfiniteInteger, return 0.
+ * If this infinite integer is greater than anInfiniteInteger, return 1.
+ */
+ public int compareTo(final InfiniteIntegerInterface anInfiniteInteger);
+}
diff --git a/projects/project2_LInfiniteInteger/LInfiniteInteger.java b/projects/project2_LInfiniteInteger/LInfiniteInteger.java
new file mode 100644
index 0000000..c74ab41
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/LInfiniteInteger.java
@@ -0,0 +1,562 @@
+
+public class LInfiniteInteger implements InfiniteIntegerInterface
+{
+ private Node firstNode;
+ private Node lastNode;
+ private int numberOfDigits;
+ private boolean isNegative;
+
+ /**
+ * Constructor: Constructs this infinite integer from a string
+ * representing an integer.
+ * @param s a string represents an integer
+ */
+ public LInfiniteInteger(String s)
+ {
+ if(s.toCharArray().length > 0 && s.toCharArray()[0] == '-') //Short circuit in case the string is empty
+ {
+ isNegative = true;
+ s = s.substring(1);
+ }
+ boolean significantDigit = false;
+ for(char c : s.toCharArray())
+ {
+ if(!significantDigit && Character.getNumericValue(c) == 0)
+ {
+ }
+ else
+ {
+ significantDigit = true;
+ Node n = new Node(lastNode,Character.getNumericValue(c),null);
+ if(firstNode == null)
+ {
+ firstNode = n;
+ }
+ lastNode = n;
+ numberOfDigits++;
+ }
+ }
+ if(firstNode == null)
+ {
+ firstNode = new Node(null,0,null);
+ lastNode = firstNode;
+ numberOfDigits++;
+ }
+ for(Node tmp = lastNode; tmp != null && tmp.previous != null;tmp = tmp.previous)
+ {
+ //System.out.println("[ME] Setting node with data " + tmp.previous.data + " to have corret next.");
+ tmp.previous.next = tmp;
+ }
+ }
+
+ /**
+ * Constructor: Constructs this infinite integer from an integer.
+ * @param anInteger an integer
+ */
+ public LInfiniteInteger(int anInteger)
+ {
+ isNegative = anInteger < 0;
+ //System.out.println("[ME] Makeing with integer" + anInteger);
+ if(isNegative)
+ {
+ anInteger *= -1;
+ }
+ for(int i = 10; i/10 <= anInteger; i *= 10)
+ {
+ //System.out.println("[ME] Makeing a node with " + (anInteger%i)/(i/10));
+ Node n = new Node(null,(anInteger%i)/(i/10),firstNode);
+ firstNode = n;
+ numberOfDigits++;
+ }
+ Node tmp = firstNode;
+ for(; tmp != null && tmp.next != null;tmp = tmp.next)
+ {
+ //System.out.println("[ME] Setting node with data " + tmp.previous.data + " to have corret next.");
+ tmp.next.previous = tmp;
+ }
+ lastNode = tmp;
+ if(anInteger == 0)
+ {
+ Node n = new Node(null,0,null);
+ firstNode = n;
+ lastNode = n;
+ }
+ //numberOfDigits--; //Subtract 1, because we looped 1 too many times for digits, but needed to take into account potential digits to the left
+ //System.out.println("[ME]Created from integer, number is " + this.toString());
+ }
+
+ /**
+ * Gets the number of digits of this infinite integer.
+ * @return an integer representing the number of digits
+ * of this infinite integer.
+ */
+ public int getNumberOfDigits()
+ {
+ numberOfDigits = 0;
+ for(Node tmp = firstNode; tmp != null; tmp = tmp.next)
+ {
+ numberOfDigits++;
+ }
+ return numberOfDigits;
+ }
+
+ /**
+ * Checks whether this infinite integer is a negative number.
+ * @return true if this infinite integer is a negative number.
+ * Otherwise, return false.
+ */
+ public boolean isNegative()
+ {
+ return isNegative;
+ }
+
+ /**
+ * Calculates the result of this infinite integer plus anInfiniteInteger
+ * @param anInfiniteInteger the infinite integer to be added to this
+ * infinite integer.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer plus anInfiniteInteger
+ */
+ public InfiniteIntegerInterface plus(final InfiniteIntegerInterface anInfiniteInteger)
+ {
+ LInfiniteInteger output = new LInfiniteInteger("");
+
+ //System.out.println("[ME] Attempting to add " + this.toString() + " and " + anInfiniteInteger.toString());
+
+ //If both are negative do addition, but the answer is negative
+ if(this.isNegative() && anInfiniteInteger.compareTo(new LInfiniteInteger("")) <= 0)
+ {
+
+ //And the other number is zero, set output to negative, and add
+ output.isNegative = true;
+ }
+ else if(this.compareTo(new LInfiniteInteger("")) <= 0 && anInfiniteInteger.isNegative())
+ {
+ output.isNegative = true;
+ }
+ //If one is negitive, find out which, and do a subtraction instead
+ if(this.compareTo(new LInfiniteInteger("")) < 0 && anInfiniteInteger.compareTo(new LInfiniteInteger("")) > 0)
+ {
+ //this is negitive, but the other is positive
+ LInfiniteInteger temp = new LInfiniteInteger(this.toString());
+ temp.isNegative = false;
+ return anInfiniteInteger.minus(temp);
+ }
+ if(this.compareTo(new LInfiniteInteger("")) > 0 && anInfiniteInteger.compareTo(new LInfiniteInteger("")) < 0)
+ {
+ //anInfiniteInteger is negitive, but we are positive.
+ LInfiniteInteger temp = new LInfiniteInteger(anInfiniteInteger.toString());
+ temp.isNegative = false;
+ return this.minus(temp);
+ }
+ //We should only get to this point if we're really doing addition
+ int carry = 0;
+ Node thattemp = new LInfiniteInteger(anInfiniteInteger.toString()).lastNode;
+ Node temp = this.lastNode;
+ if(temp == null)
+ {
+ //System.out.println("[ME] LAST NODE IS NULL FROM START!");
+ }
+ for(; temp != null || thattemp != null;)
+ {
+ int sum = 0;
+ //System.out.print("[ME] After this interation, ");
+ if(temp != null)
+ {
+ sum += temp.data;
+ //System.out.print(" " + temp.data + " + ");
+ temp = temp.previous;
+ }
+ else
+ {
+ //System.out.print(" NULL + ");
+ }
+ if(thattemp != null)
+ {
+ //System.out.print(thattemp.data);
+ sum += thattemp.data;
+ thattemp = thattemp.previous;
+ }
+ else
+ {
+ //System.out.print(" NULL ");
+ }
+ sum += carry;
+ carry = sum / 10;
+ output.addfirst(sum % 10);
+ //System.out.print(" , sum is " + sum%10 + " and carry is " + carry + "\n");
+ }
+ if(carry > 0)
+ {
+ output.addfirst(carry);
+ }
+ output.removeLast();
+ //Return the result
+ return output;
+ }
+ private void removeLast()
+ {
+ Node tmp = lastNode;
+ if(tmp != null)
+ {
+ tmp = lastNode.previous;
+ if(tmp != null)
+ {
+ tmp.next = null;
+ }
+ lastNode = tmp;
+ }
+ }
+ private void removeFirst()
+ {
+ Node tmp = firstNode;
+ if(tmp != null)
+ {
+ tmp = firstNode.next;
+ if(tmp != null)
+ {
+ tmp.previous = null;
+ }
+ firstNode = tmp;
+ }
+ }
+ private void addfirst(int data)
+ {
+ Node tmp = firstNode;
+ Node n = new Node(null,data,firstNode);
+ firstNode = n;
+ if(tmp != null)
+ {
+ tmp.previous = n;
+ }
+ }
+ private void addlast(int data)
+ {
+ Node tmp = lastNode;
+ Node n = new Node(lastNode,data,null);
+ lastNode = n;
+ if(tmp != null)
+ {
+ tmp.next = n;
+ }
+ }
+ private Node getLastNode()
+ {
+ return lastNode;
+ }
+ private Node getFirstNode()
+ {
+ return firstNode;
+ }
+ /**
+ * Calculates the result of this infinite integer subtracted by anInfiniteInteger
+ * @param anInfiniteInteger the infinite integer to subtract.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer subtracted by anInfiniteInteger
+ */
+ public InfiniteIntegerInterface minus(final InfiniteIntegerInterface anInfiniteInteger)
+ {
+ //System.out.println("[ME] Attempting to subtract " + anInfiniteInteger.toString() + " from " + this.toString());
+ // Figure out if we're really supposed to subtract, or we need to do a clever add
+ //Cases:
+ //We are negative, and anInteger is not negative (-this - that) = (-this + -that)
+ if(this.isNegative && !anInfiniteInteger.isNegative())
+ {
+ //Just add them as negitive numbers
+ LInfiniteInteger tmp= new LInfiniteInteger(anInfiniteInteger.toString());
+ tmp.isNegative = true;
+ return this.plus(tmp);
+
+ }
+ //We are not negative, and anInteger is negative (this - -that) = (this + that)
+ if(!this.isNegative && anInfiniteInteger.isNegative())
+ {
+ LInfiniteInteger tmp= new LInfiniteInteger(anInfiniteInteger.toString());
+ tmp.isNegative = false;
+ return this.plus(tmp);
+ }
+ //We are both negitive(-this - -that) = (-this + that)
+ if(this.isNegative && anInfiniteInteger.isNegative())
+ {
+ LInfiniteInteger tmp = new LInfiniteInteger(anInfiniteInteger.toString());
+ tmp.isNegative = false;
+ return this.plus(tmp);
+ }
+ //Figure out which number is lower in magnitude, and have that the the "fake" negitive, and maybe flip the signs back if nessessarry.
+ //Find both numbers without magnitude
+ LInfiniteInteger thisnomag = new LInfiniteInteger(this.toString());
+ thisnomag.isNegative = false;
+ LInfiniteInteger thatnomag = new LInfiniteInteger(anInfiniteInteger.toString());
+ thatnomag.isNegative = false;
+ boolean negateAtEnd = false;
+ LInfiniteInteger bigger = null;
+ LInfiniteInteger smaller = null;
+ if(thisnomag.compareTo(thatnomag) > 0)
+ {
+ //We are bigger
+ negateAtEnd = false;
+ bigger = new LInfiniteInteger(this.toString());
+ smaller = new LInfiniteInteger(anInfiniteInteger.toString());
+ }
+ else if(thisnomag.compareTo(thatnomag) < 0)
+ {
+ //The other guy is bigger
+ //System.out.println("[ME] " + anInfiniteInteger.toString() + " is bigger");
+ negateAtEnd = true;
+ bigger = new LInfiniteInteger(anInfiniteInteger.toString());
+ smaller = new LInfiniteInteger(this.toString());
+ }
+ else
+ {
+ //They are the same magnitude.
+ bigger = new LInfiniteInteger(this.toString());
+ smaller = new LInfiniteInteger(this.toString());
+ }
+ //System.out.println("[ME] Bigger number is " + bigger.toString() + " and smaller is " + smaller.toString() + " negateing at end: " + negateAtEnd);
+ //For each digit in the bigger, subtract the bigger - the smaller, borrowing where needed
+ Node tmp1 = bigger.lastNode;
+ Node tmp2 = smaller.lastNode;
+ LInfiniteInteger answer = new LInfiniteInteger("");
+ while(tmp1 != null)
+ {
+ //Get the numbers
+ int bignum = tmp1.data;
+ int smallnum = 0;
+ if(tmp2 != null)
+ {
+ smallnum = tmp2.data;
+ }
+ else
+ {
+ smallnum = 0;
+ }
+ //If the smaller number's digit is larger than the larger number's digit, we need to barrow
+ if(smallnum > bignum)
+ {
+ //System.out.println("[ME] Needing to barrow because " + smallnum + " > " + bignum);
+ barrow(tmp1.previous);
+ //System.out.println("[ME] After barrowing, number is " + bigger.toString());
+ bignum = bignum+10;
+ }
+ //Then do regular subtraction
+ //System.out.println("[ME] Adding " + (bignum - smallnum) + " to answer, answer is " + answer.toString() + " bigger is " + bigger.toString() + " smaller is " + smaller.toString());
+ answer.addfirst(bignum - smallnum);
+ tmp1 = tmp1.previous;
+ if(tmp2 != null)
+ {
+ tmp2 = tmp2.previous;
+ }
+ }
+ answer.removeLast(); // remove the 0
+ //Remove any 0's at the beginning.
+ for(Node tmp = answer.firstNode; tmp != null && tmp != answer.lastNode; tmp = tmp.next)
+ {
+ if(tmp.data == 0)
+ {
+ answer.removeFirst();
+ }
+ else
+ {
+ break;
+ }
+ }
+ //Retun the answer
+ answer.isNegative = negateAtEnd;
+ return answer;
+ }
+ private void barrow(Node n)
+ {
+ //System.out.println("[ME] Barrowing from " + n.data);
+ if(n.data != 0)
+ {
+ //System.out.println("[ME] Found something to barrow from: " + n.data);
+ n.data--;
+ }
+ else
+ {
+ barrow(n.previous);
+ n.data = 9;
+ }
+ }
+ /**
+ * Generates a string representing this infinite integer. If this infinite integer
+ * is a negative number a minus symbol should be in the front of numbers. For example,
+ * "-12345678901234567890". But if the infinite integer is a positive number, no symbol
+ * should be in the front of the numbers (e.g., "12345678901234567890").
+ * @return a string representing this infinite integer number.
+ */
+ public String toString()
+ {
+ String output = "";
+ if(isNegative)
+ {
+ output += "-";
+ }
+ for(Node tmp = firstNode; tmp != null; tmp = tmp.next)
+ {
+ //System.out.println("[ME] this node has " + tmp.data + " and it's next node is " + tmp.next);
+ output += tmp.data;
+ }
+ //System.out.println("[ME] Returning " + output);
+ return output;
+ }
+
+ /**
+ * Compares this infinite integer with anInfiniteInteger
+ * @return either -1, 0, or 1 as follows:
+ * If this infinite integer is less than anInfiniteInteger, return -1.
+ * If this infinite integer is equal to anInfiniteInteger, return 0.
+ * If this infinite integer is greater than anInfiniteInteger, return 1.
+ */
+ public int compareTo(InfiniteIntegerInterface anInfiniteInteger)
+ {
+ //System.out.println("[ME] Compareing " + this.toString() + " with " + anInfiniteInteger.toString());
+ //If they're different signs, we're done.
+ if(this.isNegative() && !anInfiniteInteger.isNegative())
+ {
+ return -1;
+ }
+ if(!this.isNegative() && anInfiniteInteger.isNegative())
+ {
+ return 1;
+ }
+ //Otherwise, they're the same sign, and we need to compare digits.
+ //If one has more digits than the other, we're also done.
+ if(this.getNumberOfDigits() > anInfiniteInteger.getNumberOfDigits())
+ {
+ return 1;
+ }
+ if(anInfiniteInteger.getNumberOfDigits() > this.getNumberOfDigits())
+ {
+ return -1;
+ }
+ Node thattemp = new LInfiniteInteger(anInfiniteInteger.toString()).firstNode;
+ Node thistemp = this.firstNode;
+ for(; thistemp != null || thattemp != null;)
+ {
+ if(thistemp.data > thattemp.data)
+ {
+ return 1;
+ }
+ if(thistemp.data < thattemp.data)
+ {
+ return -1;
+ }
+ if(thistemp != null)
+ {
+ thistemp = thistemp.next;
+ }
+ if(thattemp != null)
+ {
+ thattemp = thattemp.next;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Calculates the result of this infinite integer multiplied by anInfiniteInteger
+ * @param anInfiniteInteger the multiplier.
+ * @return a NEW infinite integer representing the result of this
+ * infinite integer multiplied by anInfiniteInteger.
+ */
+ public InfiniteIntegerInterface multiply(final InfiniteIntegerInterface anInfiniteInteger)
+ {
+ //Figure out if we're supposed to be negative or positive
+ boolean negateAtEnd = false;
+ //If we are negative and param is not, (- * +) answer will be negative
+ if(this.isNegative && !anInfiniteInteger.isNegative())
+ {
+ negateAtEnd = true;
+ }
+ //If we are positive, and param is negitive (+ * -) answer will be negative
+ if(!this.isNegative && anInfiniteInteger.isNegative())
+ {
+ negateAtEnd = true;
+ }
+ //Otherwise, we will be positive (+ * +) or (- * -)
+ //Unless one of the numbers is 0, in which case we can just return 0.
+ LInfiniteInteger thisusigned = new LInfiniteInteger(this.toString());
+ LInfiniteInteger thatusigned = new LInfiniteInteger(anInfiniteInteger.toString());
+ if((thisusigned.compareTo(new LInfiniteInteger("")) == 0) || (thatusigned.compareTo(new LInfiniteInteger("")) == 0))
+ {
+ return new LInfiniteInteger("");
+ }
+ //Find the number with more digits, and the one with fewer digits
+ LInfiniteInteger larger = null;
+ LInfiniteInteger smaller = null;
+ if(this.getNumberOfDigits() > anInfiniteInteger.getNumberOfDigits())
+ {
+ larger = new LInfiniteInteger(this.toString());
+ smaller = new LInfiniteInteger(anInfiniteInteger.toString());
+ }
+ if(anInfiniteInteger.getNumberOfDigits() >= this.getNumberOfDigits())
+ {
+ larger = new LInfiniteInteger(anInfiniteInteger.toString());
+ smaller = new LInfiniteInteger(this.toString());
+ }
+ //For every digit, multiply each other number by the digit, in order, and multiply the next answer by 10 (or just add a 0 to it)
+ LInfiniteInteger answer = new LInfiniteInteger("");
+ int mult = 0; //Number to multiply the answers by
+ //System.out.println("[ME] Multiplying " + larger.toString() + " with " + smaller.toString());
+ for(Node n = smaller.lastNode; n != null; n = n.previous)
+ {
+ LInfiniteInteger thismult = new LInfiniteInteger("");
+ int carry = 0;
+ for(Node d = larger.lastNode; d != null; d = d.previous)
+ {
+ int product = n.data * d.data;
+ product += carry;
+
+ if(product > 9)
+ {
+ carry = product/10;
+ }
+ else
+ {
+ carry = 0;
+ }
+ product %= 10;
+ //System.out.println("[ME] Product is " + product + " carry is " + carry);
+ thismult.addfirst(product);
+ }
+ if(carry > 0)
+ {
+ thismult.addfirst(carry);
+ }
+
+ //Shift the mult over, so it will add up correctly
+ for(int i = 0; i < mult; i++)
+ {
+ thismult.addlast(0);
+ }
+ thismult.removeLast();
+ //System.out.println("[ME] Attempting to add " + answer.toString() + " with " + thismult.toString());
+ answer = (LInfiniteInteger) answer.plus(thismult);
+ mult++;
+ }
+ //answer.removeLast();
+ answer.isNegative = negateAtEnd;
+ //If it's -something * 0, answer will be -0, just make it +0
+ return answer;
+ }
+
+ private class Node
+ {
+ private int data;
+ private Node next;
+ private Node previous;
+
+ private Node(Node previousNode, int aData, Node nextNode)
+ {
+ previous = previousNode;
+ data = aData;
+ next = nextNode;
+ }
+
+ private Node(int aData)
+ {
+ this(null, aData, null);
+ }
+ }
+}
diff --git a/projects/project2_LInfiniteInteger/LInfiniteIntegerTester.java b/projects/project2_LInfiniteInteger/LInfiniteIntegerTester.java
new file mode 100644
index 0000000..503932d
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/LInfiniteIntegerTester.java
@@ -0,0 +1,1136 @@
+import java.util.Scanner;
+
+public class LInfiniteIntegerTester
+{
+ public static void main(String[] args)
+ {
+ int option = 1; // 1 to stop right after a FAIL
+ int numErrors = 0; // number of errors
+
+ System.out.println("Welcome to AInfiniteInteger Tester");
+ System.out.println("There are two options:");
+ System.out.println(" 1. Stop right after a FAIL");
+ System.out.println(" 2. Do not stop after a FAIL");
+ System.out.print("Please select an option (1 or 2): ");
+
+ @SuppressWarnings("resource")
+ Scanner in = new Scanner(System.in);
+
+ do
+ {
+ option = 1;//in.nextInt();
+ if(option != 1 && option != 2)
+ {
+ System.out.print("Invalid option. Please select an option (1 or 2): ");
+ }
+ }
+ while(option != 1 && option != 2);
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of a positive integer: ");
+
+ InfiniteIntegerInterface gd1 = new LInfiniteInteger("123456789");
+
+ if(gd1.getNumberOfDigits() != 9)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd1 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("The integer 123456789 contains 9 digits.");
+ System.out.println("But your gd1.getNumberOfDigits() returns " + gd1.getNumberOfDigits() + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of a negative integer: ");
+
+ InfiniteIntegerInterface gd2 = new LInfiniteInteger("-123456789");
+
+ if(gd2.getNumberOfDigits() != 9)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd2 = new LInfiniteInteger(\"-123456789\");");
+ System.out.println("The integer -123456789 contains 9 digits.");
+ System.out.println("But your gd2.getNumberOfDigits() returns " + gd2.getNumberOfDigits() + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of a positive integer with leading 0s: ");
+
+ InfiniteIntegerInterface gd3 = new LInfiniteInteger("000123456789");
+
+ if(gd3.getNumberOfDigits() != 9)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd3 = new LInfiniteInteger(\"000123456789\");");
+ System.out.println("The integer 123456789 contains 9 digits.");
+ System.out.println("But your gd3.getNumberOfDigits() returns " + gd3.getNumberOfDigits() + ".");
+ System.out.println("Did you handle leading 0s?");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of a negative integer with leading 0s: ");
+
+ InfiniteIntegerInterface gd4 = new LInfiniteInteger("-000123456789");
+
+ if(gd4.getNumberOfDigits() != 9)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd4 = new LInfiniteInteger(\"-000123456789\");");
+ System.out.println("The integer -123456789 contains 9 digits.");
+ System.out.println("But your gd4.getNumberOfDigits() returns " + gd4.getNumberOfDigits() + ".");
+ System.out.println("Did you handle leading 0s?");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of 0: ");
+
+ InfiniteIntegerInterface gd5 = new LInfiniteInteger("0");
+
+ if(gd5.getNumberOfDigits() != 1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd5 = new LInfiniteInteger(\"0\");");
+ System.out.println("The integer 0 contains 1 digits.");
+ System.out.println("But your gd5.getNumberOfDigits() returns " + gd5.getNumberOfDigits() + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method getNumberOfDigits()
+
+ System.out.print("Checking the method getNumberOfDigits() of 0 with leading 0s: ");
+
+ InfiniteIntegerInterface gd6 = new LInfiniteInteger("0000");
+
+ if(gd6.getNumberOfDigits() != 1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd5 = new LInfiniteInteger(\"0000\");");
+ System.out.println("The integer 0 contains 1 digits.");
+ System.out.println("But your gd6.getNumberOfDigits() returns " + gd6.getNumberOfDigits() + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a positive integer: ");
+
+ if(!gd1.toString().equals("123456789"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd1 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("But your gd1.toString() returns " + gd1 + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a negative integer: ");
+
+ if(!gd2.toString().equals("-123456789"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd2 = new LInfiniteInteger(\"-123456789\");");
+ System.out.println("But your gd2.toString() returns " + gd2 + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a positive integer with leading 0s: ");
+
+ if(!gd3.toString().equals("123456789"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd3 = new LInfiniteInteger(\"000123456789\");");
+ System.out.println("But your gd3.toString() returns " + gd3 + ".");
+ System.out.println("Did you handle leading 0s?");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a negative integer with leading 0s: ");
+
+ if(!gd4.toString().equals("-123456789"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd4 = new LInfiniteInteger(\"-000123456789\");");
+ System.out.println("But your gd4.toString() returns " + gd4 + ".");
+ System.out.println("Did you handle leading 0s?");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a 0: ");
+
+ if(!gd5.toString().equals("0"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd5 = new LInfiniteInteger(\"0\");");
+ System.out.println("But your gd5.toString() returns " + gd5 + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method toString()
+
+ System.out.print("Checking the method toString() of a 0 with leading 0s: ");
+
+ if(!gd6.toString().equals("0"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface gd6 = new LInfiniteInteger(\"0000\");");
+ System.out.println("But your gd6.toString() returns " + gd6 + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ InfiniteIntegerInterface cp1 = new LInfiniteInteger("987654321");
+
+ if(cp1.compareTo(cp1) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 987654321 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp1 = new LInfiniteInteger(\"987654321\");");
+ System.out.println("cp1.compareTo(cp1) should return 0.");
+ System.out.println("But your cp1.compareTo(cp1) returns " + cp1.compareTo(cp1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ InfiniteIntegerInterface cp2 = new LInfiniteInteger("123456789");
+
+ if(cp1.compareTo(cp2) != 1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 987654321 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp1 = new LInfiniteInteger(\"987654321\");");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp2 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("cp1.compareTo(cp2) should return 1.");
+ System.out.println("But your cp1.compareTo(cp2) returns " + cp1.compareTo(cp2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ if(cp2.compareTo(cp1) != -1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 987654321 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp1 = new LInfiniteInteger(\"987654321\");");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp2 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("cp2.compareTo(cp1) should return -1.");
+ System.out.println("But your cp2.compareTo(cp1) returns " + cp2.compareTo(cp1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ InfiniteIntegerInterface cp3 = new LInfiniteInteger("123456789");
+
+ if(cp2.compareTo(cp3) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp2 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp3 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("cp2.compareTo(cp3) should return 0.");
+ System.out.println("But your cp2.compareTo(cp3) returns " + cp2.compareTo(cp3) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ InfiniteIntegerInterface cp4 = new LInfiniteInteger("-123456789");
+
+ if(cp3.compareTo(cp4) != 1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp3 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp4 = new LInfiniteInteger(\"-123456789\");");
+ System.out.println("cp3.compareTo(cp4) should return 1.");
+ System.out.println("But your cp3.compareTo(cp4) returns " + cp3.compareTo(cp4) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Testing the method compareTo()
+
+ System.out.print("Checking the method compareTo(): ");
+
+ if(cp4.compareTo(cp3) != -1)
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp3 = new LInfiniteInteger(\"123456789\");");
+ System.out.println("The integer -123456789 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface cp4 = new LInfiniteInteger(\"-123456789\");");
+ System.out.println("cp4.compareTo(cp3) should return -1.");
+ System.out.println("But your cp4.compareTo(cp3) returns " + cp4.compareTo(cp3) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // Testing the method plus()
+
+ System.out.println("Testing the method plus()");
+ System.out.println("=========================");
+
+ System.out.println("The range of the infinite integer x is [-500,500].");
+ System.out.println("The range of the infinite integer y is [-500,500].");
+ System.out.print("Checking all possible values of x + y: ");
+
+ for(int i = -500; i <= 500; i++)
+ {
+ for(int j = -500; j <= 500; j++)
+ {
+ InfiniteIntegerInterface x = new LInfiniteInteger(i);
+ InfiniteIntegerInterface y = new LInfiniteInteger(j);
+
+ if(!((i + j) + "").equals(x.plus(y).toString()))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger x was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface x = new LInfiniteInteger(" + i + ");");
+ System.out.println("InfiniteInteger y was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface y = new LInfiniteInteger(" + j + ");");
+ System.out.println("The result of " + i + " + " + j + " should be " + (i + j) + ".");
+ System.out.println("But your x.plus(y) returns " + x.plus(y) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ }
+ }
+
+ System.out.println("PASS\n");
+
+ System.out.print("Calculating 12345678901234567890 + 12345678901234567890: ");
+ InfiniteIntegerInterface tp1 = new LInfiniteInteger("12345678901234567890");
+ if(!tp1.plus(tp1).toString().equals("24691357802469135780"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The result of 12345678901234567890 + 12345678901234567890 should be 24691357802469135780.");
+ System.out.println("But your tp1.plus(tp1) returns " + tp1.plus(tp1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating 12345678901234567890 + (-12345678901234567890): ");
+
+ InfiniteIntegerInterface tp2_1 = new LInfiniteInteger("12345678901234567890");
+ InfiniteIntegerInterface tp2_2 = new LInfiniteInteger("-12345678901234567890");
+ if(!tp2_1.plus(tp2_2).toString().equals("0"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp2_1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The integer -12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp2_2 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("The result of 12345678901234567890 + (-12345678901234567890) should be 0.");
+ System.out.println("But your tp2_1.plus(tp2_2) returns " + tp2_1.plus(tp2_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating 100000000000000000000 + (-1): ");
+ InfiniteIntegerInterface tp3_1 = new LInfiniteInteger("100000000000000000000");
+ InfiniteIntegerInterface tp3_2 = new LInfiniteInteger("-1");
+ if(!tp3_1.plus(tp3_2).toString().equals("99999999999999999999"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 100000000000000000000 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp3_1 = new LInfiniteInteger(\"100000000000000000000\");");
+ System.out.println("The integer -1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp3_2 = new LInfiniteInteger(\"-1\");");
+ System.out.println("The result of 100000000000000000000 + (-1) should be 99999999999999999999.");
+ System.out.println("But your tp3_1.plus(tp3_2) returns " + tp3_1.plus(tp3_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating (-1) + 100000000000000000000: ");
+ InfiniteIntegerInterface tp4_1 = new LInfiniteInteger("-1");
+ InfiniteIntegerInterface tp4_2 = new LInfiniteInteger("100000000000000000000");
+ if(!tp4_1.plus(tp4_2).toString().equals("99999999999999999999"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp4_1 = new LInfiniteInteger(\"-1\");");
+ System.out.println("The integer 100000000000000000000 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp4_2 = new LInfiniteInteger(\"100000000000000000000\");");
+ System.out.println("The result of (-1) + 100000000000000000000 should be 99999999999999999999.");
+ System.out.println("But your tp4_1.plus(tp4_2) returns " + tp4_1.plus(tp4_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating 1 + (-100000000000000000000): ");
+ InfiniteIntegerInterface tp5_1 = new LInfiniteInteger("1");
+ InfiniteIntegerInterface tp5_2 = new LInfiniteInteger("-100000000000000000000");
+ if(!tp5_1.plus(tp5_2).toString().equals("-99999999999999999999"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp5_1 = new LInfiniteInteger(\"1\");");
+ System.out.println("The integer -100000000000000000000 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp5_2 = new LInfiniteInteger(\"-100000000000000000000\");");
+ System.out.println("The result of 1 + (-100000000000000000000) should be -99999999999999999999.");
+ System.out.println("But your tp5_1.plus(tp5_2) returns " + tp5_1.plus(tp5_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating (-100000000000000000000) + 1: ");
+ InfiniteIntegerInterface tp6_1 = new LInfiniteInteger("-100000000000000000000");
+ InfiniteIntegerInterface tp6_2 = new LInfiniteInteger("1");
+ if(!tp6_1.plus(tp6_2).toString().equals("-99999999999999999999"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer -100000000000000000000 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp6_1 = new LInfiniteInteger(\"-100000000000000000000\");");
+ System.out.println("The integer 1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tp6_2 = new LInfiniteInteger(\"1\");");
+ System.out.println("The result of (-100000000000000000000) + 1 should be -99999999999999999999.");
+ System.out.println("But your tp6_1.plus(tp6_2) returns " + tp6_1.plus(tp6_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // Testing the method minus()
+
+ System.out.println("Testing the method minus()");
+ System.out.println("==========================");
+
+ System.out.println("The range of the infinite integer x is [-500,500].");
+ System.out.println("The range of the infinite integer y is [-500,500].");
+ System.out.print("Checking all possible values of x - y: ");
+
+ for(int i = -500; i <= 500; i++)
+ {
+ for(int j = -500; j <= 500; j++)
+ {
+ InfiniteIntegerInterface x = new LInfiniteInteger(i);
+ InfiniteIntegerInterface y = new LInfiniteInteger(j);
+
+ if(!((i - j) + "").equals(x.minus(y).toString()))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger x was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface x = new LInfiniteInteger(" + i + ");");
+ System.out.println("InfiniteInteger y was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface y = new LInfiniteInteger(" + j + ");");
+ System.out.println("The result of " + i + " - " + j + " should be " + (i - j) + ".");
+ System.out.println("But your x.minus(y) returns " + x.minus(y) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ }
+ }
+
+ System.out.println("PASS\n");
+
+ InfiniteIntegerInterface tm1 = new LInfiniteInteger("12345678901234567890");
+
+ System.out.print("Calculating 12345678901234567890 - 12345678901234567890: ");
+ if(!tm1.minus(tm1).toString().equals("0"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tm1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The result of 12345678901234567890 - 12345678901234567890 should be 0.");
+ System.out.println("But your tm1.minus(tm1) returns " + tm1.minus(tm1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ InfiniteIntegerInterface tm2_1 = new LInfiniteInteger("12345678901234567890");
+ InfiniteIntegerInterface tm2_2 = new LInfiniteInteger("1234567890");
+
+ System.out.print("Calculating 12345678901234567890 - 1234567890: ");
+ if(!tm2_1.minus(tm2_2).toString().equals("12345678900000000000"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tm2_1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The integer 1234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tm2_2 = new LInfiniteInteger(\"1234567890\");");
+ System.out.println("The result of 12345678901234567890 - 1234567890 should be 12345678900000000000.");
+ System.out.println("But your tm2_1.minus(tm2_2) returns " + tm2_1.minus(tm2_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ InfiniteIntegerInterface tm3_1 = new LInfiniteInteger("1234567890");
+ InfiniteIntegerInterface tm3_2 = new LInfiniteInteger("12345678901234567890");
+
+ System.out.print("Calculating 1234567890 - 12345678901234567890: ");
+ if(!tm3_1.minus(tm3_2).toString().equals("-12345678900000000000"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The integer 1234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tm3_1 = new LInfiniteInteger(\"1234567890\");");
+ System.out.println("The integer 12345678901234567890 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tm3_2 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The result of 1234567890 - 12345678901234567890 should be -12345678900000000000.");
+ System.out.println("But your tm3_1.minus(tm3_2) returns " + tm3_1.minus(tm3_2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // Testing the method multiply()
+
+ System.out.println("Testing the method multiply()");
+ System.out.println("=============================");
+
+ System.out.println("The range of the infinite integer x is [-500,500].");
+ System.out.println("The range of the infinite integer y is [-500,500].");
+ System.out.print("Checking all possible values of x * y: ");
+
+ for(int i = -500; i <= 500; i++)
+ {
+ for(int j = -500; j <= 500; j++)
+ {
+ InfiniteIntegerInterface x = new LInfiniteInteger(i);
+ InfiniteIntegerInterface y = new LInfiniteInteger(j);
+
+ if(!((i * j) + "").equals(x.multiply(y).toString()))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger x was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface x = new LInfiniteInteger(" + i + ");");
+ System.out.println("InfiniteInteger y was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface y = new LInfiniteInteger(" + j + ");");
+ System.out.println("The result of " + i + " * " + j + " should be " + (i * j) + ".");
+ System.out.println("But your x.multiply(y) returns " + x.multiply(y) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ }
+ }
+
+ System.out.println("PASS\n");
+
+ System.out.print("Calculating 12345678901234567890 * 12345678901234567890: ");
+
+ InfiniteIntegerInterface tml1 = new LInfiniteInteger("12345678901234567890");
+ String tml1Result = "152415787532388367501905199875019052100";
+
+ if(!tml1.multiply(tml1).toString().equals(tml1Result))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("The result of " + tml1 + " * " + tml1 + " should be " + tml1Result + ".");
+ System.out.println("But your tml1.multiply(tml1) returns " + tml1.multiply(tml1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating 12345678901234567890 * -12345678901234567890: ");
+
+ InfiniteIntegerInterface tml2 = new LInfiniteInteger("-12345678901234567890");
+
+ if(!tml1.multiply(tml2).toString().equals("-" + tml1Result))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("InfiniteInteger tml2 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml2 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("The result of " + tml1 + " * " + tml2 + " should be -" + tml1Result + ".");
+ System.out.println("But your tml1.multiply(tml2) returns " + tml1.multiply(tml2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating -12345678901234567890 * 12345678901234567890: ");
+
+ if(!tml2.multiply(tml1).toString().equals("-" + tml1Result))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml1 = new LInfiniteInteger(\"12345678901234567890\");");
+ System.out.println("InfiniteInteger tml2 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml2 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("The result of " + tml2 + " * " + tml1 + " should be -" + tml1Result + ".");
+ System.out.println("But your tml2.multiply(tml1) returns " + tml2.multiply(tml1) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Calculating -12345678901234567890 * -12345678901234567890: ");
+
+ if(!tml2.multiply(tml2).toString().equals(tml1Result))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml2 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml2 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("The result of " + tml2 + " * " + tml2 + " should be " + tml1Result + ".");
+ System.out.println("But your tml2.multiply(tml2) returns " + tml2.multiply(tml2) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Multiply by 0
+
+ System.out.print("Calculating 12345678901234567890 * 0: ");
+
+ InfiniteIntegerInterface tml0 = new LInfiniteInteger("0");
+
+ if(!tml1.multiply(tml0).toString().equals("0"))
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml1 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("InfiniteInteger tml0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml0 = new LInfiniteInteger(\"0\");");
+ System.out.println("The result of " + tml1 + " * " + tml0 + " should be " + tml1Result + ".");
+ System.out.println("But your tml1.multiply(tml0) returns " + tml1.multiply(tml0) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Checking equivalent to zero (compareTo): ");
+
+ InfiniteIntegerInterface tml3 = tml1.multiply(tml0);
+
+ if(tml3.compareTo(tml0) != 0)
+ {
+ System.out.println("FAIL");
+ System.out.println("InfiniteInteger tml1 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml1 = new LInfiniteInteger(\"-12345678901234567890\");");
+ System.out.println("InfiniteInteger tml0 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml0 = new LInfiniteInteger(\"0\");");
+ System.out.println("InfiniteInteger tml3 was constructed using the following statement:");
+ System.out.println(" InfiniteIntegerInterface tml3 = tml1.multiply(tml0);");
+ System.out.println("The result of calling tml3.compareTo(tml0) should be 0.");
+ System.out.println("But your tml3.compareTo(tml0) returns " + tml3.compareTo(tml0) + ".\n");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+
+ System.out.println();
+
+ // Crazy Tests
+
+ System.out.println("Let's go crazy.");
+ System.out.println("Calculating values of 2^1, 2^2, 2^4, 2^8, ..., 2^1024 using loops of additions");
+
+ int resultNumber = 0;
+ int[] resultNumDigits = new int[11];
+ String[] resultStrings = new String[11];
+ resultNumDigits[0] = 1;
+ resultStrings[0] = "2";
+ resultNumDigits[1] = 1;
+ resultStrings[1] = "4";
+ resultNumDigits[2] = 2;
+ resultStrings[2] = "16";
+ resultNumDigits[3] = 3;
+ resultStrings[3] = "256";
+ resultNumDigits[4] = 5;
+ resultStrings[4] = "65536";
+ resultNumDigits[5] = 10;
+ resultStrings[5] = "4294967296";
+ resultNumDigits[6] = 20;
+ resultStrings[6] = "18446744073709551616";
+ resultNumDigits[7] = 39;
+ resultStrings[7] = "340282366920938463463374607431768211456";
+ resultNumDigits[8] = 78;
+ resultStrings[8] = "115792089237316195423570985008687907853269984665640564039457584007913129639936";
+ resultNumDigits[9] = 155;
+ resultStrings[9] = "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096";
+ resultNumDigits[10] = 309;
+ resultStrings[10] = "179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216";
+
+ System.out.println("This test is done by first construct the infinit integer x using the followoing statement:");
+ System.out.println(" InfiniteIntegerInterface x = new LInfiniteInteger(\"1\");");
+ System.out.println("Then repeatedly executing the following statement:");
+ System.out.println(" x = x.plus(x);\n");
+
+ for(int n = 1; n <= 1024; n = n + n)
+ {
+ InfiniteIntegerInterface x = new LInfiniteInteger("1");
+
+ for(int i = 1; i <= n; i++)
+ {
+ x = x.plus(x);
+ }
+ System.out.print("2^" + n + " is " + x + " containing " + x.getNumberOfDigits() + " digits: ");
+ if(x.getNumberOfDigits() != resultNumDigits[resultNumber] || !x.toString().equals(resultStrings[resultNumber]))
+ {
+ System.out.println("FAIL");
+ System.out.println("2^" + n + " should be " + resultStrings[resultNumber] + " which contains " + resultNumDigits[resultNumber] + " digits.");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ resultNumber++;
+ }
+
+ System.out.println();
+
+ int numDigitsGoal = 1000;
+ String crazyResultString = "1313879718456104225921995528497555855625152414017051819746489965175418594035237238181967239932841927943368022817082758088019245450978689926961358127631787144754373062120106902504163460853000843067796699510293924385333858122456855065858902248896798237625003273316840048212276610565777594650220087971045508055611314300070786176626378923084556948528977153135635206046615173944871186308702998089733796437598174864856900497873863589167218546523213052953471290292740839713119247294213720517263787354623928731924441813068650485005632246166869508621489664962699281739398162579362377493635567561343072827446535980932480283909225368443393486477711655376434350643031227524710815041165924570415486219444700695031601993251625411314037854648482400238147123249264167061961509379444920959953800364778020888142773659393688842351560111550969115614788364312559110854239694359378947557812483113318119934088060561737965196192041096299817733313038159648080136912212919336690293080257579650807503654066749005924284432908288";
+ int resultOfx = 3319;
+
+ System.out.println("Let's go to the extreme.");
+ System.out.println("Let's find the number x where 2^x contains " + numDigitsGoal + " digits.");
+
+ InfiniteIntegerInterface crazy = new LInfiniteInteger("1");
+ int result = 0;
+ while(crazy.getNumberOfDigits() < numDigitsGoal)
+ {
+ crazy = crazy.plus(crazy);
+ result++;
+ }
+
+ System.out.println("2^" + result + " is " + crazy + ".");
+ System.out.println("2^" + result + " contains " + numDigitsGoal + " digits.");
+
+ System.out.print("Crazy test: ");
+
+ if(resultOfx == result && crazyResultString.equals(crazy.toString()))
+ {
+ System.out.println("PASS");
+ }
+ else
+ {
+ System.out.println("FAIL");
+ System.out.println("The answer should be 2^" + resultOfx + ".");
+ System.out.println("Where 2^" + resultOfx + " is equal to " + crazyResultString + ".");
+ if(option == 1)
+ {
+ return;
+ }
+ else
+ {
+ numErrors++;
+ }
+ }
+
+ // Show number of errors
+
+ if(numErrors != 0)
+ {
+ System.out.println("\nThere are " + numErrors + " errors detected.");
+ }
+ else
+ {
+ System.out.println("\nThere are no errors detected. Good Job!!!");
+ }
+ }
+}
diff --git a/projects/project2_LInfiniteInteger/LStack.java b/projects/project2_LInfiniteInteger/LStack.java
new file mode 100644
index 0000000..15e9bed
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/LStack.java
@@ -0,0 +1,66 @@
+
+public class LStack<T> implements StackInterface<T>
+{
+ private Node firstNode;
+
+ public LStack()
+ {
+ firstNode = null;
+ }
+
+ public void push(T anEntry)
+ {
+ Node newNode = new Node(anEntry, firstNode);
+ firstNode = newNode;
+ }
+
+ public T pop()
+ {
+ T result = null;
+
+ if(firstNode != null)
+ {
+ result = firstNode.data;
+ firstNode = firstNode.next;
+ }
+
+ return result;
+ }
+
+ public T peek()
+ {
+ if(firstNode != null)
+ {
+ return firstNode.data;
+ }
+
+ return null;
+ }
+
+ public boolean isEmpty()
+ {
+ return firstNode == null;
+ }
+
+ public void clear()
+ {
+ firstNode = null;
+ }
+
+ private class Node
+ {
+ private T data;
+ private Node next;
+
+ private Node(T aData)
+ {
+ this(aData, null);
+ }
+
+ private Node(T aData, Node nextNode)
+ {
+ data = aData;
+ next = nextNode;
+ }
+ }
+}
diff --git a/projects/project2_LInfiniteInteger/StackInterface.java b/projects/project2_LInfiniteInteger/StackInterface.java
new file mode 100644
index 0000000..1007f13
--- /dev/null
+++ b/projects/project2_LInfiniteInteger/StackInterface.java
@@ -0,0 +1,9 @@
+
+public interface StackInterface<T>
+{
+ public void push(T anEntry);
+ public T pop();
+ public T peek();
+ public boolean isEmpty();
+ public void clear();
+}
diff --git a/projects/project3_kenken/Cell.java b/projects/project3_kenken/Cell.java
new file mode 100644
index 0000000..b9966cf
--- /dev/null
+++ b/projects/project3_kenken/Cell.java
@@ -0,0 +1,30 @@
+public class Cell
+{
+ int x,y;
+ int num;
+ public Cell(int x, int y)
+ {
+ this.x = x;
+ this.y = y;
+ }
+ public int getX()
+ {
+ return x;
+ }
+ public int getY()
+ {
+ return y;
+ }
+ public void setNum(int num)
+ {
+ this.num = num;
+ }
+ public int getNum()
+ {
+ return num;
+ }
+ public String toString()
+ {
+ return "Cell:(" + x + "," + y + ")=" + num;
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/KCage.java b/projects/project3_kenken/KCage.java
new file mode 100644
index 0000000..dc3642c
--- /dev/null
+++ b/projects/project3_kenken/KCage.java
@@ -0,0 +1,200 @@
+
+public class KCage
+{
+ Cell[] cells;
+ int targetnumber;
+ Operator operator;
+ public KCage()
+ {
+
+ }
+ public KCage(int tn,Operator op,Cell[] c)
+ {
+ cells = c;
+ targetnumber = tn;
+ operator = op;
+ }
+ public int getNumCells()
+ {
+ return cells.length;
+ }
+ public int getTargNumber()
+ {
+ return targetnumber;
+ }
+ public Operator getOperator()
+ {
+ return operator;
+ }
+ public Cell getCell(int i)
+ {
+ return cells[i];
+ }
+ public boolean[] getPossibilitiesForOthers(int num)
+ {
+ boolean[] output = new boolean[num];
+ if(operator == Operator.MINUS)
+ {
+ for(int i = 1; i < num; i++)
+ {
+ for(int j = 1; j < num; j++)
+ {
+ if(i-j == targetnumber || j-i == targetnumber)
+ {
+ output[i] = true;
+ output[j] = true;
+ }
+ }
+ }
+ }
+ if(operator == Operator.DIVIDE)
+ {
+ for(int i = 1; i < num; i++)
+ {
+ for(int j = 1; j < num; j++)
+ {
+ if(i/(j*1.0) == targetnumber || j/(i*1.0) == targetnumber)
+ {
+ output[i] = true;
+ output[j] = true;
+ }
+ }
+ }
+ }
+ if(operator == Operator.PLUS)
+ {
+ for(int i = 0; i < num*cells.length; i++)
+ {
+
+ }
+ int sum = 0;
+ for(Cell c : cells)
+ {
+
+ }
+ }
+ return output;
+ }
+ public boolean test(int xn, int yn, int num)
+ {
+ for(Cell c : cells)
+ {
+ if(c.getX() == xn && c.getY() == yn)
+ {
+ if(operator == Operator.PLUS)
+ {
+ int sum = 0;
+ for(Cell c2 : cells)
+ {
+ sum += c2.getNum();
+ }
+ sum += num;
+ if(sum == targetnumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(operator == Operator.MINUS)
+ {
+ Cell thiscell;
+ Cell thatcell;
+ if(c == cells[0])
+ {
+ thiscell = cells[0];
+ thatcell = cells[1];
+ }
+ else
+ {
+ thatcell = cells[0];
+ thiscell = cells[1];
+ }
+ if(thiscell.getNum() == 0 || thatcell.getNum() == 0)
+ {
+ return true;
+ }
+ if(thatcell.getNum() - num == targetnumber || num - thatcell.getNum() == targetnumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(operator == Operator.MULTIPLY)
+ {
+ int product = 1;
+ for(Cell c2 : cells)
+ {
+ if(c2.getNum() != 0)
+ product *= c2.getNum();
+ }
+ product *= num;
+ if(product <= targetnumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(operator == Operator.DIVIDE)
+ {
+ Cell thiscell;
+ Cell thatcell;
+ if(c == cells[0])
+ {
+ thiscell = cells[0];
+ thatcell = cells[1];
+ }
+ else
+ {
+ thatcell = cells[0];
+ thiscell = cells[1];
+ }
+ if(thiscell.getNum() == 0 || thatcell.getNum() == 0)
+ {
+ return true;
+ }
+ if((thatcell.getNum()*1.0)/num == targetnumber || (num*1.0)/thatcell.getNum() == targetnumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ else if(operator == Operator.NONE)
+ {
+ if(num == targetnumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ }
+ }
+ return false;
+ }
+ public String toString()
+ {
+ String output = "Cage(" + targetnumber + "," + operator + "){\n\t\t";
+ if(cells.length == 0)
+ return output+"}";
+ output += cells[0];
+ for(int i = 1; i < cells.length; i++)
+ {
+ output += ",\n\t\t"+cells[i];
+ }
+ return output + "\n\t}";
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/KPuzzle b/projects/project3_kenken/KPuzzle
new file mode 100644
index 0000000..e29ee65
--- /dev/null
+++ b/projects/project3_kenken/KPuzzle
@@ -0,0 +1 @@
+public class KPuzzle \ No newline at end of file
diff --git a/projects/project3_kenken/KPuzzle.java b/projects/project3_kenken/KPuzzle.java
new file mode 100644
index 0000000..41af390
--- /dev/null
+++ b/projects/project3_kenken/KPuzzle.java
@@ -0,0 +1,264 @@
+import java.util.Scanner;
+import java.io.*;
+
+public class KPuzzle
+{
+ //a 2-d array of the cages, cages that are more than 1 square will have alieases on all of the squares.
+ KCage[] p;//The puzzle
+ int size;
+ boolean[] p2; //The possiblilities for every square - 3D
+ public KPuzzle()
+ {
+
+ }
+ public KPuzzle(String filename)
+ {
+ parsePuzzle(filename);
+ makePossible();
+ checkCages();
+ }
+ private void checkCages()
+ {
+ for(int i = 0; i < p.length; i++)
+ {
+ KCage c = p[i];
+ if(c.getNumCells() == 1)
+ {
+ Cell cell = c.getCell(0);
+ this.putNumber(cell.getX(),cell.getY(),c.getTargNumber());
+ System.out.println("After putting " + c.getTargNumber() + " into (" + cell.getX() + "," + cell.getY() + ") Possibilities are:");
+ this.printPossibilities();
+ return;
+ }
+ }
+ }
+ public Cell getCell(int x, int y)
+ {
+ KCage k = p[y*size + x];
+ for(int i = 0; i < k.getNumCells();i++)
+ {
+ Cell c = k.getCell(i);
+ if(c.getX() == x && c.getY() == y)
+ {
+ return c;
+ }
+ }
+ return null;
+ }
+ public boolean isComplete()
+ {
+ for(int i = 0; i < size; i++)
+ {
+ for(int j = 0; j < size; j++)
+ {
+ int possibilitiesForCell = 0;
+ for(int k = 0; k < size; k++)
+ {
+ if(p2[(i*size*size)+(j*size)+k])
+ {
+ possibilitiesForCell++;
+ }
+ }
+ if(possibilitiesForCell != 1)
+ {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+ public boolean[] getPossibilities(int xn, int yn)
+ {
+ boolean[] output = new boolean[size];
+ for(int i = 0; i < size; i++)
+ {
+ output[i] = p2[(yn*size*size)+(xn*size)+i];
+ }
+ return output;
+ }
+ public void removePossibility(int xn, int yn, int num)
+ {
+ p2[(yn*size*size)+(xn*size)+num-1] = false;
+ }
+ public void addPossibility(int xn, int yn, int num)
+ {
+ p2[(yn*size*size)+(xn*size)+num-1] = true;
+ }
+ public void putNumber(int xn, int yn, int num)
+ {
+ System.out.println("putting " + num + " in (" + xn + "," + yn + ")");
+ for(int y = 0; y < size; y++)
+ {
+ for(int z = 0; z < size; z++)
+ {
+ if(z == num-1)
+ {
+ //System.out.println("Setting (" + xn + "," + y + "," + z + ") to false");
+ p2[(y*size*size)+(xn*size)+z] = false;
+ }
+ }
+ }
+ for(int x = 0; x < size; x++)
+ {
+ for(int z = 0; z < size; z++)
+ {
+ if(z == num-1)
+ p2[(yn*size*size)+(x*size)+z] = false;
+ }
+ }
+ for(int z = 0; z < size; z++)
+ {
+ p2[(yn*size*size)+(xn*size)+z] = false;
+ }
+ System.out.println("Setting (" + xn + "," + yn + "," + (num-1) + ") to true");
+ p2[(yn*size*size)+(xn*size)+num-1] = true;
+ }
+ public void takeNumber(int xn, int yn)
+ {
+ int thisnum = -1;
+ for(int z = 0; z < size; z++)
+ {
+ if(p2[(yn*size*size)+(xn*size)+z])
+ thisnum = z;
+ }
+ if(thisnum == -1)
+ {
+ System.out.println("I couldn't find a number there!");
+ return;
+ }
+ for(int y = 0; y < size; y++)
+ {
+ for(int z = 0; z < size; z++)
+ {
+ if(z == thisnum)
+ {
+ System.out.println("Setting (" + xn + "," + y + "," + z + ") to true");
+ p2[(y*size*size)+(xn*size)+z] = true;
+ }
+ }
+ }
+ for(int x = 0; x < size; x++)
+ {
+ for(int z = 0; z < size; z++)
+ {
+ if(z == thisnum)
+ p2[(yn*size*size)+(x*size)+z] = true;
+ }
+ }
+ for(int z = 0; z < size; z++)
+ {
+ p2[(yn*size*size)+(xn*size)+z] = true;
+ }
+ }
+ public void printPossibilities()
+ {
+ for(int y = 0; y < size; y++)
+ {
+ for(int x = 0; x < size; x++)
+ {
+ System.out.print("Possibilities for (" + x + "," + y + ") are: ");
+ for(int z = 0; z < size; z++)
+ {
+ if(p2[(y*size*size)+(x*size)+z])
+ {
+ System.out.print(z+1);
+ }
+ }
+ System.out.println("");
+ }
+ }
+ }
+ private void makePossible()
+ {
+ p2 = new boolean[size*size*size];
+ //System.out.println("Makeing possibilities:");
+ for(int i = 0; i < size; i++)
+ {
+ for(int j = 0; j < size; j++)
+ {
+ for(int k = 0; k < size; k++)
+ {
+ p2[(i*size*size)+(j*size)+k] = true;
+ //System.out.print(p2[(i*size*size)+(j*size)+k] + " ");
+ }
+ //System.out.print("\t");
+ }
+ //System.out.println("");
+ }
+ }
+ private void parsePuzzle(String filename)
+ {
+ Scanner s = null;
+ try
+ {
+ s = new Scanner(new FileInputStream(filename));
+ }
+ catch (Exception e)
+ {
+ System.out.println("Something went terribly wrong!\n" + e);
+ }
+ size = Integer.parseInt(s.nextLine().replaceAll("\n",""));
+ p = new KCage[size*size];
+ //System.out.println("Puzzle size: " + size + " Cages: " + p.length);
+ for(int i = 0; s.hasNextLine();i++)
+ {
+ String t1 = s.nextLine();
+ //System.out.println("Praseing: " + t1);
+ String[] t2 = t1.split(",");
+ //System.out.println("Parts length: " + t2.length);
+ if(t2.length > 1)
+ {
+ Cell[] allcells = new Cell[Integer.parseInt(t2[2])];
+ for(int j = 0; j < Integer.parseInt(t2[2]);j++)
+ {
+ String[] coords = s.nextLine().split(",");
+ allcells[j] = new Cell(Integer.parseInt(coords[0]),Integer.parseInt(coords[1]));
+ }
+ for(Cell c : allcells)
+ {
+ p[c.getY()*size + c.getX()] = new KCage(Integer.parseInt(t2[0]),getOp(t2[1]),allcells);
+ }
+ //p[i] = new KCage(Integer.parseInt(t2[0]),getOp(t2[1]),allcells);
+ //System.out.println("Created " + p[i]);
+ }
+ }
+ }
+ public KCage getCage(int i)
+ {
+ return p[i];
+ }
+ public int getNumCages()
+ {
+ return p.length;
+ }
+ public String toString()
+ {
+ String output = "Puzzle{\n\t";
+ if(p.length == 0)
+ return output+"}";
+ output += p[0];
+ for(int i = 1; i < p.length; i++)
+ {
+ output += ",\n\t"+p[i];
+ }
+ return output + "\n}";
+ }
+ private static Operator getOp(String s)
+ {
+ switch(s)
+ {
+ case "+":
+ return Operator.PLUS;
+ case "-":
+ return Operator.MINUS;
+ case "*":
+ return Operator.MULTIPLY;
+ case "/":
+ return Operator.DIVIDE;
+ case " ":
+ return Operator.NONE;
+ default:
+ return Operator.NULL;
+ }
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/Operator.java b/projects/project3_kenken/Operator.java
new file mode 100644
index 0000000..5facf0e
--- /dev/null
+++ b/projects/project3_kenken/Operator.java
@@ -0,0 +1,4 @@
+public enum Operator
+{
+ PLUS,MINUS,MULTIPLY,DIVIDE,NULL,NONE
+} \ No newline at end of file
diff --git a/projects/project3_kenken/Solver.java b/projects/project3_kenken/Solver.java
new file mode 100644
index 0000000..ebdf950
--- /dev/null
+++ b/projects/project3_kenken/Solver.java
@@ -0,0 +1,173 @@
+
+
+public class Solver
+{
+ private int x;
+ private int y;
+ private KStack stack;
+ public Solver()
+ {
+ stack = new KStack();
+ x = 0;
+ y = 0;
+ }
+ public void solve(KPuzzle puz)
+ {
+ puz.printPossibilities();
+ boolean[] b = puz.getPossibilities(x,y);
+ int numlen = 0;
+ int lastplace = -1;
+ System.out.println("looking for possibility in (" + x + "," + y + ")");
+ for(for int i = 0; i < b.length; i++)
+ {
+ if(ba)
+ {
+ numlen++;
+ lastplace = i;
+ }
+ }
+ if(numlen == 1)
+ {
+ imply(x,y,lastplace)
+ }
+ else
+ {
+ for(int i = 0; i < b.length; i++)
+ {
+ System.out.println("Scanning: " + (i+1) + " : " + b[i]);
+ if(b[i])
+ {
+ guess(x,y,i+1);
+ puz.putNumber(x,y,i+1);
+ x++;
+ if(x > puz.size)
+ {
+ y++;
+ x = 0;
+ }
+ solve(puz);
+ int[] arr = stack.pop();
+ puz.takeNumber(arr[1],arr[2]);
+ }
+ if(numlen == 0)
+ {
+ System.out.println("Exhausted possibilities, backtracking");
+ return;
+ }
+ }
+ }
+ if(numlen == 1)
+ {
+ System.out.println("implying " + lastplace + " in (" + x + "," + y + ")");
+ imply(x,y,lastplace);
+ puz.putNumber(x,y,lastplace);
+ }
+ else if(numlen == 0)
+ {
+ //Pop everything to the last guess
+ System.out.println("Found a cell with no possibilitys, backtracking");
+ while(stack.peek()[0] == 1 && stack.getLength() > 1);
+ {
+ int[] arr = stack.pop();
+ puz.removePossibility(arr[1],arr[2],arr[3]);
+ }
+ }
+ else
+ {
+ System.out.println("Guessing " + lastplace + " in (" + x + "," + y + ")");
+ guess(x,y,lastplace);
+ puz.putNumber(x,y,lastplace);
+ b[lastplace] = false;
+ }
+ }
+ private void guess(int x, int y, int num)
+ {
+ int[] item = new int[4];
+ item[0] = 1;
+ item[1] = x;
+ item[2] = y;
+ item[3] = num;
+ stack.push(item);
+ }
+ private void imply(int x, int y, int num)
+ {
+ int[] item = new int[4];
+ item[0] = 0;
+ item[1] = x;
+ item[2] = y;
+ item[3] = num;
+ stack.push(item);
+ }
+ public class KStack
+ {
+ private KNode head;
+ private int length;
+ public KStack()
+ {
+ length = 0;
+ }
+ public int[] peek()
+ {
+ return head.getData();
+ }
+ public int[] pop()
+ {
+ int[] output = head.getData();
+ head = head.getNext();
+ length--;
+ return output;
+ }
+ public void push(int[] i)
+ {
+ head = new KNode(i,head);
+ length++;
+ }
+ public boolean hasNext()
+ {
+ return head != null;
+ }
+ public int getLength()
+ {
+ return length;
+ }
+ public String toString()
+ {
+ String output = "";
+ for(KNode tmp = head; tmp != null; tmp=tmp.getNext())
+ {
+ output += tmp.getData() + " ";
+ }
+ return output;
+ }
+ /*public int[] toArray()
+ {
+ int[] output = new int[length];
+ int i = length-1;
+ for(KNode tmp = head; tmp != null; tmp = tmp.getNext())
+ {
+ output[i] = tmp.getData();
+ i--;
+ }
+ return output;
+ }*/
+
+ }
+ public class KNode
+ {
+ private KNode next = null;
+ private int[] data;
+ public KNode(int[] d, KNode n)
+ {
+ data = d;
+ next = n;
+ }
+ public int[] getData()
+ {
+ return data;
+ }
+ public KNode getNext()
+ {
+ return next;
+ }
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/images/3x3_1.jpg b/projects/project3_kenken/images/3x3_1.jpg
new file mode 100644
index 0000000..764f9a3
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/3x3_1_solution.jpg b/projects/project3_kenken/images/3x3_1_solution.jpg
new file mode 100644
index 0000000..2514be0
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/3x3_2.jpg b/projects/project3_kenken/images/3x3_2.jpg
new file mode 100644
index 0000000..c06f1d0
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/3x3_2_solution.jpg b/projects/project3_kenken/images/3x3_2_solution.jpg
new file mode 100644
index 0000000..0396e3f
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/3x3_3.jpg b/projects/project3_kenken/images/3x3_3.jpg
new file mode 100644
index 0000000..3dd4691
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_3.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/3x3_3_solution.jpg b/projects/project3_kenken/images/3x3_3_solution.jpg
new file mode 100644
index 0000000..5b3049c
--- /dev/null
+++ b/projects/project3_kenken/images/3x3_3_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_1.jpg b/projects/project3_kenken/images/4x4_1.jpg
new file mode 100644
index 0000000..1a4d971
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_1_solution.jpg b/projects/project3_kenken/images/4x4_1_solution.jpg
new file mode 100644
index 0000000..fbdc213
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_2.jpg b/projects/project3_kenken/images/4x4_2.jpg
new file mode 100644
index 0000000..60c64d3
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_2_solution.jpg b/projects/project3_kenken/images/4x4_2_solution.jpg
new file mode 100644
index 0000000..aa6e135
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_3.jpg b/projects/project3_kenken/images/4x4_3.jpg
new file mode 100644
index 0000000..60076ec
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_3.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/4x4_3_solution.jpg b/projects/project3_kenken/images/4x4_3_solution.jpg
new file mode 100644
index 0000000..85bd8c0
--- /dev/null
+++ b/projects/project3_kenken/images/4x4_3_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_1.jpg b/projects/project3_kenken/images/5x5_1.jpg
new file mode 100644
index 0000000..c9e7cb7
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_1_solution.jpg b/projects/project3_kenken/images/5x5_1_solution.jpg
new file mode 100644
index 0000000..5cefef4
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_2.jpg b/projects/project3_kenken/images/5x5_2.jpg
new file mode 100644
index 0000000..4651465
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_2_solution.jpg b/projects/project3_kenken/images/5x5_2_solution.jpg
new file mode 100644
index 0000000..b8c71a5
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_3.jpg b/projects/project3_kenken/images/5x5_3.jpg
new file mode 100644
index 0000000..cce77bb
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_3.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/5x5_3_solution.jpg b/projects/project3_kenken/images/5x5_3_solution.jpg
new file mode 100644
index 0000000..64d90bd
--- /dev/null
+++ b/projects/project3_kenken/images/5x5_3_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/6x6_1.jpg b/projects/project3_kenken/images/6x6_1.jpg
new file mode 100644
index 0000000..8f03d5c
--- /dev/null
+++ b/projects/project3_kenken/images/6x6_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/6x6_1_solution.jpg b/projects/project3_kenken/images/6x6_1_solution.jpg
new file mode 100644
index 0000000..1b9f1d1
--- /dev/null
+++ b/projects/project3_kenken/images/6x6_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/6x6_2.jpg b/projects/project3_kenken/images/6x6_2.jpg
new file mode 100644
index 0000000..2dad139
--- /dev/null
+++ b/projects/project3_kenken/images/6x6_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/6x6_2_solution.jpg b/projects/project3_kenken/images/6x6_2_solution.jpg
new file mode 100644
index 0000000..e0c87e9
--- /dev/null
+++ b/projects/project3_kenken/images/6x6_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/7x7_1.jpg b/projects/project3_kenken/images/7x7_1.jpg
new file mode 100644
index 0000000..7ed98a0
--- /dev/null
+++ b/projects/project3_kenken/images/7x7_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/7x7_1_solution.jpg b/projects/project3_kenken/images/7x7_1_solution.jpg
new file mode 100644
index 0000000..bec6b7a
--- /dev/null
+++ b/projects/project3_kenken/images/7x7_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/7x7_2.jpg b/projects/project3_kenken/images/7x7_2.jpg
new file mode 100644
index 0000000..d3e7e3b
--- /dev/null
+++ b/projects/project3_kenken/images/7x7_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/7x7_2_solution.jpg b/projects/project3_kenken/images/7x7_2_solution.jpg
new file mode 100644
index 0000000..ed35a9b
--- /dev/null
+++ b/projects/project3_kenken/images/7x7_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/8x8_1.jpg b/projects/project3_kenken/images/8x8_1.jpg
new file mode 100644
index 0000000..573259a
--- /dev/null
+++ b/projects/project3_kenken/images/8x8_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/8x8_1_solution.jpg b/projects/project3_kenken/images/8x8_1_solution.jpg
new file mode 100644
index 0000000..50d1d53
--- /dev/null
+++ b/projects/project3_kenken/images/8x8_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/8x8_2.jpg b/projects/project3_kenken/images/8x8_2.jpg
new file mode 100644
index 0000000..db8829a
--- /dev/null
+++ b/projects/project3_kenken/images/8x8_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/8x8_2_solution.jpg b/projects/project3_kenken/images/8x8_2_solution.jpg
new file mode 100644
index 0000000..ddd423d
--- /dev/null
+++ b/projects/project3_kenken/images/8x8_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_1.jpg b/projects/project3_kenken/images/9x9_1.jpg
new file mode 100644
index 0000000..bda6fb8
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_1.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_1_solution.jpg b/projects/project3_kenken/images/9x9_1_solution.jpg
new file mode 100644
index 0000000..c20f72f
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_1_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_2.jpg b/projects/project3_kenken/images/9x9_2.jpg
new file mode 100644
index 0000000..53c8b10
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_2.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_2_solution.jpg b/projects/project3_kenken/images/9x9_2_solution.jpg
new file mode 100644
index 0000000..0b41dad
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_2_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_3.jpg b/projects/project3_kenken/images/9x9_3.jpg
new file mode 100644
index 0000000..82d231b
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_3.jpg
Binary files differ
diff --git a/projects/project3_kenken/images/9x9_3_solution.jpg b/projects/project3_kenken/images/9x9_3_solution.jpg
new file mode 100644
index 0000000..638f2bd
--- /dev/null
+++ b/projects/project3_kenken/images/9x9_3_solution.jpg
Binary files differ
diff --git a/projects/project3_kenken/kenkensolver.java b/projects/project3_kenken/kenkensolver.java
new file mode 100644
index 0000000..8a8e70c
--- /dev/null
+++ b/projects/project3_kenken/kenkensolver.java
@@ -0,0 +1,14 @@
+public class kenkensolver
+{
+ public static void main(String[] args)
+ {
+ KPuzzle p = new KPuzzle("./puzzle_files/3x3_3.txt");
+ //System.out.println("Puzzle is: " + p);
+ //p.takeNumber(0,0);
+ System.out.println("\n\n\n");
+ Solver s = new Solver();
+ //p.printPossibilities();
+ //stack = new KStack();
+ s.solve(p);
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/project3_kenken.pdf b/projects/project3_kenken/project3_kenken.pdf
new file mode 100644
index 0000000..8ec834e
--- /dev/null
+++ b/projects/project3_kenken/project3_kenken.pdf
Binary files differ
diff --git a/projects/project3_kenken/puzzle_files/3x3_1.txt b/projects/project3_kenken/puzzle_files/3x3_1.txt
new file mode 100644
index 0000000..b23e027
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/3x3_1.txt
@@ -0,0 +1,17 @@
+3
+5
+3, ,1
+0,0
+6,*,2
+0,1
+1,1
+2,/,2
+0,2
+1,2
+2,/,2
+1,0
+2,0
+2,-,2
+2,1
+2,2
+
diff --git a/projects/project3_kenken/puzzle_files/3x3_2.txt b/projects/project3_kenken/puzzle_files/3x3_2.txt
new file mode 100644
index 0000000..2556aa6
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/3x3_2.txt
@@ -0,0 +1,17 @@
+3
+5
+2, ,1
+0,0
+9,*,3
+0,1
+0,2
+1,2
+2,-,2
+1,0
+2,0
+2,/,2
+1,1
+2,1
+2, ,1
+2,2
+
diff --git a/projects/project3_kenken/puzzle_files/3x3_3.txt b/projects/project3_kenken/puzzle_files/3x3_3.txt
new file mode 100644
index 0000000..a844c5b
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/3x3_3.txt
@@ -0,0 +1,17 @@
+3
+5
+1,-,2
+0,1
+0,2
+2,-,2
+0,0
+1,0
+2, ,1
+1,1
+3,+,2
+2,0
+2,1
+3,/,2
+1,2
+2,2
+
diff --git a/projects/project3_kenken/puzzle_files/4x4_1.txt b/projects/project3_kenken/puzzle_files/4x4_1.txt
new file mode 100644
index 0000000..fcd1e9b
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/4x4_1.txt
@@ -0,0 +1,27 @@
+4
+8
+1,-,2
+0,0
+0,1
+1,-,2
+0,2
+1,2
+7,+,2
+1,0
+2,0
+2,/,2
+1,1
+2,1
+8,*,3
+0,3
+1,3
+2,3
+3,-,2
+3,0
+3,1
+2,/,2
+2,2
+3,2
+3, ,1
+3,3
+
diff --git a/projects/project3_kenken/puzzle_files/4x4_2.txt b/projects/project3_kenken/puzzle_files/4x4_2.txt
new file mode 100644
index 0000000..4b4ddf3
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/4x4_2.txt
@@ -0,0 +1,27 @@
+4
+8
+1, ,1
+0,3
+6,*,2
+0,0
+1,0
+3,-,2
+0,1
+1,1
+7,+,2
+0,2
+1,2
+1,-,2
+2,1
+2,2
+3,-,2
+2,0
+3,0
+2,/,2
+3,1
+3,2
+9,+,3
+1,3
+2,3
+3,3
+
diff --git a/projects/project3_kenken/puzzle_files/4x4_3.txt b/projects/project3_kenken/puzzle_files/4x4_3.txt
new file mode 100644
index 0000000..f80c871
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/4x4_3.txt
@@ -0,0 +1,28 @@
+4
+9
+1, ,1
+0,1
+2,/,2
+0,2
+0,3
+6,*,2
+0,0
+1,0
+1,-,2
+1,1
+1,2
+2,-,2
+1,3
+2,3
+3,-,2
+2,0
+3,0
+5,+,2
+2,1
+3,1
+2,/,2
+2,2
+3,2
+4, ,1
+3,3
+
diff --git a/projects/project3_kenken/puzzle_files/5x5_1.txt b/projects/project3_kenken/puzzle_files/5x5_1.txt
new file mode 100644
index 0000000..cc6ff3f
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/5x5_1.txt
@@ -0,0 +1,41 @@
+5
+13
+4,-,2
+0,0
+0,1
+2,/,2
+0,2
+1,2
+1,-,2
+0,3
+1,3
+1,-,2
+0,4
+1,4
+1,-,2
+1,0
+2,0
+3,-,2
+2,2
+2,3
+3, ,1
+2,4
+4, ,1
+3,0
+30,*,3
+1,1
+2,1
+3,1
+5,+,2
+4,0
+4,1
+15,*,2
+3,2
+4,2
+3,-,2
+3,3
+4,3
+1,-,2
+3,4
+4,4
+
diff --git a/projects/project3_kenken/puzzle_files/5x5_2.txt b/projects/project3_kenken/puzzle_files/5x5_2.txt
new file mode 100644
index 0000000..6b8a919
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/5x5_2.txt
@@ -0,0 +1,37 @@
+5
+9
+2,/,2
+0,1
+1,1
+1,-,2
+0,2
+1,2
+6,+,3
+0,3
+0,4
+1,4
+15,*,3
+0,0
+1,0
+2,0
+6,*,3
+2,1
+2,2
+3,2
+9,+,3
+1,3
+2,3
+3,3
+4,-,2
+2,4
+3,4
+120,*,4
+3,0
+3,1
+4,0
+4,1
+10,+,3
+4,2
+4,3
+4,4
+
diff --git a/projects/project3_kenken/puzzle_files/5x5_3.txt b/projects/project3_kenken/puzzle_files/5x5_3.txt
new file mode 100644
index 0000000..e8b97db
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/5x5_3.txt
@@ -0,0 +1,39 @@
+5
+11
+4,-,2
+0,0
+0,1
+2,/,2
+0,3
+0,4
+30,*,3
+0,2
+1,1
+1,2
+3,-,2
+1,3
+1,4
+1,-,2
+1,0
+2,0
+2,-,2
+2,2
+2,3
+6,+,2
+2,4
+3,4
+12,+,4
+2,1
+3,0
+3,1
+4,0
+5, ,1
+4,1
+11,+,3
+3,2
+3,3
+4,2
+1,-,2
+4,3
+4,4
+
diff --git a/projects/project3_kenken/puzzle_files/6x6_1.txt b/projects/project3_kenken/puzzle_files/6x6_1.txt
new file mode 100644
index 0000000..07d23b0
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/6x6_1.txt
@@ -0,0 +1,56 @@
+6
+17
+2,/,2
+0,4
+0,5
+9,+,3
+0,0
+0,1
+1,1
+24,*,2
+0,2
+1,2
+6,*,2
+0,3
+1,3
+8,+,2
+1,4
+1,5
+2,/,2
+1,0
+2,0
+4, ,1
+2,1
+3,/,2
+2,3
+2,4
+4,-,2
+2,2
+3,2
+1,-,2
+3,3
+3,4
+2,/,2
+2,5
+3,5
+13,+,3
+3,0
+3,1
+4,0
+1,-,2
+4,3
+4,4
+1, ,1
+4,5
+13,+,3
+4,1
+5,0
+5,1
+10,+,3
+4,2
+5,2
+5,3
+1,-,2
+5,4
+5,5
+
diff --git a/projects/project3_kenken/puzzle_files/6x6_2.txt b/projects/project3_kenken/puzzle_files/6x6_2.txt
new file mode 100644
index 0000000..8a4a11b
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/6x6_2.txt
@@ -0,0 +1,55 @@
+6
+16
+3,-,2
+0,2
+0,3
+3,-,2
+0,0
+1,0
+2,-,2
+0,1
+1,1
+1,-,2
+1,2
+1,3
+720,*,4
+0,4
+0,5
+1,4
+1,5
+12,+,3
+2,0
+2,1
+2,2
+5,-,2
+2,3
+2,4
+4,-,2
+3,1
+3,2
+12,*,3
+2,5
+3,4
+3,5
+3,/,2
+3,0
+4,0
+3,-,2
+3,3
+4,3
+2,-,2
+4,4
+4,5
+60,*,3
+4,1
+5,0
+5,1
+2,-,2
+4,2
+5,2
+1,-,2
+5,3
+5,4
+1, ,1
+5,5
+
diff --git a/projects/project3_kenken/puzzle_files/7x7_1.txt b/projects/project3_kenken/puzzle_files/7x7_1.txt
new file mode 100644
index 0000000..fd59a27
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/7x7_1.txt
@@ -0,0 +1,73 @@
+7
+21
+3, ,1
+0,1
+3,-,2
+0,2
+0,3
+30,*,3
+0,0
+1,0
+1,1
+13,+,3
+0,4
+1,3
+1,4
+60,*,3
+0,5
+0,6
+1,5
+2,-,2
+2,0
+2,1
+5,-,2
+1,2
+2,2
+28,*,2
+2,4
+2,5
+1,-,2
+1,6
+2,6
+1,-,2
+3,1
+3,2
+3,+,2
+2,3
+3,3
+4,-,2
+3,5
+3,6
+18,+,3
+3,0
+4,0
+4,1
+3,/,2
+4,2
+4,3
+11,+,2
+3,4
+4,4
+10,+,3
+4,5
+4,6
+5,5
+9,+,3
+5,0
+5,1
+6,0
+70,*,3
+5,2
+6,1
+6,2
+2,-,2
+5,3
+6,3
+3,/,2
+5,4
+6,4
+15,+,3
+5,6
+6,5
+6,6
+
diff --git a/projects/project3_kenken/puzzle_files/7x7_2.txt b/projects/project3_kenken/puzzle_files/7x7_2.txt
new file mode 100644
index 0000000..e3d03e9
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/7x7_2.txt
@@ -0,0 +1,74 @@
+7
+22
+120,*,3
+0,1
+0,2
+0,3
+6,-,2
+0,4
+0,5
+2,/,2
+0,0
+1,0
+12,+,3
+1,1
+1,2
+1,3
+6, ,1
+1,4
+2,-,2
+0,6
+1,6
+5,-,2
+2,0
+2,1
+2,/,2
+2,3
+2,4
+7,+,3
+1,5
+2,5
+2,6
+10,+,2
+3,0
+3,1
+5,-,2
+3,5
+3,6
+14,+,3
+2,2
+3,2
+4,2
+20,*,3
+3,3
+3,4
+4,4
+3,/,2
+4,5
+4,6
+2,-,2
+4,0
+5,0
+4,-,2
+4,1
+5,1
+7,+,2
+4,3
+5,3
+8,+,2
+6,0
+6,1
+5,-,2
+5,2
+6,2
+16,+,3
+5,4
+6,3
+6,4
+1,-,2
+5,5
+6,5
+2,-,2
+5,6
+6,6
+
diff --git a/projects/project3_kenken/puzzle_files/8x8_1.txt b/projects/project3_kenken/puzzle_files/8x8_1.txt
new file mode 100644
index 0000000..9a3f5f1
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/8x8_1.txt
@@ -0,0 +1,92 @@
+8
+25
+14,+,2
+0,2
+0,3
+3,/,2
+0,6
+0,7
+560,*,4
+0,0
+0,1
+1,0
+1,1
+48,*,3
+0,4
+1,3
+1,4
+5,-,2
+0,5
+1,5
+6,-,2
+1,2
+2,2
+4,-,2
+2,3
+2,4
+12,+,3
+1,6
+2,5
+2,6
+19,+,3
+2,0
+2,1
+3,1
+17,+,4
+1,7
+2,7
+3,6
+3,7
+17,+,3
+3,2
+4,1
+4,2
+3,-,2
+3,3
+4,3
+126,*,3
+3,4
+3,5
+4,4
+6,+,3
+3,0
+4,0
+5,0
+3,+,2
+5,2
+5,3
+6,*,2
+5,1
+6,1
+7,+,2
+6,2
+6,3
+240,*,3
+4,5
+5,5
+6,5
+16,+,4
+4,6
+4,7
+5,6
+6,6
+1,-,2
+5,7
+6,7
+13,+,2
+6,0
+7,0
+1,-,2
+7,1
+7,2
+18,+,4
+5,4
+6,4
+7,3
+7,4
+1, ,1
+7,5
+2,/,2
+7,6
+7,7
+
diff --git a/projects/project3_kenken/puzzle_files/8x8_2.txt b/projects/project3_kenken/puzzle_files/8x8_2.txt
new file mode 100644
index 0000000..01e6de9
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/8x8_2.txt
@@ -0,0 +1,92 @@
+8
+25
+8,+,2
+0,3
+0,4
+6,+,2
+0,0
+1,0
+192,*,3
+0,1
+0,2
+1,1
+14,+,3
+0,5
+1,4
+1,5
+15,+,3
+0,6
+0,7
+1,6
+9,+,3
+1,2
+1,3
+2,3
+1,-,2
+2,4
+2,5
+15,+,2
+2,0
+3,0
+2,/,2
+2,1
+3,1
+9,+,2
+2,2
+3,2
+3,-,2
+4,0
+4,1
+17,+,3
+3,3
+3,4
+4,3
+10,*,3
+3,5
+4,4
+4,5
+6,+,3
+2,6
+3,6
+4,6
+20,+,4
+1,7
+2,7
+3,7
+4,7
+60,*,4
+4,2
+5,0
+5,1
+5,2
+4,/,2
+5,3
+5,4
+2,/,2
+6,0
+6,1
+2,/,2
+5,5
+6,5
+14,+,3
+5,6
+5,7
+6,7
+1,-,2
+7,0
+7,1
+56,*,2
+6,2
+7,2
+90,*,4
+6,3
+6,4
+7,3
+7,4
+5, ,1
+7,5
+168,*,3
+6,6
+7,6
+7,7
+
diff --git a/projects/project3_kenken/puzzle_files/9x9_1.txt b/projects/project3_kenken/puzzle_files/9x9_1.txt
new file mode 100644
index 0000000..40654c0
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/9x9_1.txt
@@ -0,0 +1,119 @@
+9
+35
+2,/,2
+0,0
+1,0
+21,*,3
+0,1
+0,2
+1,2
+7,-,2
+0,3
+0,4
+4,/,2
+1,3
+1,4
+3,-,2
+0,5
+1,5
+1,-,2
+0,6
+0,7
+2,-,2
+1,6
+1,7
+17,+,2
+0,8
+1,8
+14,+,3
+1,1
+2,1
+2,2
+3,-,2
+2,4
+2,5
+2,/,2
+2,3
+3,3
+20,+,3
+2,6
+2,7
+3,6
+3,-,2
+2,8
+3,8
+54,*,3
+3,1
+3,2
+4,1
+4,/,2
+4,2
+4,3
+17,+,2
+4,5
+4,6
+7, ,1
+4,8
+14,+,4
+2,0
+3,0
+4,0
+5,0
+17,+,2
+5,1
+5,2
+23,+,4
+3,4
+3,5
+4,4
+5,4
+3, ,1
+5,5
+160,*,3
+3,7
+4,7
+5,7
+2,-,2
+5,3
+6,3
+8,*,2
+6,4
+6,5
+6,+,3
+5,6
+6,6
+6,7
+3,/,2
+5,8
+6,8
+720,*,4
+6,0
+6,1
+6,2
+7,1
+4,/,2
+7,3
+7,4
+8,-,2
+7,6
+7,7
+4,-,2
+7,0
+8,0
+20,+,3
+7,2
+8,1
+8,2
+8,-,2
+8,3
+8,4
+10,+,2
+7,5
+8,5
+3,/,2
+8,6
+8,7
+2,-,2
+7,8
+8,8
+
diff --git a/projects/project3_kenken/puzzle_files/9x9_2.txt b/projects/project3_kenken/puzzle_files/9x9_2.txt
new file mode 100644
index 0000000..f6bff8e
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/9x9_2.txt
@@ -0,0 +1,119 @@
+9
+35
+4,/,2
+0,0
+0,1
+6,-,2
+0,2
+0,3
+5,-,2
+0,7
+0,8
+140,*,3
+1,1
+1,2
+1,3
+18,*,3
+0,4
+1,4
+1,5
+20,+,3
+0,5
+0,6
+1,6
+7,-,2
+1,7
+1,8
+5,-,2
+2,1
+2,2
+5,-,2
+2,4
+2,5
+1620,*,4
+1,0
+2,0
+3,0
+3,1
+5,-,2
+2,3
+3,3
+1,-,2
+3,5
+3,6
+11,+,3
+2,6
+2,7
+3,7
+4,-,2
+2,8
+3,8
+8,-,2
+4,0
+4,1
+10,*,2
+3,2
+4,2
+40,*,2
+3,4
+4,4
+56,*,2
+4,5
+4,6
+2,/,2
+5,0
+5,1
+1,-,2
+4,3
+5,3
+6,-,2
+5,5
+5,6
+2,/,2
+4,7
+5,7
+2,-,2
+4,8
+5,8
+11,+,2
+6,0
+6,1
+6,*,3
+5,2
+6,2
+6,3
+3,-,2
+5,4
+6,4
+252,*,3
+6,6
+6,7
+6,8
+10,+,2
+7,3
+7,4
+1,-,2
+6,5
+7,5
+10,+,2
+7,0
+8,0
+6,-,2
+7,1
+8,1
+48,*,2
+7,2
+8,2
+24,*,2
+8,3
+8,4
+1080,*,4
+7,6
+7,7
+8,5
+8,6
+20,*,3
+7,8
+8,7
+8,8
+
diff --git a/projects/project3_kenken/puzzle_files/9x9_3.txt b/projects/project3_kenken/puzzle_files/9x9_3.txt
new file mode 100644
index 0000000..8285929
--- /dev/null
+++ b/projects/project3_kenken/puzzle_files/9x9_3.txt
@@ -0,0 +1,118 @@
+9
+34
+42,*,3
+0,0
+0,1
+0,2
+8, ,1
+0,3
+1,-,2
+0,4
+0,5
+4,-,2
+0,6
+0,7
+2,-,2
+1,6
+1,7
+5,-,2
+0,8
+1,8
+2,/,2
+1,0
+2,0
+6,*,2
+1,1
+2,1
+19,+,4
+1,2
+1,3
+1,4
+2,2
+56,*,3
+1,5
+2,4
+2,5
+2,-,2
+2,6
+2,7
+1,-,2
+3,1
+3,2
+2,/,2
+2,3
+3,3
+7,+,3
+3,4
+3,5
+3,6
+15,+,3
+2,8
+3,7
+3,8
+19,+,3
+3,0
+4,0
+4,1
+240,*,4
+4,2
+4,3
+4,4
+4,5
+2,/,2
+4,6
+4,7
+15,+,5
+5,1
+5,2
+5,3
+5,4
+5,5
+6, ,1
+5,6
+21,*,2
+4,8
+5,8
+8,-,2
+5,0
+6,0
+2,/,2
+6,1
+6,2
+7,-,2
+6,3
+6,4
+2,-,2
+6,5
+6,6
+5,-,2
+5,7
+6,7
+15,+,3
+6,8
+7,7
+7,8
+12,+,3
+7,0
+7,1
+8,0
+72,*,3
+7,2
+8,1
+8,2
+16,+,2
+7,3
+8,3
+13,+,2
+7,4
+8,4
+20,+,3
+7,5
+7,6
+8,5
+3,-,2
+8,6
+8,7
+2, ,1
+8,8
+
diff --git a/projects/project3_kenken/stab2/3x3_1.txt b/projects/project3_kenken/stab2/3x3_1.txt
new file mode 100644
index 0000000..b23e027
--- /dev/null
+++ b/projects/project3_kenken/stab2/3x3_1.txt
@@ -0,0 +1,17 @@
+3
+5
+3, ,1
+0,0
+6,*,2
+0,1
+1,1
+2,/,2
+0,2
+1,2
+2,/,2
+1,0
+2,0
+2,-,2
+2,1
+2,2
+
diff --git a/projects/project3_kenken/stab2/3x3_2.txt b/projects/project3_kenken/stab2/3x3_2.txt
new file mode 100644
index 0000000..2556aa6
--- /dev/null
+++ b/projects/project3_kenken/stab2/3x3_2.txt
@@ -0,0 +1,17 @@
+3
+5
+2, ,1
+0,0
+9,*,3
+0,1
+0,2
+1,2
+2,-,2
+1,0
+2,0
+2,/,2
+1,1
+2,1
+2, ,1
+2,2
+
diff --git a/projects/project3_kenken/stab2/3x3_3.txt b/projects/project3_kenken/stab2/3x3_3.txt
new file mode 100644
index 0000000..a844c5b
--- /dev/null
+++ b/projects/project3_kenken/stab2/3x3_3.txt
@@ -0,0 +1,17 @@
+3
+5
+1,-,2
+0,1
+0,2
+2,-,2
+0,0
+1,0
+2, ,1
+1,1
+3,+,2
+2,0
+2,1
+3,/,2
+1,2
+2,2
+
diff --git a/projects/project3_kenken/stab2/4x4_1.txt b/projects/project3_kenken/stab2/4x4_1.txt
new file mode 100644
index 0000000..fcd1e9b
--- /dev/null
+++ b/projects/project3_kenken/stab2/4x4_1.txt
@@ -0,0 +1,27 @@
+4
+8
+1,-,2
+0,0
+0,1
+1,-,2
+0,2
+1,2
+7,+,2
+1,0
+2,0
+2,/,2
+1,1
+2,1
+8,*,3
+0,3
+1,3
+2,3
+3,-,2
+3,0
+3,1
+2,/,2
+2,2
+3,2
+3, ,1
+3,3
+
diff --git a/projects/project3_kenken/stab2/4x4_2.txt b/projects/project3_kenken/stab2/4x4_2.txt
new file mode 100644
index 0000000..4b4ddf3
--- /dev/null
+++ b/projects/project3_kenken/stab2/4x4_2.txt
@@ -0,0 +1,27 @@
+4
+8
+1, ,1
+0,3
+6,*,2
+0,0
+1,0
+3,-,2
+0,1
+1,1
+7,+,2
+0,2
+1,2
+1,-,2
+2,1
+2,2
+3,-,2
+2,0
+3,0
+2,/,2
+3,1
+3,2
+9,+,3
+1,3
+2,3
+3,3
+
diff --git a/projects/project3_kenken/stab2/4x4_3.txt b/projects/project3_kenken/stab2/4x4_3.txt
new file mode 100644
index 0000000..f80c871
--- /dev/null
+++ b/projects/project3_kenken/stab2/4x4_3.txt
@@ -0,0 +1,28 @@
+4
+9
+1, ,1
+0,1
+2,/,2
+0,2
+0,3
+6,*,2
+0,0
+1,0
+1,-,2
+1,1
+1,2
+2,-,2
+1,3
+2,3
+3,-,2
+2,0
+3,0
+5,+,2
+2,1
+3,1
+2,/,2
+2,2
+3,2
+4, ,1
+3,3
+
diff --git a/projects/project3_kenken/stab2/5x5_1.txt b/projects/project3_kenken/stab2/5x5_1.txt
new file mode 100644
index 0000000..cc6ff3f
--- /dev/null
+++ b/projects/project3_kenken/stab2/5x5_1.txt
@@ -0,0 +1,41 @@
+5
+13
+4,-,2
+0,0
+0,1
+2,/,2
+0,2
+1,2
+1,-,2
+0,3
+1,3
+1,-,2
+0,4
+1,4
+1,-,2
+1,0
+2,0
+3,-,2
+2,2
+2,3
+3, ,1
+2,4
+4, ,1
+3,0
+30,*,3
+1,1
+2,1
+3,1
+5,+,2
+4,0
+4,1
+15,*,2
+3,2
+4,2
+3,-,2
+3,3
+4,3
+1,-,2
+3,4
+4,4
+
diff --git a/projects/project3_kenken/stab2/5x5_2.txt b/projects/project3_kenken/stab2/5x5_2.txt
new file mode 100644
index 0000000..6b8a919
--- /dev/null
+++ b/projects/project3_kenken/stab2/5x5_2.txt
@@ -0,0 +1,37 @@
+5
+9
+2,/,2
+0,1
+1,1
+1,-,2
+0,2
+1,2
+6,+,3
+0,3
+0,4
+1,4
+15,*,3
+0,0
+1,0
+2,0
+6,*,3
+2,1
+2,2
+3,2
+9,+,3
+1,3
+2,3
+3,3
+4,-,2
+2,4
+3,4
+120,*,4
+3,0
+3,1
+4,0
+4,1
+10,+,3
+4,2
+4,3
+4,4
+
diff --git a/projects/project3_kenken/stab2/5x5_3.txt b/projects/project3_kenken/stab2/5x5_3.txt
new file mode 100644
index 0000000..e8b97db
--- /dev/null
+++ b/projects/project3_kenken/stab2/5x5_3.txt
@@ -0,0 +1,39 @@
+5
+11
+4,-,2
+0,0
+0,1
+2,/,2
+0,3
+0,4
+30,*,3
+0,2
+1,1
+1,2
+3,-,2
+1,3
+1,4
+1,-,2
+1,0
+2,0
+2,-,2
+2,2
+2,3
+6,+,2
+2,4
+3,4
+12,+,4
+2,1
+3,0
+3,1
+4,0
+5, ,1
+4,1
+11,+,3
+3,2
+3,3
+4,2
+1,-,2
+4,3
+4,4
+
diff --git a/projects/project3_kenken/stab2/6x6_1.txt b/projects/project3_kenken/stab2/6x6_1.txt
new file mode 100644
index 0000000..07d23b0
--- /dev/null
+++ b/projects/project3_kenken/stab2/6x6_1.txt
@@ -0,0 +1,56 @@
+6
+17
+2,/,2
+0,4
+0,5
+9,+,3
+0,0
+0,1
+1,1
+24,*,2
+0,2
+1,2
+6,*,2
+0,3
+1,3
+8,+,2
+1,4
+1,5
+2,/,2
+1,0
+2,0
+4, ,1
+2,1
+3,/,2
+2,3
+2,4
+4,-,2
+2,2
+3,2
+1,-,2
+3,3
+3,4
+2,/,2
+2,5
+3,5
+13,+,3
+3,0
+3,1
+4,0
+1,-,2
+4,3
+4,4
+1, ,1
+4,5
+13,+,3
+4,1
+5,0
+5,1
+10,+,3
+4,2
+5,2
+5,3
+1,-,2
+5,4
+5,5
+
diff --git a/projects/project3_kenken/stab2/6x6_2.txt b/projects/project3_kenken/stab2/6x6_2.txt
new file mode 100644
index 0000000..8a4a11b
--- /dev/null
+++ b/projects/project3_kenken/stab2/6x6_2.txt
@@ -0,0 +1,55 @@
+6
+16
+3,-,2
+0,2
+0,3
+3,-,2
+0,0
+1,0
+2,-,2
+0,1
+1,1
+1,-,2
+1,2
+1,3
+720,*,4
+0,4
+0,5
+1,4
+1,5
+12,+,3
+2,0
+2,1
+2,2
+5,-,2
+2,3
+2,4
+4,-,2
+3,1
+3,2
+12,*,3
+2,5
+3,4
+3,5
+3,/,2
+3,0
+4,0
+3,-,2
+3,3
+4,3
+2,-,2
+4,4
+4,5
+60,*,3
+4,1
+5,0
+5,1
+2,-,2
+4,2
+5,2
+1,-,2
+5,3
+5,4
+1, ,1
+5,5
+
diff --git a/projects/project3_kenken/stab2/7x7_1.txt b/projects/project3_kenken/stab2/7x7_1.txt
new file mode 100644
index 0000000..fd59a27
--- /dev/null
+++ b/projects/project3_kenken/stab2/7x7_1.txt
@@ -0,0 +1,73 @@
+7
+21
+3, ,1
+0,1
+3,-,2
+0,2
+0,3
+30,*,3
+0,0
+1,0
+1,1
+13,+,3
+0,4
+1,3
+1,4
+60,*,3
+0,5
+0,6
+1,5
+2,-,2
+2,0
+2,1
+5,-,2
+1,2
+2,2
+28,*,2
+2,4
+2,5
+1,-,2
+1,6
+2,6
+1,-,2
+3,1
+3,2
+3,+,2
+2,3
+3,3
+4,-,2
+3,5
+3,6
+18,+,3
+3,0
+4,0
+4,1
+3,/,2
+4,2
+4,3
+11,+,2
+3,4
+4,4
+10,+,3
+4,5
+4,6
+5,5
+9,+,3
+5,0
+5,1
+6,0
+70,*,3
+5,2
+6,1
+6,2
+2,-,2
+5,3
+6,3
+3,/,2
+5,4
+6,4
+15,+,3
+5,6
+6,5
+6,6
+
diff --git a/projects/project3_kenken/stab2/7x7_2.txt b/projects/project3_kenken/stab2/7x7_2.txt
new file mode 100644
index 0000000..e3d03e9
--- /dev/null
+++ b/projects/project3_kenken/stab2/7x7_2.txt
@@ -0,0 +1,74 @@
+7
+22
+120,*,3
+0,1
+0,2
+0,3
+6,-,2
+0,4
+0,5
+2,/,2
+0,0
+1,0
+12,+,3
+1,1
+1,2
+1,3
+6, ,1
+1,4
+2,-,2
+0,6
+1,6
+5,-,2
+2,0
+2,1
+2,/,2
+2,3
+2,4
+7,+,3
+1,5
+2,5
+2,6
+10,+,2
+3,0
+3,1
+5,-,2
+3,5
+3,6
+14,+,3
+2,2
+3,2
+4,2
+20,*,3
+3,3
+3,4
+4,4
+3,/,2
+4,5
+4,6
+2,-,2
+4,0
+5,0
+4,-,2
+4,1
+5,1
+7,+,2
+4,3
+5,3
+8,+,2
+6,0
+6,1
+5,-,2
+5,2
+6,2
+16,+,3
+5,4
+6,3
+6,4
+1,-,2
+5,5
+6,5
+2,-,2
+5,6
+6,6
+
diff --git a/projects/project3_kenken/stab2/8x8_1.txt b/projects/project3_kenken/stab2/8x8_1.txt
new file mode 100644
index 0000000..9a3f5f1
--- /dev/null
+++ b/projects/project3_kenken/stab2/8x8_1.txt
@@ -0,0 +1,92 @@
+8
+25
+14,+,2
+0,2
+0,3
+3,/,2
+0,6
+0,7
+560,*,4
+0,0
+0,1
+1,0
+1,1
+48,*,3
+0,4
+1,3
+1,4
+5,-,2
+0,5
+1,5
+6,-,2
+1,2
+2,2
+4,-,2
+2,3
+2,4
+12,+,3
+1,6
+2,5
+2,6
+19,+,3
+2,0
+2,1
+3,1
+17,+,4
+1,7
+2,7
+3,6
+3,7
+17,+,3
+3,2
+4,1
+4,2
+3,-,2
+3,3
+4,3
+126,*,3
+3,4
+3,5
+4,4
+6,+,3
+3,0
+4,0
+5,0
+3,+,2
+5,2
+5,3
+6,*,2
+5,1
+6,1
+7,+,2
+6,2
+6,3
+240,*,3
+4,5
+5,5
+6,5
+16,+,4
+4,6
+4,7
+5,6
+6,6
+1,-,2
+5,7
+6,7
+13,+,2
+6,0
+7,0
+1,-,2
+7,1
+7,2
+18,+,4
+5,4
+6,4
+7,3
+7,4
+1, ,1
+7,5
+2,/,2
+7,6
+7,7
+
diff --git a/projects/project3_kenken/stab2/8x8_2.txt b/projects/project3_kenken/stab2/8x8_2.txt
new file mode 100644
index 0000000..01e6de9
--- /dev/null
+++ b/projects/project3_kenken/stab2/8x8_2.txt
@@ -0,0 +1,92 @@
+8
+25
+8,+,2
+0,3
+0,4
+6,+,2
+0,0
+1,0
+192,*,3
+0,1
+0,2
+1,1
+14,+,3
+0,5
+1,4
+1,5
+15,+,3
+0,6
+0,7
+1,6
+9,+,3
+1,2
+1,3
+2,3
+1,-,2
+2,4
+2,5
+15,+,2
+2,0
+3,0
+2,/,2
+2,1
+3,1
+9,+,2
+2,2
+3,2
+3,-,2
+4,0
+4,1
+17,+,3
+3,3
+3,4
+4,3
+10,*,3
+3,5
+4,4
+4,5
+6,+,3
+2,6
+3,6
+4,6
+20,+,4
+1,7
+2,7
+3,7
+4,7
+60,*,4
+4,2
+5,0
+5,1
+5,2
+4,/,2
+5,3
+5,4
+2,/,2
+6,0
+6,1
+2,/,2
+5,5
+6,5
+14,+,3
+5,6
+5,7
+6,7
+1,-,2
+7,0
+7,1
+56,*,2
+6,2
+7,2
+90,*,4
+6,3
+6,4
+7,3
+7,4
+5, ,1
+7,5
+168,*,3
+6,6
+7,6
+7,7
+
diff --git a/projects/project3_kenken/stab2/9x9_1.txt b/projects/project3_kenken/stab2/9x9_1.txt
new file mode 100644
index 0000000..40654c0
--- /dev/null
+++ b/projects/project3_kenken/stab2/9x9_1.txt
@@ -0,0 +1,119 @@
+9
+35
+2,/,2
+0,0
+1,0
+21,*,3
+0,1
+0,2
+1,2
+7,-,2
+0,3
+0,4
+4,/,2
+1,3
+1,4
+3,-,2
+0,5
+1,5
+1,-,2
+0,6
+0,7
+2,-,2
+1,6
+1,7
+17,+,2
+0,8
+1,8
+14,+,3
+1,1
+2,1
+2,2
+3,-,2
+2,4
+2,5
+2,/,2
+2,3
+3,3
+20,+,3
+2,6
+2,7
+3,6
+3,-,2
+2,8
+3,8
+54,*,3
+3,1
+3,2
+4,1
+4,/,2
+4,2
+4,3
+17,+,2
+4,5
+4,6
+7, ,1
+4,8
+14,+,4
+2,0
+3,0
+4,0
+5,0
+17,+,2
+5,1
+5,2
+23,+,4
+3,4
+3,5
+4,4
+5,4
+3, ,1
+5,5
+160,*,3
+3,7
+4,7
+5,7
+2,-,2
+5,3
+6,3
+8,*,2
+6,4
+6,5
+6,+,3
+5,6
+6,6
+6,7
+3,/,2
+5,8
+6,8
+720,*,4
+6,0
+6,1
+6,2
+7,1
+4,/,2
+7,3
+7,4
+8,-,2
+7,6
+7,7
+4,-,2
+7,0
+8,0
+20,+,3
+7,2
+8,1
+8,2
+8,-,2
+8,3
+8,4
+10,+,2
+7,5
+8,5
+3,/,2
+8,6
+8,7
+2,-,2
+7,8
+8,8
+
diff --git a/projects/project3_kenken/stab2/9x9_2.txt b/projects/project3_kenken/stab2/9x9_2.txt
new file mode 100644
index 0000000..f6bff8e
--- /dev/null
+++ b/projects/project3_kenken/stab2/9x9_2.txt
@@ -0,0 +1,119 @@
+9
+35
+4,/,2
+0,0
+0,1
+6,-,2
+0,2
+0,3
+5,-,2
+0,7
+0,8
+140,*,3
+1,1
+1,2
+1,3
+18,*,3
+0,4
+1,4
+1,5
+20,+,3
+0,5
+0,6
+1,6
+7,-,2
+1,7
+1,8
+5,-,2
+2,1
+2,2
+5,-,2
+2,4
+2,5
+1620,*,4
+1,0
+2,0
+3,0
+3,1
+5,-,2
+2,3
+3,3
+1,-,2
+3,5
+3,6
+11,+,3
+2,6
+2,7
+3,7
+4,-,2
+2,8
+3,8
+8,-,2
+4,0
+4,1
+10,*,2
+3,2
+4,2
+40,*,2
+3,4
+4,4
+56,*,2
+4,5
+4,6
+2,/,2
+5,0
+5,1
+1,-,2
+4,3
+5,3
+6,-,2
+5,5
+5,6
+2,/,2
+4,7
+5,7
+2,-,2
+4,8
+5,8
+11,+,2
+6,0
+6,1
+6,*,3
+5,2
+6,2
+6,3
+3,-,2
+5,4
+6,4
+252,*,3
+6,6
+6,7
+6,8
+10,+,2
+7,3
+7,4
+1,-,2
+6,5
+7,5
+10,+,2
+7,0
+8,0
+6,-,2
+7,1
+8,1
+48,*,2
+7,2
+8,2
+24,*,2
+8,3
+8,4
+1080,*,4
+7,6
+7,7
+8,5
+8,6
+20,*,3
+7,8
+8,7
+8,8
+
diff --git a/projects/project3_kenken/stab2/9x9_3.txt b/projects/project3_kenken/stab2/9x9_3.txt
new file mode 100644
index 0000000..8285929
--- /dev/null
+++ b/projects/project3_kenken/stab2/9x9_3.txt
@@ -0,0 +1,118 @@
+9
+34
+42,*,3
+0,0
+0,1
+0,2
+8, ,1
+0,3
+1,-,2
+0,4
+0,5
+4,-,2
+0,6
+0,7
+2,-,2
+1,6
+1,7
+5,-,2
+0,8
+1,8
+2,/,2
+1,0
+2,0
+6,*,2
+1,1
+2,1
+19,+,4
+1,2
+1,3
+1,4
+2,2
+56,*,3
+1,5
+2,4
+2,5
+2,-,2
+2,6
+2,7
+1,-,2
+3,1
+3,2
+2,/,2
+2,3
+3,3
+7,+,3
+3,4
+3,5
+3,6
+15,+,3
+2,8
+3,7
+3,8
+19,+,3
+3,0
+4,0
+4,1
+240,*,4
+4,2
+4,3
+4,4
+4,5
+2,/,2
+4,6
+4,7
+15,+,5
+5,1
+5,2
+5,3
+5,4
+5,5
+6, ,1
+5,6
+21,*,2
+4,8
+5,8
+8,-,2
+5,0
+6,0
+2,/,2
+6,1
+6,2
+7,-,2
+6,3
+6,4
+2,-,2
+6,5
+6,6
+5,-,2
+5,7
+6,7
+15,+,3
+6,8
+7,7
+7,8
+12,+,3
+7,0
+7,1
+8,0
+72,*,3
+7,2
+8,1
+8,2
+16,+,2
+7,3
+8,3
+13,+,2
+7,4
+8,4
+20,+,3
+7,5
+7,6
+8,5
+3,-,2
+8,6
+8,7
+2, ,1
+8,8
+
diff --git a/projects/project3_kenken/stab2/Constraint.java b/projects/project3_kenken/stab2/Constraint.java
new file mode 100644
index 0000000..4d97055
--- /dev/null
+++ b/projects/project3_kenken/stab2/Constraint.java
@@ -0,0 +1,12 @@
+public class Constraint
+{
+ public String op;
+ public Position[] positions;
+ public int targNumber;
+ public Constraint(int targNumber,String op,Position[] pos)
+ {
+ this.op = op;
+ positions = pos;
+ this.targNumber = targNumber;
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/KNode.java b/projects/project3_kenken/stab2/KNode.java
new file mode 100644
index 0000000..e82e0e2
--- /dev/null
+++ b/projects/project3_kenken/stab2/KNode.java
@@ -0,0 +1,18 @@
+public class KNode
+{
+ private KNode next = null;
+ private int[] data;
+ public KNode(int[] d, KNode n)
+ {
+ data = d;
+ next = n;
+ }
+ public int[] getData()
+ {
+ return data;
+ }
+ public KNode getNext()
+ {
+ return next;
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/KStack.java b/projects/project3_kenken/stab2/KStack.java
new file mode 100644
index 0000000..613f9f2
--- /dev/null
+++ b/projects/project3_kenken/stab2/KStack.java
@@ -0,0 +1,54 @@
+public class KStack
+{
+ private KNode head;
+ private int length;
+ public KStack()
+ {
+ length = 0;
+ }
+ public int[] peek()
+ {
+ return head.getData();
+ }
+ public int[] pop()
+ {
+ int[] output = head.getData();
+ head = head.getNext();
+ length--;
+ return output;
+ }
+ public void push(int[] i)
+ {
+ head = new KNode(i,head);
+ length++;
+ }
+ public boolean hasNext()
+ {
+ return head != null;
+ }
+ public int getLength()
+ {
+ return length;
+ }
+ public String toString()
+ {
+ String output = "";
+ for(KNode tmp = head; tmp != null; tmp=tmp.getNext())
+ {
+ output += tmp.getData() + " ";
+ }
+ return output;
+ }
+ public int[][] toArray()
+ {
+ int[][] output = new int[length][4];
+ int i = length-1;
+ for(KNode tmp = head; tmp != null; tmp = tmp.getNext())
+ {
+ output[i] = tmp.getData();
+ i--;
+ }
+ return output;
+ }
+
+}
diff --git a/projects/project3_kenken/stab2/Position.java b/projects/project3_kenken/stab2/Position.java
new file mode 100644
index 0000000..b036299
--- /dev/null
+++ b/projects/project3_kenken/stab2/Position.java
@@ -0,0 +1,11 @@
+public class Position
+{
+ public int x;
+ public int y;
+ public Position(int x, int y)
+ {
+ this.x = x;
+ this.y = y;
+ }
+
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/Solver.java b/projects/project3_kenken/stab2/Solver.java
new file mode 100644
index 0000000..18a864b
--- /dev/null
+++ b/projects/project3_kenken/stab2/Solver.java
@@ -0,0 +1,865 @@
+import java.util.Scanner;
+import java.io.*;
+
+public class Solver
+{
+ public int[][] puzzle;
+ public Constraint[] constraints;
+ public int size;
+ public Solver(String filename)
+ {
+ parsePuzzle(filename);
+ /*puzzle = new int[3][3];
+ constraints = new Constraint[5];
+
+ Position[] p1 = new Position[1];
+ p1[0] = new Position(0,0);
+ constraints[0] = new Constraint(3," ",p1);
+
+ Position[] p2 = new Position[2];
+ p2[0] = new Position(1,0);
+ p2[1] = new Position(1,1);
+ constraints[1] = new Constraint(6,"*",p2);
+
+ Position[] p3 = new Position[2];
+ p3[0] = new Position(2,0);
+ p3[1] = new Position(2,1);
+ constraints[2] = new Constraint(2,"/",p3);
+
+ Position[] p4 = new Position[2];
+ p4[0] = new Position(0,1);
+ p4[1] = new Position(0,2);
+ constraints[3] = new Constraint(2,"/",p4);
+
+ Position[] p5 = new Position[2];
+ p5[0] = new Position(1,2);
+ p5[1] = new Position(2,2);
+ constraints[4] = new Constraint(2,"-",p5);
+
+ size = puzzle.length;
+ */
+ System.out.println("Everything parsed, data is:");
+ System.out.println("Puzzle:");
+ printArray(puzzle);
+ System.out.println("Constraints:");
+ printArray(constraints);
+ System.out.println("size: " + size);
+ }
+ private void parsePuzzle(String filename)
+ {
+ Scanner s = null;
+ try
+ {
+ s = new Scanner(new FileInputStream(filename));
+ }
+ catch (Exception e)
+ {
+ System.out.println("Something went terribly wrong!\n" + e);
+ }
+ size = Integer.parseInt(s.nextLine().replaceAll("\n",""));
+
+ puzzle = new int[size][size];
+
+ constraints = new Constraint[Integer.parseInt(s.nextLine().replaceAll("\n",""))];
+
+ //System.out.println("Puzzle size: " + size + " Cages: " + p.length);
+ for(int i = 0; s.hasNextLine();i++)
+ {
+ String t1 = s.nextLine();
+ System.out.println("Praseing: " + t1);
+ String[] t2 = t1.split(",");
+ System.out.println("Parts length: " + t2.length);
+ if(t2.length > 1)
+ {
+ Position[] allcells = new Position[Integer.parseInt(t2[2])];
+ for(int j = 0; j < Integer.parseInt(t2[2]);j++)
+ {
+ String[] coords = s.nextLine().split(",");
+ allcells[j] = new Position(Integer.parseInt(coords[1]),Integer.parseInt(coords[0]));
+ }
+ constraints[i] = new Constraint(Integer.parseInt(t2[0]),t2[1],allcells);
+ System.out.println("Created new constraint(" + Integer.parseInt(t2[0]) + "," + t2[1] + ",");
+ printArray(allcells);
+ /*
+ for(Position c : allcells)
+ {
+ constraints[i] = new Constraint(Integer.parseInt(t2[0]),t2[1],allcells);
+ }
+ */
+ //p[i] = new KCage(Integer.parseInt(t2[0]),getOp(t2[1]),allcells);
+ //System.out.println("Created " + p[i]);
+ }
+ }
+ }
+ public void put(int x, int y, int num)
+ {
+ puzzle[x][y] = num;
+ }
+ public int remove(int x, int y)
+ {
+ int num = puzzle[x][y];
+ puzzle[x][y] = 0;
+ return num;
+ }
+ public boolean[] getPossibilities(int x, int y)
+ {
+ boolean[] row = getPossibilitiesByRow(y);
+ boolean[] col = getPossibilitiesByCol(x);
+ boolean[] cage = getPossibilitiesByCage(x,y);
+ boolean[] output = new boolean[size];
+ System.out.println("By row:");
+ printArray(row);
+ System.out.println("By col:");
+ printArray(col);
+ System.out.println("By cage:");
+ printArray(cage);
+ for(int i = 0; i < size; i++)
+ {
+ if(row[i] && col[i] && cage[i])
+ {
+ output[i] = true;
+ }
+ }
+ System.out.println("Possibilities for (" + x + "," + y + ") are ");
+ printArray(output);
+ return output;
+ }
+ public boolean[] getPossibilitiesByRow(int row)
+ {
+ boolean[] possibs = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {//Set all places is possibs to true
+ possibs[j] = true;
+ }
+ //Find all the possibilities
+ for(int j = 0; j < size; j++)
+ { //For every other place
+ if(puzzle[j][row] != 0)
+ {
+ //System.out.println("Setting (" + j + "," + row + "): " + puzzle[j][row] + " to false");
+ possibs[puzzle[j][row]-1] = false;
+ }
+ }
+ return possibs;
+ }
+ public boolean[] getPossibilitiesByCol(int col)
+ {
+ boolean[] possibs = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {//Set all places is possibs to true
+ possibs[j] = true;
+ }
+ //Find all the possibilities
+ for(int j = 0; j < size; j++)
+ { //For every other place
+ if(puzzle[col][j] != 0)
+ {
+ //System.out.println("Setting (" + col + "," + j + "): " + puzzle[col][j] + " to false");
+ possibs[puzzle[col][j]-1] = false;
+ }
+ }
+ return possibs;
+ }
+ public boolean[] getPossibilitiesByCage(int x, int y)
+ {
+ //System.out.println("Finding cage possibilities on (" + x + "," + y + ")");
+ for(Constraint c : constraints)
+ {
+ //System.out.println("Testing a constraint: " + c.op);
+ for(Position p : c.positions)
+ {
+ //System.out.println("Found a position in this constraint: (" + p.x + "," + p.y + ")");
+ if(p.x == x && p.y == y)
+ {
+ System.out.println("Found cell being talked about.");
+ //We found the cage that's being talked about
+ if(c.op.equals("+"))
+ {
+ System.out.println("Found op: +");
+ return getPossibilitiesByCageAdd(c);
+ }
+ else if(c.op.equals("-"))
+ {
+ System.out.println("Found op: -");
+ return getPossibilitiesByCageSub(c);
+ }
+ else if(c.op.equals("*"))
+ {
+ System.out.println("Found op: *");
+ return getPossibilitiesByCageMul(c);
+ }
+ else if(c.op.equals("/"))
+ {
+ System.out.println("Found op: /");
+ return getPossibilitiesByCageDiv(c);
+ }
+ else if(c.op.equals(" "))
+ {
+ System.out.println("Found op: (NONE)");
+ boolean[] output = new boolean[size];
+ output[c.targNumber-1] = true;
+ //System.out.println("Returning:");
+ //printArray(output);
+ return output;
+ }
+ else
+ {
+ System.out.println("Bad operator: (" + c.op + ")");
+ return null;
+ }
+ }
+ }
+ }
+ System.out.println("Something has gone wrong in getPossibilitiesByCage");
+ return null;
+ }
+ private boolean[] getPossibilitiesByCageAdd(Constraint c)
+ {
+ System.out.println("Getting possibilities for add cage");
+ //Try the numbers 1 to size for every square
+ boolean[] output = new boolean[size];
+ int targ = c.targNumber;
+ //If any of the numbers are already in, subtract them from targ
+ for(Position p : c.positions)
+ {
+ targ -= puzzle[p.x][p.y];
+ }
+ //possibilities are targnumber - 1*# of positions to fill
+ int numcells = c.positions.length;
+ int max = targ - numcells;
+ int min = 1;
+ for(int i = min; i < max; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageMul(Constraint c)
+ {
+ //Numbers can be from 1 to size for this one
+ //If the target number is odd, only an odd* an odd will work
+ int targ = c.targNumber;
+ System.out.println("Getting mul cage possibs:");
+ System.out.println("Cage: (" + c.targNumber + "," + c.op);
+ printArray(c.positions);
+ //If any of the numbers are already in, divide the target by that.
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ System.out.println("Found a number, useing division shortcut");
+ targ /= puzzle[p.x][p.y];
+ }
+ }
+ boolean[] output = new boolean[size];
+ if(c.targNumber % 2 == 1)
+ {
+ System.out.println("Found an odd number, useing odd numbers shortcut");
+ for(int i = 1; i < size+1; i+= 2)
+ {
+ System.out.println("Setting " + i + " to true");
+ output[i-1] = true;
+ }
+ System.out.println("Returning ");
+ printArray(output);
+ return output;
+ }
+ for(int i = 1; i < size+1; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageSub(Constraint c)
+ {
+ //If one of the items is already in it, find what the other value must be
+ boolean[] output = new boolean[size];
+ int x1 = c.positions[0].x;
+ int y1 = c.positions[0].y;
+ int x2 = c.positions[1].x;
+ int y2 = c.positions[1].y;
+ if(puzzle[x1][y1] != 0)
+ {
+ int onlypossib = 0;
+ if(c.targNumber > puzzle[x1][y1])
+ {
+ onlypossib = c.targNumber-puzzle[x1][y1];
+ }
+ else if(c.targNumber < puzzle[x1][y1])
+ {
+ onlypossib = puzzle[x1][y1] - c.targNumber;
+ }
+ output[onlypossib-1] = true;
+ return output;
+ }
+ if(puzzle[x2][y2] != 0)
+ {
+ int onlypossib = 0;
+ if(c.targNumber>puzzle[x2][y2])
+ {
+ onlypossib = c.targNumber-puzzle[x2][y2];
+ }
+ else if(c.targNumber < puzzle[x2][y2])
+ {
+ onlypossib = puzzle[x2][y2] - c.targNumber;
+ }
+ output[onlypossib-1] = true;
+ return output;
+ }
+ //Otherwise, values can be from 1 to targnumber - 2
+ for(int i = 1; i < c.targNumber-2; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageDiv(Constraint c)
+ {
+ //If one of the items is already in it, find what the other value must be
+ boolean[] output = new boolean[size];
+ int x1 = c.positions[0].x;
+ int y1 = c.positions[0].y;
+ int x2 = c.positions[1].x;
+ int y2 = c.positions[1].y;
+ if(puzzle[x1][y1] != 0)
+ {
+ int onlypossib = c.targNumber/puzzle[x1][y1];
+ output[onlypossib-1] = true;
+ return output;
+ }
+ if(puzzle[x2][y2] != 0)
+ {
+ int onlypossib = c.targNumber/puzzle[x2][y2];
+ output[onlypossib-1] = true;
+ return output;
+ }
+ //Otherwise, values can be from 1 to targnumber
+ for(int i = 1; i < c.targNumber+1; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ public boolean isSolved()
+ {
+ boolean tr = testRows();
+ boolean tc = testCols();
+ boolean ta = testCages();
+ System.out.println("Checking for solution(Rows: " + tr + ")(Cols: " + tc + ")(Cages: " + ta+"):");
+ printArray(puzzle);
+ if(!testRows() || !testCols() || !testCages())
+ {
+ return false;
+ }
+ return true;
+ }
+ private boolean testCages()
+ {
+ for(Constraint c : constraints)
+ {
+ if(!testConstraint(c))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ private boolean testConstraint(Constraint c)
+ {
+ if(c.op.equals("+"))
+ {
+ int sum = 0;
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ sum += puzzle[p.x][p.y];
+ }
+ else
+ {
+ return false;
+ }
+ }
+ if(sum == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ printArray(c.positions);
+ return false;
+ }
+ }
+ else if(c.op.equals("-"))
+ {
+ Position p1 = c.positions[0];
+ Position p2 = c.positions[1];
+ if(puzzle[p1.x][p1.y] != 0 && puzzle[p2.x][p2.y] != 0)
+ {
+ int num1 = puzzle[p1.x][p1.y];
+ int num2 = puzzle[p2.x][p2.y];
+ if(num1 - num2 == c.targNumber)
+ {
+ return true;
+ }
+ if(num2 - num1 == c.targNumber)
+ {
+ return true;
+ }
+ }
+ else
+ {
+ System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ printArray(c.positions);
+ return false;
+ }
+ return false;
+ }
+ else if(c.op.equals("*"))
+ {
+ int product = 1;
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ product *= puzzle[p.x][p.y];
+ }
+ else
+ {
+ return false;
+ }
+ }
+ if(product == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ printArray(c.positions);
+ System.out.println("Product is " + product);
+ return false;
+ }
+ }
+ else if(c.op.equals("/"))
+ {
+ Position p1 = c.positions[0];
+ Position p2 = c.positions[1];
+ if(puzzle[p1.x][p1.y] != 0 && puzzle[p2.x][p2.y] != 0)
+ {
+ double num1 = puzzle[p1.x][p1.y];
+ double num2 = puzzle[p2.x][p2.y];
+ if(num1 / num2 == c.targNumber)
+ {
+ return true;
+ }
+ if(num2 / num1 == c.targNumber)
+ {
+ return true;
+ }
+ }
+ else
+ {
+ System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ printArray(c.positions);
+ return false;
+ }
+ return false;
+ }
+ else if(c.op.equals(" "))
+ {
+ int x = c.positions[0].x;
+ int y = c.positions[0].y;
+ if(puzzle[x][y] == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ System.out.println("Something went wrong in testConstraint");
+ return false;
+ }
+ private boolean testCols()
+ {
+ for(int i = 0; i < size; i++)
+ {
+ boolean[] uniqueCols = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {
+ if(puzzle[i][j] == 0)
+ {
+ return false;
+ }
+ uniqueCols[puzzle[i][j]-1] = true;
+ }
+ for(int j = 0; j < uniqueCols.length; j++)
+ {
+ if(!uniqueCols[j])
+ {
+ return false;
+ }
+ }
+ }
+ //System.out.println("Something went wrong in testCols!");
+ return true;
+ }
+ private boolean testRows()
+ {
+ for(int i = 0; i < size; i++)
+ {
+ boolean[] uniqueRows = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {
+ if(puzzle[j][i] == 0)
+ {
+ return false;
+ }
+ uniqueRows[puzzle[j][i]-1] = true;
+ }
+ for(int j = 0; j < uniqueRows.length; j++)
+ {
+ if(!uniqueRows[j])
+ {
+ return false;
+ }
+ }
+ }
+ //System.out.println("Something went wrong in testRows");
+ return true;
+ }
+ public int[][] implyByRows()
+ {
+ //System.out.println("Implying by rows...");
+ int[][][] output = new int[size][4][size];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ {
+ //System.out.println("Calling imply row helper on row " + i);
+ output[i] = implyByRowsHelper(i);
+ if(output[i].length > 0)
+ {
+ numImplyed++;
+ }
+ }
+ int[][] realoutput = new int[numImplyed][4];
+ int j = 0;
+ for(int i = 0; i < numImplyed;i++)
+ {
+ if(output[i].length > 0)
+ {
+ realoutput[j] = output[i][0];
+ j++;
+ }
+ }
+ return realoutput;
+ }
+ public int[][] implyByCols()
+ {
+ //System.out.println("Implying by cols...");
+ int[][][] output = new int[size][4][size];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ {
+ //System.out.println("Calling imply col helper on col " + i);
+ output[i] = implyByColsHelper(i);
+ if(output[i].length > 0)
+ {
+ numImplyed++;
+ }
+ }
+ int[][] realoutput = new int[numImplyed][4];
+ int j = 0;
+ for(int i = 0; i < numImplyed;i++)
+ {
+ if(output[i].length > 0)
+ {
+ realoutput[j] = output[i][0];
+ j++;
+ }
+ }
+ return realoutput;
+ }
+ public int[][] implyByCages()
+ {
+ //System.out.println("Implying by cages");
+ int[][][][] output = new int[size][size][4][size];
+ int numImplyed = 0;
+ //We should only be implying ONE number max!
+ for(int x = 0; x < size; x++)
+ {
+ for(int y = 0; y < size; y++)
+ {
+ //Scan for a num that has only 1 possibility
+ output[x][y] = implyByCagesHelper(x,y);
+ //System.out.println("Attempted to imply by cages on (" + x + "," + y + "):");
+ //printArray(output[x][y]);
+ if(output[x][y].length == 1)
+ {
+ //numImplyed++;
+ //System.out.println("Implything by cage. returning:");
+ //printArray(output[x][y]);
+ return output[x][y];
+ }
+ else
+ {
+ //System.out.println("Unable to imply");
+ }
+ }
+ }
+ //System.out.println("Unable to imply ANYTHING");
+ int[][] realoutput = new int[0][0];
+ return realoutput;
+ /*
+ int[][] realoutput = new int[1][4];
+ int track = 0;
+ if(output.length == 1)
+ {
+ realoutput[0] = output[x][y][0];
+ return realoutput;
+ }
+ */
+ }
+ public int[][] implyByCagesHelper(int x, int y)
+ {
+ int[][] realoutput = new int[size][4];
+ //System.out.println("Implying on cage(" + x + "," + y + ")");
+ int[][] output = new int[size][4];
+ if(puzzle[x][y] != 0)
+ {
+ //This square already has a number in it.
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByCage(x,y);
+ //System.out.println("Got possibilities:");
+ //printArray(possibs);
+ int j = 0;
+ int numtrue = 0;
+ for(boolean b : possibs)
+ {
+ if(b)
+ {
+ numtrue++;
+ }
+ }
+ if(numtrue == 1)
+ {
+ for(int i = 0; i < possibs.length;i++)
+ {
+ if(possibs[i])
+ {
+ realoutput = new int[1][4];
+ puzzle[x][y] = i+1;
+ realoutput[j][0] = 0;
+ realoutput[j][1] = x;
+ realoutput[j][2] = y;
+ realoutput[j][3] = i;
+ return realoutput;
+ }
+ }
+ }
+ }
+ return realoutput;
+ }
+ private int[][] implyByRowsHelper(int row)
+ {
+ //System.out.println("Implying on row " + row);
+ //boolean[] places = new boolean[size];
+ //Outputs all numbers that should go on the stack, each number is in the form (0,x,y,num)
+ //this method may output more than 1 implyed number.
+ int[][] output = new int[size][4];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ { //For each square
+ //This place already has something
+ if(puzzle[i][row] != 0)
+ {
+ //System.out.println("(" + i + "," + row + ") already has " + puzzle[i][row]);
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByRow(row);
+ //System.out.println("Possibilities for (" + i + "," + row + ") are:");
+ printArray(possibs);
+ //Find out how many possibilites for this place is true
+ int numtrue = 0;
+ int lasttrue = 0;
+ for(int j = 0; j < size;j++)
+ {
+ if(possibs[j])
+ {
+ numtrue++;
+ lasttrue = j+1;
+ }
+ }
+ if(numtrue == 1)
+ {
+ puzzle[i][row] = lasttrue;
+ output[numImplyed][0] = 0;
+ output[numImplyed][1] = i;
+ output[numImplyed][2] = row;
+ output[numImplyed][3] = lasttrue;
+ numImplyed++;
+ }
+ }
+ }
+ //System.out.println("First output is : ");
+ //printArray(output);
+ int[][] realoutput = new int[numImplyed][4];
+ for(int i = 0; i < numImplyed; i++)
+ {
+ realoutput[i] = output[i];
+ }
+ //System.out.println("Real output is : ");
+ //printArray(realoutput);
+ return realoutput;
+ }
+ private int[][] implyByColsHelper(int col)
+ {
+ // System.out.println("Implying on row " + row);
+ //boolean[] places = new boolean[size];
+ //Outputs all numbers that should go on the stack, each number is in the form (0,x,y,num)
+ //this method may output more than 1 implyed number.
+ int[][] output = new int[size][4];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ { //For each square
+ //This place already has something
+ if(puzzle[col][i] != 0)
+ {
+ //System.out.println("(" + i + "," + row + ") already has " + puzzle[i][row]);
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByCol(col);
+ //System.out.println("Possibilities for (" + col + "," + i + ") are:");
+ //printArray(possibs);
+ //Find out how many possibilites for this place is true
+ int numtrue = 0;
+ int lasttrue = 0;
+ for(int j = 0; j < size;j++)
+ {
+ if(possibs[j])
+ {
+ numtrue++;
+ lasttrue = j+1;
+ }
+ }
+ if(numtrue == 1)
+ {
+ puzzle[col][i] = lasttrue;
+ output[numImplyed][0] = 0;
+ output[numImplyed][1] = col;
+ output[numImplyed][2] = i;
+ output[numImplyed][3] = lasttrue;
+ numImplyed++;
+ }
+ }
+ }
+ //System.out.println("First output is : ");
+ //printArray(output);
+ int[][] realoutput = new int[numImplyed][4];
+ for(int i = 0; i < numImplyed; i++)
+ {
+ realoutput[i] = output[i];
+ }
+ //System.out.println("Real output is : ");
+ //printArray(realoutput);
+ return realoutput;
+ }
+ public void printPuzzle()
+ {
+ for(int y = 0; y < puzzle.length; y++)
+ {
+ for(int x = 0; x < puzzle[y].length; x++)
+ {
+ System.out.print(puzzle[x][y] + " ");
+ }
+ System.out.print("\n");
+ }
+ }
+ public void printArray(int[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[" + arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("," + arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(int[][] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[[]]");
+ return;
+ }
+ System.out.print("[\t");
+ printArray(arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("\t");
+ printArray(arr[i]);
+ }
+ System.out.print("]\n");
+
+ }
+ public void printArray(boolean[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[" + arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("," + arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Position[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[(" + arr[0].x + "," + arr[0].y + ")");
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print(",(" + arr[i].x + "," + arr[i].y + ")");
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Constraint[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[[]]");
+ return;
+ }
+ System.out.print("[\t");
+ printArray(arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("\t");
+ printArray(arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Constraint c)
+ {
+ System.out.print("(" + c.op + "," + c.targNumber + ",");
+ printArray(c.positions);
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/kenkensolver.java b/projects/project3_kenken/stab2/kenkensolver.java
new file mode 100644
index 0000000..dd36f5e
--- /dev/null
+++ b/projects/project3_kenken/stab2/kenkensolver.java
@@ -0,0 +1,141 @@
+public class kenkensolver
+{
+ public static boolean done = false;
+ public static void main(String args[])
+ {
+ Solver s = new Solver("3x3_1.txt");
+ s.printPuzzle();
+ KStack stack = new KStack();
+ //int[][] implied = s.implyByRows();
+ solve(s,stack);
+ System.out.println();
+ s.printPuzzle();
+ }
+ public static void solve(Solver s, KStack k)
+ {
+ System.out.println("Attempting to solve:");
+ s.printArray(s.puzzle);
+ System.out.println("Stack is:");
+ s.printArray(k.toArray());
+ if(s.isSolved())
+ {
+ System.out.println("Done!");
+ done = true;
+ return;
+ }
+ else
+ {
+ int[][] rows = s.implyByRows();
+ if(rows.length > 0)
+ {
+ //System.out.println("Implying by rows because imply returned ");
+ //s.printArray(rows);
+ for(int[] i : rows)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {
+ int[][] cols = s.implyByCols();
+ if(cols.length > 0)
+ {
+ for(int[] i : cols)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {
+ int[][] cage = s.implyByCages();
+ if(cage.length > 0)
+ {
+ for(int[] i : cage)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {//We have implyed by rows, cols, and cages, now we just have to guess.
+ //Fist, find the first(from top left) spot in the puzzle that's still 0
+ int lastx = -1;
+ int lasty = -1;
+ search:
+ for(int x = 0; x < s.size; x++)
+ {
+ for(int y = 0; y < s.size;y++)
+ {
+ if(s.puzzle[x][y] == 0)
+ {
+ lastx = x;
+ lasty = y;
+ System.out.println("Attempting to guess number for (" + x + "," + y + ")");
+ break search;
+ }
+ }
+ }
+ boolean[] possibilities = s.getPossibilities(lastx,lasty);
+ int numpossible = 0;
+ for(boolean b : possibilities)
+ {
+ if(b)
+ numpossible++;
+ }
+ if(numpossible > 0)
+ {
+ int[] guess = new int[4];
+ for(int i = 0; i < possibilities.length && !done; i++)
+ {
+ System.out.println("Unable to imply a solution for (" + lastx + "," + lasty + ") guessing:");
+ s.printArray(possibilities);
+ if(possibilities[i])
+ {
+ if(i == possibilities.length-1)
+ {
+ guess[0] = 0;
+ }
+ else
+ {
+ guess[0] = 1;
+ }
+ guess[1] = lastx;
+ guess[2] = lasty;
+ guess[3] = i+1;
+ k.push(guess);
+ s.put(lastx,lasty,i+1);
+ solve(s,k);
+ }
+ }
+ }
+ else
+ {
+ //We have exhusted all possibilities for this square
+ System.out.println("\nExhausted possibilities.. backtracking\n");
+ while(k.getLength() > 0 && k.peek()[0] == 0 && !done) //While implied stuff is still on top
+ {
+ int[] thisitem = k.pop();
+ System.out.println("Removeing:");
+ s.printArray(thisitem);
+ s.remove(thisitem[1],thisitem[2]);
+ }
+ //And pop the last guess
+ int[] lastguess = k.pop();
+ System.out.println("Removeing:");
+ s.printArray(lastguess);
+ s.remove(lastguess[1],lastguess[2]);
+ System.out.println("Done backtracking");
+ return;
+ }
+ }
+ }
+ }
+ }
+ //System.out.println("Something has gone horribly wrong!");
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/working3x3_1/3x3_1.txt b/projects/project3_kenken/stab2/working3x3_1/3x3_1.txt
new file mode 100644
index 0000000..b23e027
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/3x3_1.txt
@@ -0,0 +1,17 @@
+3
+5
+3, ,1
+0,0
+6,*,2
+0,1
+1,1
+2,/,2
+0,2
+1,2
+2,/,2
+1,0
+2,0
+2,-,2
+2,1
+2,2
+
diff --git a/projects/project3_kenken/stab2/working3x3_1/3x3_2.txt b/projects/project3_kenken/stab2/working3x3_1/3x3_2.txt
new file mode 100644
index 0000000..2556aa6
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/3x3_2.txt
@@ -0,0 +1,17 @@
+3
+5
+2, ,1
+0,0
+9,*,3
+0,1
+0,2
+1,2
+2,-,2
+1,0
+2,0
+2,/,2
+1,1
+2,1
+2, ,1
+2,2
+
diff --git a/projects/project3_kenken/stab2/working3x3_1/3x3_3.txt b/projects/project3_kenken/stab2/working3x3_1/3x3_3.txt
new file mode 100644
index 0000000..a844c5b
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/3x3_3.txt
@@ -0,0 +1,17 @@
+3
+5
+1,-,2
+0,1
+0,2
+2,-,2
+0,0
+1,0
+2, ,1
+1,1
+3,+,2
+2,0
+2,1
+3,/,2
+1,2
+2,2
+
diff --git a/projects/project3_kenken/stab2/working3x3_1/Constraint.java b/projects/project3_kenken/stab2/working3x3_1/Constraint.java
new file mode 100644
index 0000000..4d97055
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/Constraint.java
@@ -0,0 +1,12 @@
+public class Constraint
+{
+ public String op;
+ public Position[] positions;
+ public int targNumber;
+ public Constraint(int targNumber,String op,Position[] pos)
+ {
+ this.op = op;
+ positions = pos;
+ this.targNumber = targNumber;
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/working3x3_1/KNode.java b/projects/project3_kenken/stab2/working3x3_1/KNode.java
new file mode 100644
index 0000000..e82e0e2
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/KNode.java
@@ -0,0 +1,18 @@
+public class KNode
+{
+ private KNode next = null;
+ private int[] data;
+ public KNode(int[] d, KNode n)
+ {
+ data = d;
+ next = n;
+ }
+ public int[] getData()
+ {
+ return data;
+ }
+ public KNode getNext()
+ {
+ return next;
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/working3x3_1/KStack.java b/projects/project3_kenken/stab2/working3x3_1/KStack.java
new file mode 100644
index 0000000..613f9f2
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/KStack.java
@@ -0,0 +1,54 @@
+public class KStack
+{
+ private KNode head;
+ private int length;
+ public KStack()
+ {
+ length = 0;
+ }
+ public int[] peek()
+ {
+ return head.getData();
+ }
+ public int[] pop()
+ {
+ int[] output = head.getData();
+ head = head.getNext();
+ length--;
+ return output;
+ }
+ public void push(int[] i)
+ {
+ head = new KNode(i,head);
+ length++;
+ }
+ public boolean hasNext()
+ {
+ return head != null;
+ }
+ public int getLength()
+ {
+ return length;
+ }
+ public String toString()
+ {
+ String output = "";
+ for(KNode tmp = head; tmp != null; tmp=tmp.getNext())
+ {
+ output += tmp.getData() + " ";
+ }
+ return output;
+ }
+ public int[][] toArray()
+ {
+ int[][] output = new int[length][4];
+ int i = length-1;
+ for(KNode tmp = head; tmp != null; tmp = tmp.getNext())
+ {
+ output[i] = tmp.getData();
+ i--;
+ }
+ return output;
+ }
+
+}
diff --git a/projects/project3_kenken/stab2/working3x3_1/Position.java b/projects/project3_kenken/stab2/working3x3_1/Position.java
new file mode 100644
index 0000000..b036299
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/Position.java
@@ -0,0 +1,11 @@
+public class Position
+{
+ public int x;
+ public int y;
+ public Position(int x, int y)
+ {
+ this.x = x;
+ this.y = y;
+ }
+
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/working3x3_1/Solver.java b/projects/project3_kenken/stab2/working3x3_1/Solver.java
new file mode 100644
index 0000000..8c6a5a3
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/Solver.java
@@ -0,0 +1,853 @@
+import java.util.Scanner;
+import java.io.*;
+
+public class Solver
+{
+ public int[][] puzzle;
+ public Constraint[] constraints;
+ public int size;
+ public Solver(String filename)
+ {
+ parsePuzzle(filename);
+ /*puzzle = new int[3][3];
+ constraints = new Constraint[5];
+
+ Position[] p1 = new Position[1];
+ p1[0] = new Position(0,0);
+ constraints[0] = new Constraint(3," ",p1);
+
+ Position[] p2 = new Position[2];
+ p2[0] = new Position(1,0);
+ p2[1] = new Position(1,1);
+ constraints[1] = new Constraint(6,"*",p2);
+
+ Position[] p3 = new Position[2];
+ p3[0] = new Position(2,0);
+ p3[1] = new Position(2,1);
+ constraints[2] = new Constraint(2,"/",p3);
+
+ Position[] p4 = new Position[2];
+ p4[0] = new Position(0,1);
+ p4[1] = new Position(0,2);
+ constraints[3] = new Constraint(2,"/",p4);
+
+ Position[] p5 = new Position[2];
+ p5[0] = new Position(1,2);
+ p5[1] = new Position(2,2);
+ constraints[4] = new Constraint(2,"-",p5);
+
+ size = puzzle.length;
+ */
+ //System.out.println("Everything parsed, data is:");
+ //System.out.println("Puzzle:");
+ //printArray(puzzle);
+ //System.out.println("Constraints:");
+ //printArray(constraints);
+ //System.out.println("size: " + size);
+ }
+ private void parsePuzzle(String filename)
+ {
+ Scanner s = null;
+ try
+ {
+ s = new Scanner(new FileInputStream(filename));
+ }
+ catch (Exception e)
+ {
+ System.out.println("Something went terribly wrong!\n" + e);
+ }
+ size = Integer.parseInt(s.nextLine().replaceAll("\n",""));
+
+ puzzle = new int[size][size];
+
+ constraints = new Constraint[Integer.parseInt(s.nextLine().replaceAll("\n",""))];
+
+ //System.out.println("Puzzle size: " + size + " Cages: " + p.length);
+ for(int i = 0; s.hasNextLine();i++)
+ {
+ String t1 = s.nextLine();
+ //System.out.println("Praseing: " + t1);
+ String[] t2 = t1.split(",");
+ //System.out.println("Parts length: " + t2.length);
+ if(t2.length > 1)
+ {
+ Position[] allcells = new Position[Integer.parseInt(t2[2])];
+ for(int j = 0; j < Integer.parseInt(t2[2]);j++)
+ {
+ String[] coords = s.nextLine().split(",");
+ allcells[j] = new Position(Integer.parseInt(coords[1]),Integer.parseInt(coords[0]));
+ }
+ constraints[i] = new Constraint(Integer.parseInt(t2[0]),t2[1],allcells);
+ //System.out.println("Created new constraint(" + Integer.parseInt(t2[0]) + "," + t2[1] + ",");
+ //printArray(allcells);
+ /*
+ for(Position c : allcells)
+ {
+ constraints[i] = new Constraint(Integer.parseInt(t2[0]),t2[1],allcells);
+ }
+ */
+ //p[i] = new KCage(Integer.parseInt(t2[0]),getOp(t2[1]),allcells);
+ //System.out.println("Created " + p[i]);
+ }
+ }
+ }
+ public void put(int x, int y, int num)
+ {
+ puzzle[x][y] = num;
+ }
+ public int remove(int x, int y)
+ {
+ int num = puzzle[x][y];
+ puzzle[x][y] = 0;
+ return num;
+ }
+ public boolean[] getPossibilities(int x, int y)
+ {
+ boolean[] row = getPossibilitiesByRow(y);
+ boolean[] col = getPossibilitiesByCol(x);
+ boolean[] cage = getPossibilitiesByCage(x,y);
+ boolean[] output = new boolean[size];
+ for(int i = 0; i < size; i++)
+ {
+ if(row[i] && col[i] && cage[i])
+ {
+ output[i] = true;
+ }
+ }
+ //System.out.println("Possibilities for (" + x + "," + y + ") are ");
+ //printArray(output);
+ return output;
+ }
+ public boolean[] getPossibilitiesByRow(int row)
+ {
+ boolean[] possibs = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {//Set all places is possibs to true
+ possibs[j] = true;
+ }
+ //Find all the possibilities
+ for(int j = 0; j < size; j++)
+ { //For every other place
+ if(puzzle[j][row] != 0)
+ {
+ //System.out.println("Setting (" + j + "," + row + "): " + puzzle[j][row] + " to false");
+ possibs[puzzle[j][row]-1] = false;
+ }
+ }
+ return possibs;
+ }
+ public boolean[] getPossibilitiesByCol(int col)
+ {
+ boolean[] possibs = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {//Set all places is possibs to true
+ possibs[j] = true;
+ }
+ //Find all the possibilities
+ for(int j = 0; j < size; j++)
+ { //For every other place
+ if(puzzle[col][j] != 0)
+ {
+ //System.out.println("Setting (" + col + "," + j + "): " + puzzle[col][j] + " to false");
+ possibs[puzzle[col][j]-1] = false;
+ }
+ }
+ return possibs;
+ }
+ public boolean[] getPossibilitiesByCage(int x, int y)
+ {
+ //System.out.println("Finding cage possibilities on (" + x + "," + y + ")");
+ for(Constraint c : constraints)
+ {
+ //System.out.println("Testing a constraint: " + c.op);
+ for(Position p : c.positions)
+ {
+ //System.out.println("Found a position in this constraint: (" + p.x + "," + p.y + ")");
+ if(p.x == x && p.y == y)
+ {
+ System.out.println("Found cell being talked about.");
+ //We found the cage that's being talked about
+ if(c.op.equals("+"))
+ {
+ //System.out.println("Found op: +");
+ return getPossibilitiesByCageAdd(c);
+ }
+ else if(c.op.equals("-"))
+ {
+ //System.out.println("Found op: -");
+ return getPossibilitiesByCageSub(c);
+ }
+ else if(c.op.equals("*"))
+ {
+ //System.out.println("Found op: *");
+ return getPossibilitiesByCageMul(c);
+ }
+ else if(c.op.equals("/"))
+ {
+ //System.out.println("Found op: /");
+ return getPossibilitiesByCageDiv(c);
+ }
+ else if(c.op.equals(" "))
+ {
+ //System.out.println("Found op: (NONE)");
+ boolean[] output = new boolean[size];
+ output[c.targNumber-1] = true;
+ //System.out.println("Returning:");
+ //printArray(output);
+ return output;
+ }
+ else
+ {
+ //System.out.println("Bad operator: (" + c.op + ")");
+ return null;
+ }
+ }
+ }
+ }
+ System.out.println("Something has gone wrong in getPossibilitiesByCage");
+ return null;
+ }
+ private boolean[] getPossibilitiesByCageAdd(Constraint c)
+ {
+ //System.out.println("Getting possibilities for add cage");
+ //Try the numbers 1 to size for every square
+ boolean[] output = new boolean[size];
+ int targ = c.targNumber;
+ //If any of the numbers are already in, subtract them from targ
+ for(Position p : c.positions)
+ {
+ targ -= puzzle[p.x][p.y];
+ }
+ //possibilities are targnumber - 1*# of positions to fill
+ int numcells = c.positions.length;
+ int max = targ - numcells;
+ int min = 1;
+ for(int i = min; i < max; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageMul(Constraint c)
+ {
+ //Numbers can be from 1 to size for this one
+ //If the target number is odd, only an odd* an odd will work
+ int targ = c.targNumber;
+ //If any of the numbers are already in, divide the target by that.
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ //System.out.println("Found a number, useing division shortcut");
+ targ /= puzzle[p.x][p.y];
+ }
+ }
+ boolean[] output = new boolean[size];
+ if(c.targNumber % 2 == 1)
+ {
+ //System.out.println("Found an odd number, useing odd numbers shortcut");
+ for(int i = 1; i < size; i+= 2)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ for(int i = 1; i < size+1; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageSub(Constraint c)
+ {
+ //If one of the items is already in it, find what the other value must be
+ boolean[] output = new boolean[size];
+ int x1 = c.positions[0].x;
+ int y1 = c.positions[0].y;
+ int x2 = c.positions[1].x;
+ int y2 = c.positions[1].y;
+ if(puzzle[x1][y1] != 0)
+ {
+ int onlypossib = 0;
+ if(c.targNumber > puzzle[x1][y1])
+ {
+ onlypossib = c.targNumber-puzzle[x1][y1];
+ }
+ else if(c.targNumber < puzzle[x1][y1])
+ {
+ onlypossib = puzzle[x1][y1] - c.targNumber;
+ }
+ output[onlypossib-1] = true;
+ return output;
+ }
+ if(puzzle[x2][y2] != 0)
+ {
+ int onlypossib = 0;
+ if(c.targNumber>puzzle[x2][y2])
+ {
+ onlypossib = c.targNumber-puzzle[x2][y2];
+ }
+ else if(c.targNumber < puzzle[x2][y2])
+ {
+ onlypossib = puzzle[x2][y2] - c.targNumber;
+ }
+ output[onlypossib-1] = true;
+ return output;
+ }
+ //Otherwise, values can be from 1 to targnumber - 2
+ for(int i = 1; i < c.targNumber-2; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ private boolean[] getPossibilitiesByCageDiv(Constraint c)
+ {
+ //If one of the items is already in it, find what the other value must be
+ boolean[] output = new boolean[size];
+ int x1 = c.positions[0].x;
+ int y1 = c.positions[0].y;
+ int x2 = c.positions[1].x;
+ int y2 = c.positions[1].y;
+ if(puzzle[x1][y1] != 0)
+ {
+ int onlypossib = c.targNumber/puzzle[x1][y1];
+ output[onlypossib-1] = true;
+ return output;
+ }
+ if(puzzle[x2][y2] != 0)
+ {
+ int onlypossib = c.targNumber/puzzle[x2][y2];
+ output[onlypossib-1] = true;
+ return output;
+ }
+ //Otherwise, values can be from 1 to targnumber
+ for(int i = 1; i < c.targNumber+1; i++)
+ {
+ output[i-1] = true;
+ }
+ return output;
+ }
+ public boolean isSolved()
+ {
+ boolean tr = testRows();
+ boolean tc = testCols();
+ boolean ta = testCages();
+ //System.out.println("Checking for solution(Rows: " + tr + ")(Cols: " + tc + ")(Cages: " + ta+"):");
+ //printArray(puzzle);
+ if(!testRows() || !testCols() || !testCages())
+ {
+ return false;
+ }
+ return true;
+ }
+ private boolean testCages()
+ {
+ for(Constraint c : constraints)
+ {
+ if(!testConstraint(c))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ private boolean testConstraint(Constraint c)
+ {
+ if(c.op.equals("+"))
+ {
+ int sum = 0;
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ sum += puzzle[p.x][p.y];
+ }
+ else
+ {
+ return false;
+ }
+ }
+ if(sum == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ //System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ //printArray(c.positions);
+ return false;
+ }
+ }
+ else if(c.op.equals("-"))
+ {
+ Position p1 = c.positions[0];
+ Position p2 = c.positions[1];
+ if(puzzle[p1.x][p1.y] != 0 && puzzle[p2.x][p2.y] != 0)
+ {
+ int num1 = puzzle[p1.x][p1.y];
+ int num2 = puzzle[p2.x][p2.y];
+ if(num1 - num2 == c.targNumber)
+ {
+ return true;
+ }
+ if(num2 - num1 == c.targNumber)
+ {
+ return true;
+ }
+ }
+ else
+ {
+ //System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ //printArray(c.positions);
+ return false;
+ }
+ return false;
+ }
+ else if(c.op.equals("*"))
+ {
+ int product = 1;
+ for(Position p : c.positions)
+ {
+ if(puzzle[p.x][p.y] != 0)
+ {
+ product *= puzzle[p.x][p.y];
+ }
+ else
+ {
+ return false;
+ }
+ }
+ if(product == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ //System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ //printArray(c.positions);
+ //System.out.println("Product is " + product);
+ return false;
+ }
+ }
+ else if(c.op.equals("/"))
+ {
+ Position p1 = c.positions[0];
+ Position p2 = c.positions[1];
+ if(puzzle[p1.x][p1.y] != 0 && puzzle[p2.x][p2.y] != 0)
+ {
+ double num1 = puzzle[p1.x][p1.y];
+ double num2 = puzzle[p2.x][p2.y];
+ if(num1 / num2 == c.targNumber)
+ {
+ return true;
+ }
+ if(num2 / num1 == c.targNumber)
+ {
+ return true;
+ }
+ }
+ else
+ {
+ //System.out.println("Failed on constraint:("+c.targNumber+","+c.op+",");
+ //printArray(c.positions);
+ return false;
+ }
+ return false;
+ }
+ else if(c.op.equals(" "))
+ {
+ int x = c.positions[0].x;
+ int y = c.positions[0].y;
+ if(puzzle[x][y] == c.targNumber)
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ //System.out.println("Something went wrong in testConstraint");
+ return false;
+ }
+ private boolean testCols()
+ {
+ for(int i = 0; i < size; i++)
+ {
+ boolean[] uniqueCols = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {
+ if(puzzle[i][j] == 0)
+ {
+ return false;
+ }
+ uniqueCols[puzzle[i][j]-1] = true;
+ }
+ for(int j = 0; j < uniqueCols.length; j++)
+ {
+ if(!uniqueCols[j])
+ {
+ return false;
+ }
+ }
+ }
+ //System.out.println("Something went wrong in testCols!");
+ return true;
+ }
+ private boolean testRows()
+ {
+ for(int i = 0; i < size; i++)
+ {
+ boolean[] uniqueRows = new boolean[size];
+ for(int j = 0; j < size; j++)
+ {
+ if(puzzle[j][i] == 0)
+ {
+ return false;
+ }
+ uniqueRows[puzzle[j][i]-1] = true;
+ }
+ for(int j = 0; j < uniqueRows.length; j++)
+ {
+ if(!uniqueRows[j])
+ {
+ return false;
+ }
+ }
+ }
+ //System.out.println("Something went wrong in testRows");
+ return true;
+ }
+ public int[][] implyByRows()
+ {
+ //System.out.println("Implying by rows...");
+ int[][][] output = new int[size][4][size];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ {
+ //System.out.println("Calling imply row helper on row " + i);
+ output[i] = implyByRowsHelper(i);
+ if(output[i].length > 0)
+ {
+ numImplyed++;
+ }
+ }
+ int[][] realoutput = new int[numImplyed][4];
+ int j = 0;
+ for(int i = 0; i < numImplyed;i++)
+ {
+ if(output[i].length > 0)
+ {
+ realoutput[j] = output[i][0];
+ j++;
+ }
+ }
+ return realoutput;
+ }
+ public int[][] implyByCols()
+ {
+ //System.out.println("Implying by cols...");
+ int[][][] output = new int[size][4][size];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ {
+ //System.out.println("Calling imply col helper on col " + i);
+ output[i] = implyByColsHelper(i);
+ if(output[i].length > 0)
+ {
+ numImplyed++;
+ }
+ }
+ int[][] realoutput = new int[numImplyed][4];
+ int j = 0;
+ for(int i = 0; i < numImplyed;i++)
+ {
+ if(output[i].length > 0)
+ {
+ realoutput[j] = output[i][0];
+ j++;
+ }
+ }
+ return realoutput;
+ }
+ public int[][] implyByCages()
+ {
+ //System.out.println("Implying by cages");
+ int[][][][] output = new int[size][size][4][size];
+ int numImplyed = 0;
+ //We should only be implying ONE number max!
+ for(int x = 0; x < size; x++)
+ {
+ for(int y = 0; y < size; y++)
+ {
+ //Scan for a num that has only 1 possibility
+ output[x][y] = implyByCagesHelper(x,y);
+ //System.out.println("Attempted to imply by cages on (" + x + "," + y + "):");
+ //printArray(output[x][y]);
+ if(output[x][y].length == 1)
+ {
+ //numImplyed++;
+ //System.out.println("Implything by cage. returning:");
+ //printArray(output[x][y]);
+ return output[x][y];
+ }
+ else
+ {
+ //System.out.println("Unable to imply");
+ }
+ }
+ }
+ //System.out.println("Unable to imply ANYTHING");
+ int[][] realoutput = new int[0][0];
+ return realoutput;
+ /*
+ int[][] realoutput = new int[1][4];
+ int track = 0;
+ if(output.length == 1)
+ {
+ realoutput[0] = output[x][y][0];
+ return realoutput;
+ }
+ */
+ }
+ public int[][] implyByCagesHelper(int x, int y)
+ {
+ int[][] realoutput = new int[size][4];
+ //System.out.println("Implying on cage(" + x + "," + y + ")");
+ int[][] output = new int[size][4];
+ if(puzzle[x][y] != 0)
+ {
+ //This square already has a number in it.
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByCage(x,y);
+ //System.out.println("Got possibilities:");
+ //printArray(possibs);
+ int j = 0;
+ int numtrue = 0;
+ for(boolean b : possibs)
+ {
+ if(b)
+ {
+ numtrue++;
+ }
+ }
+ if(numtrue == 1)
+ {
+ for(int i = 0; i < possibs.length;i++)
+ {
+ if(possibs[i])
+ {
+ realoutput = new int[1][4];
+ puzzle[x][y] = i+1;
+ realoutput[j][0] = 0;
+ realoutput[j][1] = x;
+ realoutput[j][2] = y;
+ realoutput[j][3] = i;
+ return realoutput;
+ }
+ }
+ }
+ }
+ return realoutput;
+ }
+ private int[][] implyByRowsHelper(int row)
+ {
+ //System.out.println("Implying on row " + row);
+ //boolean[] places = new boolean[size];
+ //Outputs all numbers that should go on the stack, each number is in the form (0,x,y,num)
+ //this method may output more than 1 implyed number.
+ int[][] output = new int[size][4];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ { //For each square
+ //This place already has something
+ if(puzzle[i][row] != 0)
+ {
+ //System.out.println("(" + i + "," + row + ") already has " + puzzle[i][row]);
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByRow(row);
+ //System.out.println("Possibilities for (" + i + "," + row + ") are:");
+ //printArray(possibs);
+ //Find out how many possibilites for this place is true
+ int numtrue = 0;
+ int lasttrue = 0;
+ for(int j = 0; j < size;j++)
+ {
+ if(possibs[j])
+ {
+ numtrue++;
+ lasttrue = j+1;
+ }
+ }
+ if(numtrue == 1)
+ {
+ puzzle[i][row] = lasttrue;
+ output[numImplyed][0] = 0;
+ output[numImplyed][1] = i;
+ output[numImplyed][2] = row;
+ output[numImplyed][3] = lasttrue;
+ numImplyed++;
+ }
+ }
+ }
+ //System.out.println("First output is : ");
+ //printArray(output);
+ int[][] realoutput = new int[numImplyed][4];
+ for(int i = 0; i < numImplyed; i++)
+ {
+ realoutput[i] = output[i];
+ }
+ //System.out.println("Real output is : ");
+ //printArray(realoutput);
+ return realoutput;
+ }
+ private int[][] implyByColsHelper(int col)
+ {
+ // System.out.println("Implying on row " + row);
+ //boolean[] places = new boolean[size];
+ //Outputs all numbers that should go on the stack, each number is in the form (0,x,y,num)
+ //this method may output more than 1 implyed number.
+ int[][] output = new int[size][4];
+ int numImplyed = 0;
+ for(int i = 0; i < size; i++)
+ { //For each square
+ //This place already has something
+ if(puzzle[col][i] != 0)
+ {
+ //System.out.println("(" + i + "," + row + ") already has " + puzzle[i][row]);
+ }
+ else
+ {
+ boolean[] possibs = getPossibilitiesByCol(col);
+ //System.out.println("Possibilities for (" + col + "," + i + ") are:");
+ //printArray(possibs);
+ //Find out how many possibilites for this place is true
+ int numtrue = 0;
+ int lasttrue = 0;
+ for(int j = 0; j < size;j++)
+ {
+ if(possibs[j])
+ {
+ numtrue++;
+ lasttrue = j+1;
+ }
+ }
+ if(numtrue == 1)
+ {
+ puzzle[col][i] = lasttrue;
+ output[numImplyed][0] = 0;
+ output[numImplyed][1] = col;
+ output[numImplyed][2] = i;
+ output[numImplyed][3] = lasttrue;
+ numImplyed++;
+ }
+ }
+ }
+ //System.out.println("First output is : ");
+ //printArray(output);
+ int[][] realoutput = new int[numImplyed][4];
+ for(int i = 0; i < numImplyed; i++)
+ {
+ realoutput[i] = output[i];
+ }
+ //System.out.println("Real output is : ");
+ //printArray(realoutput);
+ return realoutput;
+ }
+ public void printPuzzle()
+ {
+ for(int y = 0; y < puzzle.length; y++)
+ {
+ for(int x = 0; x < puzzle[y].length; x++)
+ {
+ System.out.print(puzzle[x][y] + " ");
+ }
+ System.out.print("\n");
+ }
+ }
+ public void printArray(int[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[" + arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("," + arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(int[][] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[[]]");
+ return;
+ }
+ System.out.print("[\t");
+ printArray(arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("\t");
+ printArray(arr[i]);
+ }
+ System.out.print("]\n");
+
+ }
+ public void printArray(boolean[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[" + arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("," + arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Position[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[]");
+ return;
+ }
+ System.out.print("[(" + arr[0].x + "," + arr[0].y + ")");
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print(",(" + arr[i].x + "," + arr[i].y + ")");
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Constraint[] arr)
+ {
+ if(arr.length == 0)
+ {
+ System.out.println("[[]]");
+ return;
+ }
+ System.out.print("[\t");
+ printArray(arr[0]);
+ for(int i = 1; i < arr.length; i++)
+ {
+ System.out.print("\t");
+ printArray(arr[i]);
+ }
+ System.out.print("]\n");
+ }
+ public void printArray(Constraint c)
+ {
+ System.out.print("(" + c.op + "," + c.targNumber + ",");
+ printArray(c.positions);
+ }
+} \ No newline at end of file
diff --git a/projects/project3_kenken/stab2/working3x3_1/kenkensolver.java b/projects/project3_kenken/stab2/working3x3_1/kenkensolver.java
new file mode 100644
index 0000000..d141d3f
--- /dev/null
+++ b/projects/project3_kenken/stab2/working3x3_1/kenkensolver.java
@@ -0,0 +1,159 @@
+
+import java.util.Scanner;
+import java.io.*;
+import java.awt.*;
+import javax.swing.*;
+public class kenkensolver
+{
+ public static boolean done = false;
+ public static void main(String args[]) throws IOException
+ {
+ String puzzlefile = "";
+ System.out.println("Enter file:");
+ Scanner scanner = new Scanner(new InputStreamReader(System.in));
+ while(puzzlefile.equals(""))
+ {
+ String input = scanner.nextLine();
+ File f = new File(input);
+ if(f.exists() && !f.isDirectory())
+ {
+ puzzlefile = input;
+ }
+ else
+ {
+ System.out.println("Could not find file, please try again:");
+ }
+ }
+ Solver s = new Solver("3x3_1.txt");
+ //s.printPuzzle();
+ KStack stack = new KStack();
+ //int[][] implied = s.implyByRows();
+ solve(s,stack);
+ //System.out.println();
+ //s.printPuzzle();
+ JFrame frame = new JFrame();
+ KenKenComponent kc = new KenKenComponent(puzzlefile, frame);
+ kc.setNumber(s.puzzle);
+ }
+ public static void solve(Solver s, KStack k)
+ {
+ //System.out.println("Attempting to solve:");
+ //s.printArray(s.puzzle);
+ //System.out.println("Stack is:");
+ //s.printArray(k.toArray());
+ if(s.isSolved())
+ {
+ System.out.println("Done!");
+ done = true;
+ return;
+ }
+ else
+ {
+ int[][] rows = s.implyByRows();
+ if(rows.length > 0)
+ {
+ //System.out.println("Implying by rows because imply returned ");
+ //s.printArray(rows);
+ for(int[] i : rows)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {
+ int[][] cols = s.implyByCols();
+ if(cols.length > 0)
+ {
+ for(int[] i : cols)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {
+ int[][] cage = s.implyByCages();
+ if(cage.length > 0)
+ {
+ for(int[] i : cage)
+ {
+ k.push(i);
+ }
+ solve(s,k);
+ return;
+ }
+ else
+ {//We have implyed by rows, cols, and cages, now we just have to guess.
+ //Fist, find the first(from top left) spot in the puzzle that's still 0
+ int lastx = -1;
+ int lasty = -1;
+ search:
+ for(int x = 0; x < s.size; x++)
+ {
+ for(int y = 0; y < s.size;y++)
+ {
+ if(s.puzzle[x][y] == 0)
+ {
+ lastx = x;
+ lasty = y;
+ //System.out.println("Attempting to guess number for (" + x + "," + y + ")");
+ break search;
+ }
+ }
+ }
+ if(lastx != -1 && lasty != -1)
+ {
+ int[] guess = new int[4];
+ boolean[] possibilities = s.getPossibilities(lastx,lasty);
+ for(int i = 0; i < possibilities.length && !done; i++)
+ {
+ //System.out.println("Unable to imply a solution for (" + lastx + "," + lasty + ") guessing:");
+ //s.printArray(possibilities);
+ if(possibilities[i])
+ {
+ if(i == possibilities.length-1)
+ {
+ guess[0] = 0;
+ }
+ else
+ {
+ guess[0] = 1;
+ }
+ guess[1] = lastx;
+ guess[2] = lasty;
+ guess[3] = i+1;
+ k.push(guess);
+ s.put(lastx,lasty,i+1);
+ solve(s,k);
+ }
+ }
+ }
+ else
+ {
+ //We have exhusted all possibilities for this square
+ //System.out.println("\nExhausted possibilities.. backtracking\n");
+ while(k.getLength() > 0 && k.peek()[0] == 0 && !done) //While implied stuff is still on top
+ {
+ int[] thisitem = k.pop();
+ //System.out.println("Removeing:");
+ //s.printArray(thisitem);
+ s.remove(thisitem[1],thisitem[2]);
+ }
+ //And pop the last guess
+ int[] lastguess = k.pop();
+ //System.out.println("Removeing:");
+ //s.printArray(lastguess);
+ s.remove(lastguess[1],lastguess[2]);
+ //System.out.println("Done backtracking");
+ return;
+ }
+ }
+ }
+ }
+ }
+ //System.out.println("Something has gone horribly wrong!");
+ }
+} \ No newline at end of file
diff --git a/projects/project4_huffman_tree/BinaryNode.java b/projects/project4_huffman_tree/BinaryNode.java
new file mode 100644
index 0000000..d498b8e
--- /dev/null
+++ b/projects/project4_huffman_tree/BinaryNode.java
@@ -0,0 +1,100 @@
+
+public class BinaryNode<T> implements BinaryNodeInterface<T>
+{
+ private T data;
+ private BinaryNode<T> left;
+ private BinaryNode<T> right;
+
+ public BinaryNode(T dataPortion, BinaryNode<T> leftChild, BinaryNode<T> rightChild)
+ {
+ data = dataPortion;
+ left = leftChild;
+ right = rightChild;
+ }
+
+ public BinaryNode(T dataPortion)
+ {
+ this(dataPortion, null, null);
+ }
+
+ public BinaryNode()
+ {
+ this(null);
+ }
+
+ public T getData()
+ {
+ return data;
+ }
+
+ public void setData(T newData)
+ {
+ data = newData;
+ }
+
+ public BinaryNodeInterface<T> getLeftChild()
+ {
+ return left;
+ }
+
+ public BinaryNodeInterface<T> getRightChild()
+ {
+ return right;
+ }
+
+ public void setLeftChild(BinaryNodeInterface<T> leftChild)
+ {
+ left = (BinaryNode<T>) leftChild;
+ }
+
+ public void setRightChild(BinaryNodeInterface<T> rightChild)
+ {
+ right = (BinaryNode<T>) rightChild;
+ }
+
+ public boolean hasLeftChild()
+ {
+ return left != null;
+ }
+
+ public boolean hasRightChild()
+ {
+ return right != null;
+ }
+
+ public boolean isLeaf()
+ {
+ return left == null && right == null;
+ }
+
+ public int getNumberOfNodes()
+ {
+ int leftNumber = 0;
+ int rightNumber = 0;
+
+ if(left != null)
+ leftNumber = left.getNumberOfNodes();
+
+ if(right != null)
+ rightNumber = right.getNumberOfNodes();
+
+ return 1 + leftNumber + rightNumber;
+ }
+
+ public int getHeight()
+ {
+ return getHeight(this);
+ }
+
+ private int getHeight(BinaryNode<T> node)
+ {
+ int height = 0;
+
+ if(node != null)
+ {
+ height = 1 + Math.max(getHeight(node.left), getHeight(node.right));
+ }
+
+ return height;
+ }
+}
diff --git a/projects/project4_huffman_tree/BinaryNodeInterface.java b/projects/project4_huffman_tree/BinaryNodeInterface.java
new file mode 100644
index 0000000..f3ac7c1
--- /dev/null
+++ b/projects/project4_huffman_tree/BinaryNodeInterface.java
@@ -0,0 +1,15 @@
+
+public interface BinaryNodeInterface<T>
+{
+ public T getData();
+ public void setData(T newData);
+ public BinaryNodeInterface<T> getLeftChild();
+ public BinaryNodeInterface<T> getRightChild();
+ public void setLeftChild(BinaryNodeInterface<T> leftChild);
+ public void setRightChild(BinaryNodeInterface<T> rightChild);
+ public boolean hasLeftChild();
+ public boolean hasRightChild();
+ public boolean isLeaf();
+ public int getNumberOfNodes();
+ public int getHeight();
+}
diff --git a/projects/project4_huffman_tree/CompressDecompress.java b/projects/project4_huffman_tree/CompressDecompress.java
new file mode 100644
index 0000000..56b69e6
--- /dev/null
+++ b/projects/project4_huffman_tree/CompressDecompress.java
@@ -0,0 +1,189 @@
+/**
+ * It is okay to use ArrayList class but you are not allowed to use any other
+ * predefined class supplied by Java.
+ */
+import java.util.ArrayList;
+
+public class CompressDecompress
+{
+ /**
+ * Get a string representing a Huffman tree where its root node is root
+ * @param root the root node of a Huffman tree
+ * @return a string representing a Huffman tree
+ */
+ public static String getTreeString(final BinaryNodeInterface<Character> root)
+ {
+ String output = getTreeStringHelper(root);
+
+ return output; // Do not forget to change this line!!!
+ }
+ private static String getTreeStringHelper(final BinaryNodeInterface<Character> root)
+ {
+ //System.out.println("\n finding ");
+ String output = "";
+ if(root != null)
+ {
+ if(root.hasLeftChild() || root.hasRightChild())
+ {
+ //System.out.println("Found non-leaf node Right:" + root.hasRightChild() + " left: " + root.hasLeftChild());
+ output += "I";
+ output += getTreeStringHelper(root.getLeftChild());
+ output += getTreeStringHelper(root.getRightChild());
+ return output;
+ }
+ else
+ {
+ //System.out.println("Found a leaf node!");
+ output += "L"+root.getData();
+ return output;
+ }
+ }
+ else
+ {
+ return output;
+ }
+ // if(root.hasLeftChild())
+ // {
+ // //System.out.println("Finding left child");
+ // output += getTreeStringHelper(root.getLeftChild());
+ // }
+ // if(root.hasRightChild())
+ // {
+ // //System.out.println("Finding right child");
+ // output += getTreeStringHelper(root.getRightChild());
+ // }
+ // return output;
+ }
+
+ /**
+ * Compress the message using Huffman tree represented by treeString
+ * @param root the root node of a Huffman tree
+ * @param message the message to be compressed
+ * @return a string representing compressed message.
+ */
+ public static String compress(final BinaryNodeInterface<Character> root, final String message)
+ {
+ // TO DO
+ //System.out.println("Got tree: " + getTreeString(root));
+ return compressHelper(root,message);
+ //return ""; // Do not forget to change this line!!!
+ }
+ private static String compressHelper(final BinaryNodeInterface<Character> root, final String message)
+ {
+ String output = "";
+ if(message.isEmpty())
+ {
+ return output;
+ }
+ else
+ {
+ output += getStringForChar(root,message.charAt(0));
+ output += compressHelper(root,message.substring(1));
+ return output;
+ }
+ }
+ private static String getStringForChar(BinaryNodeInterface<Character> root, char c)
+ {
+ return getStringForCharHelper(root,c,"");
+ }
+ private static String getStringForCharHelper(BinaryNodeInterface<Character> root,char c, String p)
+ {
+ if(root == null)
+ return "";
+ if(root.getData() != null && root.getData().equals(new Character(c)))
+ {
+ return p;
+ }
+ String output = "";
+ if(root.hasLeftChild())
+ {
+ output = getStringForCharHelper(root.getLeftChild(),c,p+"0");
+ }
+ if(root.hasRightChild() && output == "")
+ {
+ output = getStringForCharHelper(root.getRightChild(),c,p+"1");
+ }
+ return output;
+ }
+ /**
+ * Decompress the message using Huffman tree represented by treeString
+ * @param treeString the string represents the Huffman tree of the
+ * compressed message
+ * @param message the compressed message to be decompressed
+ * @return a string representing decompressed message
+ */
+ public static String decompress(final String treeString, final String message)
+ {
+ //First, create a tree out of treeString
+ BinaryNode<Character> node = getTreeFor(treeString);
+ //Then find the output from this string
+ String output = "";
+ for(int i = 0; i < message.length();)
+ {
+ BinaryNodeInterface tmp = node;
+ while(!tmp.isLeaf())
+ {
+ if(message.charAt(i) == '0')
+ {
+ tmp = tmp.getLeftChild();
+ }
+ else if(message.charAt(i) == '1')
+ {
+ tmp = tmp.getRightChild();
+ }
+ i++;
+ }
+ output += tmp.getData();
+ }
+ return output; // Do not forget to change this line!!!
+ }
+ private static BinaryNode<Character> getTreeFor(String pre)
+ {
+ if(pre.isEmpty())
+ {
+ return null;
+ }
+ char type = pre.charAt(0);
+ BinaryNode<Character> root = new BinaryNode<Character>(null,null,null);
+ if(type == 'I')
+ {
+ int length = 0;
+ if(!root.hasLeftChild())
+ {
+ length = treeLength(pre.substring(1));
+ String lefttree = pre.substring(1,length+1);
+ root.setLeftChild(getTreeFor(lefttree));
+ }
+ if(!root.hasRightChild())
+ {
+ String righttree = pre.substring(length+1);
+ root.setRightChild(getTreeFor(righttree));
+ }
+ return root;
+ }
+ else if(type == 'L')
+ {
+ root.setData(pre.charAt(1));
+ return root;
+ }
+ return root;
+ }
+ private static int treeLength(String s) //Figure out how long the string should be
+ {
+ int output = 1;
+ for(int i = 0; i < output; i++)
+ {
+ if(s.charAt(i) == 'I')
+ {
+ output += 2;
+ }
+ if(s.charAt(i) == 'L')
+ {
+ output += 1;
+ i++;
+ }
+ }
+ return output;
+ }
+
+}
diff --git a/projects/project4_huffman_tree/CompressDecompressGUI.java b/projects/project4_huffman_tree/CompressDecompressGUI.java
new file mode 100644
index 0000000..20ecbd0
--- /dev/null
+++ b/projects/project4_huffman_tree/CompressDecompressGUI.java
@@ -0,0 +1,217 @@
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.GridLayout;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JTextArea;
+import javax.swing.border.TitledBorder;
+
+@SuppressWarnings("serial")
+public class CompressDecompressGUI extends JFrame
+{
+ JPanel inputTextAreaPanel;
+ JPanel outputTreePanel;
+ JPanel outputCompressPanel;
+ JPanel outputDecompressPanel;
+ JPanel inputTextPanel;
+ JPanel treeTextPanel;
+ JPanel outputTextPanel;
+
+ JTextArea inputTextArea;
+ JTextArea outputTreeArea;
+ JTextArea outputCompressArea;
+ JTextArea outputDecompressArea;
+
+ JScrollPane inputTextPane;
+ JScrollPane outputTreePane;
+ JScrollPane compressPane;
+ JScrollPane decompressPane;
+
+ JLabel inputNumberOfCharactersLabel;
+ JLabel inputNumberOfBytesLabel;
+ JLabel treeNumberOfCharactersLabel;
+ JLabel treeNumberOfBytesLabel;
+ JLabel outputNumberOfBytesLabel;
+ JLabel outputTotalNumberOfBytesLabel;
+ JLabel compressLabel;
+ KeyListener kListener;
+
+ public CompressDecompressGUI()
+ {
+ setLayout(new GridLayout(2,2));
+
+ setTextAreasAndPanels();
+ }
+
+ private void setTextAreasAndPanels()
+ {
+ Font monoFont = new Font("Monospaced", Font.BOLD, 14);
+
+ // Input Text
+
+ inputTextAreaPanel = new JPanel();
+ inputTextAreaPanel.setBackground(Color.WHITE);
+ inputTextAreaPanel.setLayout(new BorderLayout());
+ inputTextAreaPanel.setBorder(new TitledBorder("Type Your Message Here"));
+
+ inputTextArea = new JTextArea();
+ inputTextArea.setEditable(true);
+ inputTextArea.setLineWrap(true);
+ inputTextArea.setFont(monoFont);
+ kListener = new InputKeyEvent();
+ inputTextArea.addKeyListener(kListener);
+ inputTextPane = new JScrollPane(inputTextArea);
+ inputTextAreaPanel.add(inputTextPane);
+ inputTextPanel = new JPanel();
+ inputTextPanel.setLayout(new GridLayout(2,1));
+ inputNumberOfCharactersLabel = new JLabel("Number of Characters: 0");
+ inputNumberOfBytesLabel = new JLabel("Number of Bytes: 0");
+ inputTextPanel.add(inputNumberOfCharactersLabel);
+ inputTextPanel.add(inputNumberOfBytesLabel);
+ inputTextAreaPanel.add(inputTextPanel, BorderLayout.SOUTH);
+
+ // Output Tree
+
+ outputTreePanel = new JPanel();
+ outputTreePanel.setBackground(Color.WHITE);
+ outputTreePanel.setLayout(new BorderLayout());
+ outputTreePanel.setBorder(new TitledBorder("Tree Structure"));
+ outputTreeArea = new JTextArea();
+ outputTreeArea.setEditable(false);
+ outputTreeArea.setLineWrap(true);
+ outputTreeArea.setFont(monoFont);
+ outputTreePane = new JScrollPane(outputTreeArea);
+ outputTreePanel.add(outputTreePane);
+ treeTextPanel = new JPanel();
+ treeTextPanel.setLayout(new GridLayout(2,1));
+ treeNumberOfCharactersLabel = new JLabel("Number of Characters: 0");
+ treeNumberOfBytesLabel = new JLabel("Number of Bytes: 0");
+ treeTextPanel.add(treeNumberOfCharactersLabel);
+ treeTextPanel.add(treeNumberOfBytesLabel);
+ outputTreePanel.add(treeTextPanel, BorderLayout.SOUTH);
+
+ // Compressed Output
+
+ outputCompressPanel = new JPanel();
+ outputCompressPanel.setBackground(Color.WHITE);
+ outputCompressPanel.setLayout(new BorderLayout());
+ outputCompressPanel.setBorder(new TitledBorder("Compressed Message"));
+ outputCompressArea = new JTextArea();
+ outputCompressArea.setEditable(false);
+ outputCompressArea.setLineWrap(true);
+ outputCompressArea.setFont(monoFont);
+ compressPane = new JScrollPane(outputCompressArea);
+ outputCompressPanel.add(compressPane);
+ outputTextPanel = new JPanel();
+ outputTextPanel.setLayout(new GridLayout(3,1));
+ outputNumberOfBytesLabel = new JLabel("Number of Bytes: 0");
+ outputTotalNumberOfBytesLabel = new JLabel("Total Number of Bytes: 0");
+ compressLabel = new JLabel("Compressed to 100% of the original size");
+ outputTextPanel.add(outputNumberOfBytesLabel);
+ outputTextPanel.add(outputTotalNumberOfBytesLabel);
+ outputTextPanel.add(compressLabel);
+ outputCompressPanel.add(outputTextPanel, BorderLayout.SOUTH);
+
+ // Decompress Output
+
+ outputDecompressPanel = new JPanel();
+ outputDecompressPanel.setBackground(Color.WHITE);
+ outputDecompressPanel.setLayout(new BorderLayout());
+ outputDecompressPanel.setBorder(new TitledBorder("Decompress Message"));
+ outputDecompressArea = new JTextArea();
+ outputDecompressArea.setEditable(false);
+ outputDecompressArea.setLineWrap(true);
+ outputDecompressArea.setFont(monoFont);
+ decompressPane = new JScrollPane(outputDecompressArea);
+ outputDecompressPanel.add(decompressPane);
+
+ add(inputTextAreaPanel);
+ add(outputTreePanel);
+ add(outputCompressPanel);
+ add(outputDecompressPanel);
+ }
+
+ private class InputKeyEvent implements KeyListener
+ {
+ public void keyPressed(KeyEvent arg0)
+ {
+ }
+
+ public void keyReleased(KeyEvent arg0)
+ {
+ /* Obtain the string from inputTextArea and
+ * calculate the number of bytes from its length.
+ * Assuming that we use unicode which is two bytes
+ * per character.
+ */
+ String str = inputTextArea.getText();
+
+ int inputStringLength = str.length();
+ int inputStringBytes = str.length() * 2;
+ inputNumberOfCharactersLabel.setText("Number of Characters: " + inputStringLength);
+ inputNumberOfBytesLabel.setText("Number of Bytes: " + inputStringBytes);
+
+ /* Generate Huffman tree from the input string
+ * and obtain the root node of the Huffman tree.
+ */
+ HuffmanTree ht = new HuffmanTree(str);
+ BinaryNodeInterface<Character> root = ht.getRootNode();
+
+ /* Generate a string representing the Huffman tree rooted
+ * at root and display the string on outputTreeArea.
+ */
+ String treeString = CompressDecompress.getTreeString(root);
+ outputTreeArea.setText(treeString);
+
+ int treeStringLength = treeString.length();
+ int treeStringBytes = treeStringLength * 2;
+
+ treeNumberOfCharactersLabel.setText("Number of Characters: " + treeStringLength);
+ treeNumberOfBytesLabel.setText("Number of Bytes: " + treeStringBytes);
+
+ /* Compress the input string (str) using the Huffman tree rooted at
+ * root. The result is a new string containing just 0s and 1s. Then
+ * display the result on outputCompressArea.
+ */
+ String compressedString = CompressDecompress.compress(root, str);
+ outputCompressArea.setText(compressedString);
+ int numBytes = compressedString.length() / 8;
+ if(compressedString.length() % 8 != 0)
+ {
+ numBytes++;
+ }
+ outputNumberOfBytesLabel.setText("Number of Bytes: " + numBytes);
+ outputTotalNumberOfBytesLabel.setText("Total Number of Bytes: " + (numBytes + treeStringBytes));
+ float percentCompression = (float) (numBytes + treeStringBytes) / inputStringBytes * 100;
+ compressLabel.setText("Compressed to " + String.format("%.2f", percentCompression) + "% of the original size");
+
+ /* Decompress the compressed string (compressedString) using
+ * the string representing the Huffman tree (treeString). The
+ * result is a new string which should be exactly the same
+ * as the input string (str). Then display the result string
+ * on outputDecompressArea.
+ */
+ String decompressedString = CompressDecompress.decompress(treeString, compressedString);
+ outputDecompressArea.setText(decompressedString);
+ }
+
+ public void keyTyped(KeyEvent arg0)
+ {
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ JFrame frame = new CompressDecompressGUI();
+ frame.setSize(700,600);
+ frame.setTitle("Huffman Tree - Compression / Decompression");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frame.setVisible(true);
+ }
+} \ No newline at end of file
diff --git a/projects/project4_huffman_tree/CompressDecompressTester.java b/projects/project4_huffman_tree/CompressDecompressTester.java
new file mode 100644
index 0000000..eeae7ca
--- /dev/null
+++ b/projects/project4_huffman_tree/CompressDecompressTester.java
@@ -0,0 +1,159 @@
+
+public class CompressDecompressTester
+{
+ public static void main(String[] args)
+ {
+ int numErrors = 0;
+
+ // Test getTreeString()
+
+ System.out.print("Testing the method getTreeString() with an empty tree: ");
+ if(CompressDecompress.getTreeString(null) != "")
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.getTreeString(null) shoudl return an empty string (\"\").");
+ System.out.println("But your method getTreeString(null) returns " + CompressDecompress.getTreeString(null) + ".\n");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ System.out.println("A two node tree was constructed (from nodes) using the following statements:");
+ System.out.println(" BinaryNodeInterface<Character> nodeA = new BinaryNode<Character>('a');");
+ System.out.println(" BinaryNodeInterface<Character> twoNodeTreeRoot = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeA, null);");
+ System.out.print("Testing the method getTreeString() with two node tree: ");
+ BinaryNodeInterface<Character> nodeA = new BinaryNode<Character>('a');
+ BinaryNodeInterface<Character> twoNodeTreeRoot = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeA, null);
+ if(!CompressDecompress.getTreeString(twoNodeTreeRoot).equals("ILa"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The method getTreeString(twoNodeTreeRoot) should return ILa.");
+ System.out.println("But your method getTreeString(twoNodeTreeRoot) returns " + CompressDecompress.getTreeString(twoNodeTreeRoot) + ".\n");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ System.out.println("A nine node tree was constructed (from nodes) using the following statements:");
+ System.out.println(" BinaryNodeInterface<Character> nodeA = new BinaryNode<Character>('a');");
+ System.out.println(" BinaryNodeInterface<Character> nodeB = new BinaryNode<Character>('b');");
+ System.out.println(" BinaryNodeInterface<Character> nodeC = new BinaryNode<Character>('c');");
+ System.out.println(" BinaryNodeInterface<Character> nodeD = new BinaryNode<Character>('d');");
+ System.out.println(" BinaryNodeInterface<Character> nodeE = new BinaryNode<Character>('e');");
+ System.out.println(" BinaryNodeInterface<Character> nodeAB = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeA, (BinaryNode<Character>) nodeB);");
+ System.out.println(" BinaryNodeInterface<Character> nodeCD = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeC, (BinaryNode<Character>) nodeD);");
+ System.out.println(" BinaryNodeInterface<Character> nodeABCD = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeAB, (BinaryNode<Character>) nodeCD);");
+ System.out.println(" BinaryNodeInterface<Character> nodeABCDE = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeABCD, (BinaryNode<Character>) nodeE);");
+ System.out.print("Testing the method getTreeString() with nine node tree: ");
+ BinaryNodeInterface<Character> nodeB = new BinaryNode<Character>('b');
+ BinaryNodeInterface<Character> nodeC = new BinaryNode<Character>('c');
+ BinaryNodeInterface<Character> nodeD = new BinaryNode<Character>('d');
+ BinaryNodeInterface<Character> nodeE = new BinaryNode<Character>('e');
+ BinaryNodeInterface<Character> nodeAB = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeA, (BinaryNode<Character>) nodeB);
+ BinaryNodeInterface<Character> nodeCD = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeC, (BinaryNode<Character>) nodeD);
+ BinaryNodeInterface<Character> nodeABCD = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeAB, (BinaryNode<Character>) nodeCD);
+ BinaryNodeInterface<Character> nodeABCDE = new BinaryNode<Character>(null, (BinaryNode<Character>) nodeABCD, (BinaryNode<Character>) nodeE);
+ if(!CompressDecompress.getTreeString(nodeABCDE).equals("IIILaLbILcLdLe"))
+ {
+ System.out.println("FAIL");
+ System.out.println("The method getTreeString(nodeABCDE) should return IIILaLbILcLdLe.");
+ System.out.println("But your method getTreeString(nodeABCDE) returns " + CompressDecompress.getTreeString(nodeABCDE) + ".\n");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS\n");
+ }
+
+ // Test compress()
+
+ System.out.print("Testing the method compress with an empty input string: ");
+ if(!CompressDecompress.compress(null, "").equals(""))
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.compress(null,\"\") shoudl return an empty string (\"\").");
+ System.out.println("But your method compress(null,\"\") returns " + CompressDecompress.compress(null,"") + ".\n");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Testing the method compress using two node tree from previous test and the input string is \"aaaa\": ");
+ if(!CompressDecompress.compress(twoNodeTreeRoot, "aaaa").equals("0000"))
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.compress(twoNodeTreeRoot,\"aaaa\") should return \"0000\".");
+ System.out.println("But your method compress(twoNodeTreeRoot,\"aaaa\") returns " + CompressDecompress.compress(twoNodeTreeRoot,"aaaa") + ".");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Testing the method compress using nine node tree from previous test and the input string is \"abcde\": ");
+ if(!CompressDecompress.compress(nodeABCDE, "abcde").equals("0000010100111"))
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.compress(nodeABCDE,\"abcde\") should return \"0000010100111\".");
+ System.out.println("But your method compress(twoNodeTreeRoot,\"abcde\") returns " + CompressDecompress.compress(nodeABCDE,"abcde") + ".");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ // Test decompress()
+
+ System.out.println();
+
+ System.out.print("Testing the method decompress with empty tree and empty string: ");
+ if(!CompressDecompress.decompress("", "").equals(""))
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.decompress(\"\", \"\") should return an empty string (\"\").");
+ System.out.println("But your method decompress(\"\", \"\") returns " + CompressDecompress.decompress("", "") + ".");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.print("Testing the method decompress with the tree string IIILaLbILcLdLe and input string 1011010001000: ");
+ if(!CompressDecompress.decompress("IIILaLbILcLdLe", "1011010001000").equals("edcba"))
+ {
+ System.out.println("FAIL");
+ System.out.println("CompressDecompress.decompress(\"IIILaLbILcLdLe\", \"1011010001000\" should return edcba.");
+ System.out.println("But your method decompress(\"IIILaLbILcLdLe\", \"1011010001000\" returns " + CompressDecompress.decompress("IIILaLbILcLdLe", "1011010001000") + ".");
+ numErrors++;
+ }
+ else
+ {
+ System.out.println("PASS");
+ }
+
+ System.out.println();
+
+ if(numErrors == 0)
+ {
+ System.out.println("Your CompressDecompress works perfectly (I guess). Here is your reward:\n");
+ String jokeTree = "IIILeILaIIL\nILWIL?LvILgLkIILuLoILnLsIIIIIL,LbIL\"LfLtIILrLlIIILTIILILSILALmLyIIL.L'IIILYLGIL!LHLwIIILdILpLcILhLiL ";
+ String jokeCompressed = "1011001101111100110101101100111110010010010010001010011101111100111101100001101100110001110111100101001100000001101001111110110111111011110010100110001011011101101100011101110100011011000000101001110010111100110100000000111001001101100011100100110010110011101000010100111110010010010101101010111111010011001011101010110111001011110001110101001001111101010110111101100001011111111100001110110011110001011100111101100011010000111100011110111010001111001111011110010100110000000110100111100100111001111011110000011110001000110101101000010100000101110111000111101101010101001110011100001001111100111010001010010011011010001000110000110010110001101000011101111001010011000000011010011110101011011110011101000011110000111011001111000111101000001100101010111011000011110000011110001000110101101011011101010001111011001001111011111001001111110111100101001100010110111011011000111011101010100100101111101111000000100000111001011110000100000100100100111011100011010010101111001110110111010010101111110010010010101101010001100011101001100101110101011011111010000101001111000011101100111100010111001111011001011101000011110010101010100111111101011000111000111110010101011010111111010000101001111100111010101011001110100000111111001001101100011101110010110111100010000011110111011011110000101010011111001100100110111110100010001101110001110010011010110110011101011011011000111011110110101010100111101111100100110100110111011011100100010001100001100101100011010000111100011110111010001111001111011110010100110000000110100111110100000011111001001010110110000111100000111100010101111001010101011100011111001111010010111011110011000101111010111101111011000101001111100111010101011001110100000111111110010101000101100001001010000110101101101111101111101010100101011100001101011101100111111010001000110111000111100011110111001111101101010101001011100100010";
+
+ System.out.println(CompressDecompress.decompress(jokeTree, jokeCompressed));
+ }
+ else
+ {
+ System.out.println("There are " + numErrors + " errors in your CompressDecompress.java");
+ System.out.println("Fix your code and try again.");
+ }
+ }
+}
diff --git a/projects/project4_huffman_tree/HuffmanTree.java b/projects/project4_huffman_tree/HuffmanTree.java
new file mode 100644
index 0000000..dcbb0b4
--- /dev/null
+++ b/projects/project4_huffman_tree/HuffmanTree.java
@@ -0,0 +1,127 @@
+import java.util.ArrayList;
+
+public class HuffmanTree
+{
+ private String str;
+ private BinaryNodeInterface<Character> root;
+ private ArrayList<Character> charList;
+ private ArrayList<Integer> freqList;
+
+ public HuffmanTree(String aString)
+ {
+ str = aString;
+ root = null;
+
+ generateFrequencyList();
+ generateHuffmanTree();
+ }
+
+ public BinaryNodeInterface<Character> getRootNode()
+ {
+ return root;
+ }
+
+ private void generateHuffmanTree()
+ {
+ if(str == null || str.equals(""))
+ {
+ root = null;
+ return;
+ }
+
+ MinHeapInterface<BinaryNodeFrequency<Character>> heap = new MinHeap<BinaryNodeFrequency<Character>>();
+
+ while(!charList.isEmpty())
+ {
+ char c = charList.remove(0);
+ int freq = freqList.remove(0);
+
+ BinaryNodeInterface<Character> newNode = new BinaryNode<Character>(c);
+ BinaryNodeFrequency<Character> newBNode = new BinaryNodeFrequency<Character>(newNode, freq);
+ heap.add(newBNode);
+ }
+
+ while(!heap.isEmpty())
+ {
+ BinaryNodeFrequency<Character> left = heap.removeMin();
+ if(heap.isEmpty())
+ {
+ root = left.node;
+ break;
+ }
+
+ BinaryNodeFrequency<Character> right = heap.removeMin();
+
+ int newFrequency = left.frequency + right.frequency;
+ BinaryNodeInterface<Character> newNode = new BinaryNode<Character>(null, (BinaryNode<Character>) left.node, (BinaryNode<Character>) right.node);
+ BinaryNodeFrequency<Character> newBNode = new BinaryNodeFrequency<Character>(newNode, newFrequency);
+ heap.add(newBNode);
+ }
+
+ if(root.isLeaf())
+ {
+ BinaryNodeInterface<Character> newNode = new BinaryNode<Character>(null, (BinaryNode<Character>) root, null);
+ root = newNode;
+ }
+
+ }
+
+ private void generateFrequencyList()
+ {
+ charList = new ArrayList<Character>();
+ freqList = new ArrayList<Integer>();
+
+ int strLength = str.length();
+
+ for(int i = 0; i < strLength; i++)
+ {
+ char c = str.charAt(i);
+ int charIndex = charList.indexOf(c);
+
+ if(charIndex != -1)
+ {
+ freqList.set(charIndex, freqList.get(charIndex) + 1);
+ }
+ else
+ {
+ charList.add(c);
+ freqList.add(1);
+ }
+ }
+ }
+
+ /* The min heap requires the object to implement comparable. According
+ * to the algorithm, we need to add BinaryNode into the min heap. However,
+ * BinaryNodes are not comparable, so we need a new type of object that
+ * can be used to represent a BinaryNode that implements Comparable.
+ * In this situation, our BinaryNode will be used to store a character.
+ * To compare, we compare the frequency of the character.
+ */
+ private class BinaryNodeFrequency<T> implements Comparable<BinaryNodeFrequency<T>>
+ {
+ private BinaryNodeInterface<T> node;
+ private int frequency;
+
+ private BinaryNodeFrequency(BinaryNodeInterface<T> aNode, int aFrequency)
+ {
+ node = aNode;
+ frequency = aFrequency;
+ }
+
+ public int compareTo(BinaryNodeFrequency<T> otherBNF)
+ {
+ if(frequency < otherBNF.frequency)
+ {
+ return -1;
+ }
+ else if(frequency > otherBNF.frequency)
+ {
+ return 1;
+ }
+ else
+ {
+ return 0;
+ }
+ }
+ }
+}
diff --git a/projects/project4_huffman_tree/MinHeap.java b/projects/project4_huffman_tree/MinHeap.java
new file mode 100644
index 0000000..3b46287
--- /dev/null
+++ b/projects/project4_huffman_tree/MinHeap.java
@@ -0,0 +1,132 @@
+
+public class MinHeap<T extends Comparable<? super T>> implements MinHeapInterface<T>
+{
+ private T[] heap;
+ private int lastIndex;
+ private static final int DEFAULT_INITIAL_CAPACITY = 25;
+
+ public MinHeap()
+ {
+ this(DEFAULT_INITIAL_CAPACITY);
+ }
+
+ public MinHeap(int initialCapacity)
+ {
+ @SuppressWarnings("unchecked")
+ T[] tempHeap = (T[]) new Comparable[initialCapacity];
+
+ heap = tempHeap;
+ lastIndex = 0;
+ }
+
+ public void add(T newEntry)
+ {
+ lastIndex++;
+ ensureCapacity();
+
+ int newIndex = lastIndex;
+ int parentIndex = newIndex / 2;
+
+ while((parentIndex > 0) && newEntry.compareTo(heap[parentIndex]) < 0)
+ {
+ heap[newIndex] = heap[parentIndex];
+ newIndex = parentIndex;
+ parentIndex = newIndex / 2;
+ }
+
+ heap[newIndex] = newEntry;
+ }
+
+ public T removeMin()
+ {
+ T root = null;
+
+ if(!isEmpty())
+ {
+ root = heap[1];
+ heap[1] = heap[lastIndex];
+ lastIndex--;
+ reheap(1);
+ }
+
+ return root;
+ }
+
+ public T getMin()
+ {
+ T root = null;
+
+ if(!isEmpty())
+ {
+ root = heap[1];
+ }
+
+ return root;
+ }
+
+ public boolean isEmpty()
+ {
+ return lastIndex < 1;
+ }
+
+ public int getSize()
+ {
+ return lastIndex;
+ }
+
+ public void clear()
+ {
+ for(int i = 0; i <= lastIndex; i++)
+ {
+ heap[i] = null;
+ }
+
+ lastIndex = 0;
+ }
+
+ private void ensureCapacity()
+ {
+ if(heap.length == lastIndex)
+ {
+ @SuppressWarnings("unchecked")
+ T[] tempHeap = (T[]) new Comparable[heap.length * 2];
+
+ for(int i = 0; i < lastIndex; i++)
+ {
+ tempHeap[i] = heap[i];
+ }
+
+ heap = tempHeap;
+ }
+ }
+
+ private void reheap(int rootIndex)
+ {
+ boolean done = false;
+ T orphan = heap[rootIndex];
+ int leftChildIndex = rootIndex * 2;
+
+ while(!done && (leftChildIndex <= lastIndex))
+ {
+ int smallerChildIndex = leftChildIndex;
+ int rightChildIndex = leftChildIndex + 1;
+ if((rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[smallerChildIndex]) < 0)
+ {
+ smallerChildIndex = rightChildIndex;
+ }
+
+ if(orphan.compareTo(heap[smallerChildIndex]) > 0)
+ {
+ heap[rootIndex] = heap[smallerChildIndex];
+ rootIndex = smallerChildIndex;
+ leftChildIndex = rootIndex * 2;
+ }
+ else
+ {
+ done = true;
+ }
+ }
+
+ heap[rootIndex] = orphan;
+ }
+}
diff --git a/projects/project4_huffman_tree/MinHeapInterface.java b/projects/project4_huffman_tree/MinHeapInterface.java
new file mode 100644
index 0000000..5728a67
--- /dev/null
+++ b/projects/project4_huffman_tree/MinHeapInterface.java
@@ -0,0 +1,11 @@
+
+public interface MinHeapInterface<T extends Comparable<? super T>>
+{
+ public void add(T newEntry);
+ public T removeMin();
+ public T getMin();
+ public boolean isEmpty();
+ public int getSize();
+ public void clear();
+
+}
diff --git a/projects/project4_huffman_tree/project4_huffman_tree.pdf b/projects/project4_huffman_tree/project4_huffman_tree.pdf
new file mode 100644
index 0000000..8a06f3c
--- /dev/null
+++ b/projects/project4_huffman_tree/project4_huffman_tree.pdf
Binary files differ