Selaa lähdekoodia

Created, finished, and tested project 2.

Tom Flucke 10 vuotta sitten
vanhempi
commit
54c8e15cc0

+ 6 - 0
Project2/.classpath

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

+ 17 - 0
Project2/.project

@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>Project2</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>

+ 11 - 0
Project2/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,11 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6

+ 235 - 0
Project2/src/BinHeap.java

@@ -0,0 +1,235 @@
+/**
+ * Binary minimum heap implementation using the Comparable interface.
+ * 
+ * Project 2
+ * 
+ * @author Thomas Flucke tflucke
+ * @author Lara Luu ljluu
+ * 
+ * @since 2015/10/21
+ * 
+ * @see Comparable
+ */
+
+public class BinHeap<T extends Comparable<? super T>>
+{
+	/**
+	 * An exception to be thrown when an invalid operation is invoked while the heap is empty.
+	 * Basically a carbon-copy of RuntimeException
+	 * 
+	 * Project 2
+	 * 
+	 * @author Thomas Flucke tflucke
+	 * @author Lara Luu ljluu
+	 * 
+	 * @since 2015/10/21
+	 */
+	@SuppressWarnings("serial")
+	public static class MyException extends RuntimeException
+	{
+		/**
+		 * Default constructor which just calls the super constructor.
+		 */
+		public MyException()
+		{
+			super();
+		}
+
+		/**
+		 * Constructor which just passes a string argument to the super constructor.
+		 */
+		public MyException(String msg)
+		{
+			super(msg);
+		}
+	}
+	
+	/**
+	 * The array which holds the elements in the heap in the left-to-right, top-to-bottom order.
+	 */
+	private T[] array;
+	
+	/**
+	 * Number of valid elements in the heap.
+	 */
+	private int count;
+
+	/**
+	 * Creates a new heap with a default size of 100.
+	 */
+	@SuppressWarnings("unchecked")
+	public BinHeap()
+	{
+		array = (T[]) new Comparable[100];
+		count = 0;
+	}
+
+	/**
+	 * Creates a new heap with a given size.
+	 * 
+	 * @param maxSize The size of the heap.
+	 */
+	@SuppressWarnings("unchecked")
+	public BinHeap(int maxSize)
+	{
+		array = (T[]) new Comparable[maxSize];
+		count = 0;
+	}
+
+	/**
+	 * Inserts a new item into the heap.
+	 * @param item The item to be inserted.
+	 */
+	public void insert(T item)
+	{
+		if(count >= array.length)
+		{
+			resizeArray();
+		}
+		
+		bubbleUp(count++, item);
+	}
+	
+	/**
+	 * Resizes the array to twice it's original size.
+	 * Used when the heap is filled and an element needs to be added.
+	 */
+	private void resizeArray()
+	{
+		@SuppressWarnings("unchecked")
+		//The new array of double the length of the original
+		T[] newArray = (T[]) new Comparable[2*array.length];
+		for(int x = 0; x < count; x++)
+		{
+			newArray[x] = array[x];
+		}
+		array = newArray;
+	}
+	
+	/**
+	 * Checks if the parent is larger than the given index, and swaps the two if necessary.
+	 * Used to correct issues with smaller elements being in the bottom of the heap after an insert.
+	 * @param index The index of the element which to (maybe) move up.
+	 * @param value The value which to move up the heap
+	 */
+	private void bubbleUp(int index, T value)
+	{
+		//The index of this node's parent
+		int parentIndex = (index - 1) / 2;
+		if(count != 1 && value.compareTo(array[parentIndex]) < 0)
+		{
+			array[index] = array[parentIndex];
+			bubbleUp(parentIndex, value);
+		}
+		else
+		{
+			array[index] = value;
+		}
+	}
+	
+	/**
+	 * Deletes the element from the top of the heap (also the minimum element)
+	 * @return The deleted element
+	 * @throws MyException If the heap is empty
+	 */
+	public T deleteMin()
+	{
+		if (count == 0)
+		{
+			throw new MyException();
+		}
+		else
+		{
+			//Temporarily store the return value
+			T res = array[0];
+			bubbleDown(0, array[--count]);
+			return res;
+		}
+	}
+
+	/**
+	 * Checks if the children are smaller than the given index, and swaps the two if necessary.
+	 * Used to correct issues with larger elements being in the top of the heap after a delete.
+	 * @param index The index of the element which to (maybe) move down.
+	 * @param value The value which to move down the heap
+	 */
+	private void bubbleDown(int index, T value)
+	{
+		//The child to be moved down to.  -1 if the element has no children which are smaller than it.
+		int hole = newHole(index, value);
+		if (hole == -1)
+		{
+			array[index] = value;
+		}
+		else
+		{
+			array[index] = array[hole];
+			bubbleDown(hole, value);
+		}
+	}
+	
+	/**
+	 * Checks which of the two child nodes should be swap with the parent (if any).
+	 * Used after a delete.
+	 * @param parent The element whose children to check
+	 * @param value The value which will be considered for the parent spot.
+	 * @return Either the index of the appropriate child, or -1 if the parent is in a good situation.
+	 */
+	private int newHole(int parent, T value)
+	{
+		//The indexes of the left and right children.
+		int leftChild = 2 * parent + 1, rightChild = 2 * parent + 2;
+		
+		if (leftChild < count)
+		{
+			if (array[leftChild].compareTo(value) < 0 &&
+				(rightChild >= count || array[leftChild].compareTo(array[rightChild]) < 0)
+			   )
+			{
+				return leftChild;
+			}
+			else if (rightChild < count && array[rightChild].compareTo(value) < 0)
+			{
+				return rightChild;
+			}
+		}
+		return -1;
+	}
+	
+	/**
+	 * Checks whether or not there are any elements in the heap.
+	 * @return true if there are no elements in the heap.  false otherwise.
+	 */
+	public boolean isEmpty()
+	{
+		return count == 0;
+	}
+	
+	 /**
+	  * Returns the number of elements in the heap.
+	  * @return Number of elements in the heap.
+	  */
+	public int size()
+	{
+		return count;
+	}
+	
+	/**
+	 * Creates a string representation of the heap as a space seperated list.
+	 */
+	@Override
+	public String toString()
+	{
+		if(!isEmpty())
+		{
+			//Stores the result until it's ready to be returned.
+			String printArray = new String();
+			for(int i = 0; i < count-1; i ++)
+			{
+				printArray += array[i] + " ";
+			}
+			return printArray + array[count - 1];
+		}
+		return "";
+	}
+}

+ 96 - 0
Project2/src/HeapTest.java

@@ -0,0 +1,96 @@
+/**
+ * Driver program to allow command line user to interface with the BinHeap class.
+ * 
+ * Project 2
+ * 
+ * @author Thomas Flucke tflucke
+ * @author Lara Luu ljluu
+ * 
+ * @since 2015/10/21
+ * 
+ * @see BinHeap
+ */
+import java.util.Scanner;
+
+public class HeapTest
+{
+	/**
+	 * Runs the program.
+	 */
+	public static void main(String[] args)
+	{
+		//Console input
+		Scanner in = new Scanner(System.in);
+		System.out.println("Enter heap size: ");
+		//Heap to store the inputs
+		BinHeap<String> heap = new BinHeap<String>(in.nextInt());
+		in.nextLine();
+	
+		System.out.println("Choose one of the following operations:");
+		System.out.println("- add an element (enter the letter a)");
+		System.out.println("- delete the smallest element (enter the letter d)");
+		System.out.println("- is the heap empty (enter the letter e)");
+		System.out.println("- size of the collection (enter the letter s)");
+		System.out.println("- Quit (enter the letter q)");
+		//Remains true as long as the user doesn't quit.
+		boolean running = true;
+		while (running)
+		{
+			System.out.println("Enter a menu choice: ");
+			//The current line which should contain the command
+			String line = in.nextLine();
+			if (line.length() != 1)
+			{
+				System.out.println("Invalid choice");
+				continue;
+			}
+			//The one character command inputed
+			char command = line.charAt(0);
+			switch (command)
+			{
+				case 'a':
+					System.out.println("Enter a value:");
+					String newVal = in.nextLine();
+					heap.insert(newVal);
+					System.out.println(newVal+" inserted");
+					break;
+				case 'd':
+					try
+					{
+						System.out.println(heap.deleteMin() +" deleted");
+					}
+					catch (BinHeap.MyException me)
+					{
+						System.out.println("Invalid operation on an empty heap");
+					}
+					break;
+				case 'e':
+					System.out.println(heap.isEmpty()? "heap is empty":"heap is not empty");
+					break;
+				case 's':
+					System.out.println("the size is "+heap.size());
+					break;
+				case 'p':
+					System.out.println(heap);
+					break;
+				case 'q':
+					running = false;
+					System.out.println("Quitting");
+					break;
+				default:
+					System.out.println("Invalid Option.");
+			}
+		}
+		in.close();
+		if (!heap.isEmpty())
+		{
+			System.out.print(heap.deleteMin());
+		}
+		while (!heap.isEmpty())
+		{
+			System.out.print(" "+heap.deleteMin());
+		}
+		System.out.println();
+	}
+
+}

+ 58 - 0
Project2/src/ListPrinter.java

@@ -0,0 +1,58 @@
+/**
+ * Reads student information from a file, ignoring invalid lines, and prints them in ascending order by id.
+ * Inputs must be one-per-line, formatted as such: "[id] [last name]"
+ * 
+ * Project 2
+ * 
+ * @author Thomas Flucke tflucke
+ * @author Lara Luu ljluu
+ * 
+ * @since 2015/10/22
+ * 
+ * @see Student
+ */
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.Scanner;
+
+public class ListPrinter 
+{
+	/**
+	 * Runs the program.
+	 */
+	public static void main(String[] args) throws FileNotFoundException
+	{
+		//Console input
+		Scanner consoleIn = new Scanner(System.in);
+		//Min heap to store the students
+		BinHeap<Student> studentHeap = new BinHeap<Student>();
+	
+		System.out.println("Salutations. Please enter the file name to be read.");
+
+		//File input
+		Scanner fileIn = new Scanner(new File(consoleIn.nextLine()));
+		
+		consoleIn.close();
+		
+		//Defines the format for what a (non-negative) long value looks like
+		final String longFormat = "^\\+?\\d+$";
+		while (fileIn.hasNextLine())
+		{
+			//Breaks the input line into whitespace separated parts
+			String[] inputLineParts = fileIn.nextLine().split("\\s");
+			if(inputLineParts.length == 2 && inputLineParts[0].matches(longFormat))
+			{
+				studentHeap.insert(new Student(Long.parseLong(inputLineParts[0]), inputLineParts[1]));
+			}
+		}
+		fileIn.close();
+		System.out.println("Student List: ");
+
+		//Tracks the current student's position in the list
+		int lineNum = 0;
+		while (!studentHeap.isEmpty())
+		{
+			System.out.println(++lineNum+". "+studentHeap.deleteMin());
+		}
+	}
+}

+ 66 - 0
Project2/src/Student.java

@@ -0,0 +1,66 @@
+/**
+ * Stores student id and last name in a sortable way.
+ * 
+ * Project 2
+ * 
+ * @author Thomas Flucke tflucke
+ * @author Lara Luu ljluu
+ * 
+ * @since 2015/10/22
+ */
+
+public class Student implements Comparable<Student> 
+{
+	/**
+	 * The student's id
+	 */
+	private long id;
+	
+	/**
+	 * The student's last name
+	 */
+	private String lastName;
+	
+	/**
+	 * Creates a new student object with he given id and last name
+	 * @param id The student's id number
+	 * @param lastName The student's last name
+	 */
+	public Student(long id, String lastName)
+	{
+		this.id = id;
+		this.lastName = lastName;
+	}
+	
+	/**
+	 * Compares this student to another by id. 
+	 * @return 1 if this student's id is greater, -1 if it is less, or 0 if they are equal
+	 */
+	public int compareTo(Student other)
+	{
+		if(this.id > other.id)
+		{
+			return 1;
+		}
+		else if (this.id < other.id)
+		{
+			return -1;
+		}
+		else
+		{
+			return 0;
+		}
+	}
+	
+	/**
+	 * Creates a string representation of the student object.
+	 * The string will be in the format: "{ id: [id], name: [last name] }".
+	 * @return The string representation of the student.
+	 */
+	@Override
+	public String toString()
+	{
+		return String.format("{ id: %d, name: %s }", this.id, this.lastName);
+	}
+
+}