Explorar o código

Project 4 initial commit

Tom Flucke %!s(int64=10) %!d(string=hai) anos
pai
achega
7aa10d6f47

+ 6 - 0
Project4/.classpath

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

+ 17 - 0
Project4/.project

@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>Project4</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>

+ 12 - 0
Project4/.settings/org.eclipse.jdt.core.prefs

@@ -0,0 +1,12 @@
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.7
+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.7

+ 222 - 0
Project4/src/HashTable.java

@@ -0,0 +1,222 @@
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+public class HashTable
+{
+	private class HashEntry
+	{
+		public Object elm;
+		public boolean active;
+		
+		public HashEntry(Object elm)
+		{
+			this.elm = elm;
+			active = true;
+		}
+	}
+	
+	private HashEntry[] table;
+	private int size;
+	
+	public HashTable(int tableCapacity)
+	{
+		table = new HashEntry[nextPrime(2*tableCapacity)];
+		size = 0;
+	}
+	
+	private static boolean isPrime(int num)
+	{
+		if (num % 2 == 0)
+		{
+			return false;
+		}
+		for (int i = 3; i*i <= num; i += 2)
+		{
+			if (num % i == 0)
+			{
+				return false;
+			}
+		}
+		return true;
+	}
+	
+	private static int nextPrime(int num)
+	{
+		if (num % 2 == 0)
+		{
+			num++;
+		}
+		while (!isPrime(num))
+		{
+			num += 2;
+		}
+		return num;
+	}
+	
+	private static boolean isActive(HashEntry entry)
+	{
+		return entry != null && entry.active;
+	}
+	
+	private class Iter implements Iterator<Object>
+	{
+		private int cursor;
+		
+		public Iter()
+		{
+			cursor = -1;
+			findNextElm();
+		}
+
+		private void findNextElm()
+		{
+			cursor++;
+			while (cursor < table.length && isActive(table[cursor]))
+			{
+				cursor++;
+			}
+		}
+		
+		@Override
+		public boolean hasNext() {
+			return cursor < table.length;
+		}
+
+		@Override
+		public Object next() {
+			if (!hasNext())
+			{
+				throw new NoSuchElementException();
+			}
+			Object tmp = table[cursor];
+			findNextElm();
+			return tmp;
+		}
+
+		@Override
+		public void remove() {
+			throw new UnsupportedOperationException();
+		}
+	}
+	
+	public void insert(Object item)
+	{
+		int index = findNextIndex(item);
+		if (table[index] == null)
+		{
+			table[index] = new HashEntry(item);
+			size++;
+		}
+		else
+		{
+			table[index].active = true;
+		}
+		if (size >= table.length / 2)
+		{
+			rehash();
+		}
+	}
+	
+	private int hash(Object obj)
+	{
+		return Math.abs(obj.hashCode()) % table.length;
+	}
+	
+	private int findNextIndex(Object obj)
+	{
+		int hash = hash(obj);
+		int i = 0;
+		while (table[hash + i*i] != null && !table[hash + i*i].elm.equals(obj))
+		{
+			i++;
+		}
+		return hash+i*i;
+	}
+	
+	private void rehash()
+	{
+		HashEntry[] tmp = table;
+		table = new HashEntry[nextPrime(table.length*2)];
+		for (HashEntry he : tmp)
+		{
+			if (isActive(he))
+			{
+				insert(he.elm);
+			}
+		}
+	}
+	
+	public void delete(Object item)
+	{
+		int index = findNextIndex(item);
+		if (table[index] != null)
+		{
+			table[index].active = false;
+		}
+	}
+	
+	public Object find(Object item)
+	{
+		int index = findNextIndex(item);
+		if (isActive(table[index]))
+		{
+			return table[index];
+		}
+		return null;
+	}
+	
+	public int elementCount()
+	{
+		int count = 0;
+		for (HashEntry he : table)
+		{
+			if (isActive(he))
+			{
+				count++;
+			}
+		}
+		return count;
+	}
+	
+	public boolean isEmpty()
+	{
+		for (HashEntry he : table)
+		{
+			if (isActive(he))
+			{
+				return false;
+			}
+		}
+		return true;
+	}
+	
+	public void makeEmpty()
+	{
+		table = new HashEntry[table.length];
+	}
+	
+	public void printTable()
+	{
+		for (int i = 0; i < table.length; i++)
+		{
+			System.out.print("["+i+"] ");
+			if (table[i] == null)
+			{
+				System.out.print("empty");
+			}
+			else
+			{
+				System.out.print(table[i].elm);
+				System.out.print(", ");
+				System.out.print(table[i].active? "active":"inactive");
+			}
+			System.out.println();
+		}
+	}
+	
+	@SuppressWarnings("rawtypes")
+	public Iterator iterator()
+	{
+		return new Iter();
+	}
+}

+ 158 - 0
Project4/src/ListPrinter.java

@@ -0,0 +1,158 @@
+/**
+ * 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.Iterator;
+import java.util.Scanner;
+
+public class ListPrinter 
+{
+	/**
+	 * Runs the program.
+	 */
+	public static void main(String[] args) throws FileNotFoundException
+	{
+		//Console input
+		Scanner in = new Scanner(System.in);
+	
+		System.out.println("Salutations. Please enter the file name to be read.");
+
+		//File input
+		Scanner fileIn = new Scanner(new File(in.nextLine()));
+		
+		int N = fileIn.nextInt();
+		HashTable table = new HashTable(N);
+		fileIn.nextLine();
+		
+		while (N-- > 0)
+		{
+			Student newStud = readStudent(fileIn.nextLine());
+			if (newStud != null)
+			{
+				table.insert(newStud);
+			}
+		}
+		fileIn.close();
+		
+		System.out.println("Choose one of the following operations:");
+		System.out.println("a - add the element");
+		System.out.println("d - delete the element");
+		System.out.println("f - find and retrieve the element");
+		System.out.println("n - get the number of elements in the collection");
+		System.out.println("e - check if the collection is empty");
+		System.out.println("k - make the hash table empty");
+		System.out.println("p - print the content of the hash table");
+		System.out.println("o - output the elements of the collection");
+		System.out.println("q - Quit the program");
+		//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 two values representing the student record");
+					String newVal = in.nextLine();
+					Student newStud = readStudent(newVal);
+					if(newStud == null)
+					{
+						System.out.println("Invalid Input");
+					}
+					else
+					{
+						table.insert(newStud);
+					}
+					break;
+					
+				case 'd':
+					System.out.println("Enter ONE value to be deleted.(long, positivevalues)");
+					long id;
+					if(in.hasNextLong() && (id = in.nextLong()) > 0)
+					{
+						Student dummyStudent = new Student(id, "lastName");
+						table.delete(dummyStudent);
+						System.out.println(String.format("Student with id %d has been deleted", id));
+					}
+					else
+					{
+						System.out.println("Invalid Input");
+					}
+					break;
+					
+				case 'f':
+					System.out.println("insert the id number to be found");
+					long findId;
+					if(in.hasNextLong() && (findId = in.nextLong()) > 0)
+					{
+						Student dummyStudent = new Student(findId, "lastName");
+						table.find(dummyStudent);
+						
+						Student findStudent = (Student)table.find(dummyStudent);
+						System.out.println(findStudent != null? String.format("Student with id %d has been found", findId):"Student not found");
+						
+					}
+					else
+					{
+						System.out.println("Invalid Input");
+					}
+					break;
+					
+				case 'p':
+					table.printTable();
+					break;
+					
+				case 'o':
+					@SuppressWarnings("rawtypes")
+					Iterator tableIter = table.iterator();
+					while(tableIter.hasNext())
+					{
+						System.out.println(tableIter.next());
+					}
+					break;
+					
+				case 'q':
+					running = false;
+					System.out.println("Farewell");
+					break;
+				default:
+					System.out.println("Invalid Option.");
+			}
+		}
+		in.close();
+	}
+	
+	private static Student readStudent(String line)
+	{
+		//Defines the format for what a (non-negative) long value looks like
+		final String longFormat = "^\\+?\\d+$";
+		
+		//Breaks the input line into whitespace separated parts
+		String[] inputLineParts = line.split("\\s");
+		if(inputLineParts.length == 2 && inputLineParts[0].matches(longFormat))
+		{
+			return new Student(Long.parseLong(inputLineParts[0]), inputLineParts[1]);
+		}
+		return null;
+	}
+}

+ 58 - 0
Project4/src/Student.java

@@ -0,0 +1,58 @@
+/**
+ * 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
+{
+	/**
+	 * 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;
+	}
+	
+	@Override
+	public boolean equals(Object other)
+	{
+		return other instanceof Student && id == ((Student) other).id;
+	}
+	
+	@Override
+	public int hashCode()
+	{
+		return new Long(id).hashCode();
+	}
+	
+	/**
+	 * 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);
+	}
+
+}