diff --git a/DataLabs/lab4/BagInterface.class b/DataLabs/lab4/BagInterface.class new file mode 100644 index 0000000..6e4b165 Binary files /dev/null and b/DataLabs/lab4/BagInterface.class differ diff --git a/DataLabs/lab4/BagInterface.java b/DataLabs/lab4/BagInterface.java new file mode 100644 index 0000000..75a10e1 --- /dev/null +++ b/DataLabs/lab4/BagInterface.java @@ -0,0 +1,48 @@ +/** + An interface that describes the operations of a bag of objects. + @author Frank M. Carrano + @version 4.0 +*/ +public interface BagInterface +{ + /** Gets the current number of entries in this bag. + @return The integer number of entries currently in the bag. */ + public int getCurrentSize(); + + /** Sees whether this bag is empty. + @return True if the bag is empty, or false if not. */ + public boolean isEmpty(); + + /** Adds a new entry to this bag. + @param newEntry The object to be added as a new entry. + @return True if the addition is successful, or false if not. */ + public boolean add(T newEntry); + + /** Removes one unspecified entry from this bag, if possible. + @return Either the removed entry, if the removal. + was successful, or null. */ + public T remove(); + + /** Removes one occurrence of a given entry from this bag. + @param anEntry The entry to be removed. + @return True if the removal was successful, or false if not. */ + public boolean remove(T anEntry); + + /** Removes all entries from this bag. */ + public void clear(); + + /** Counts the number of times a given entry appears in this bag. + @param anEntry The entry to be counted. + @return The number of times anEntry appears in the bag. */ + public int getFrequencyOf(T anEntry); + + /** Tests whether this bag contains a given entry. + @param anEntry The entry to locate. + @return True if the bag contains anEntry, or false if not. */ + public boolean contains(T anEntry); + + /** Retrieves all entries that are in this bag. + @return A newly allocated array of all the entries in the bag. + Note: If the bag is empty, the returned array is empty. */ + public T[] toArray(); +} // end BagInterface diff --git a/DataLabs/lab4/LinkedBag$Node.class b/DataLabs/lab4/LinkedBag$Node.class new file mode 100644 index 0000000..c65600a Binary files /dev/null and b/DataLabs/lab4/LinkedBag$Node.class differ diff --git a/DataLabs/lab4/LinkedBag.class b/DataLabs/lab4/LinkedBag.class new file mode 100644 index 0000000..23e1171 Binary files /dev/null and b/DataLabs/lab4/LinkedBag.class differ diff --git a/DataLabs/lab4/LinkedBag.java b/DataLabs/lab4/LinkedBag.java new file mode 100644 index 0000000..e015d7e --- /dev/null +++ b/DataLabs/lab4/LinkedBag.java @@ -0,0 +1,132 @@ +/** + A class of bags whose entries are stored in a chain of linked nodes. + The bag is never full. + @author Frank M. Carrano + @version 4.0 +*/ +public final class LinkedBag implements BagInterface +{ + private Node firstNode; // Reference to first node + private int numberOfEntries; + + public LinkedBag() + { + firstNode = null; + numberOfEntries = 0; + } // end default constructor + + /** Adds a new entry to this bag. + @param newEntry The object to be added as a new entry. + @return True. */ + public boolean add(T newEntry) // OutOfMemoryError possible + { + // Add to beginning of chain: + Node newNode = new Node(newEntry); + newNode.next = firstNode; // Make new node reference rest of chain + // (firstNode is null if chain is empty) + firstNode = newNode; // New node is at beginning of chain + numberOfEntries++; + + return true; + } // end add + + /** Retrieves all entries that are in this bag. + @return A newly allocated array of all the entries in this bag. */ + public T[] toArray() + { + // The cast is safe because the new array contains null entries. + @SuppressWarnings("unchecked") + T[] result = (T[])new Object[numberOfEntries]; // Unchecked cast + + int index = 0; + Node currentNode = firstNode; + while ((index < numberOfEntries) && (currentNode != null)) + { + result[index] = currentNode.data; + index++; + currentNode = currentNode.next; + } // end while + + return result; + // Note: The body of this method could consist of one return statement, + // if you call Arrays.copyOf + } // end toArray + + /** Sees whether this bag is empty. + @return True if the bag is empty, or false if not. */ + public boolean isEmpty() + { + return numberOfEntries == 0; + } // end isEmpty + + /** Gets the number of entries currently in this bag. + @return The integer number of entries currently in the bag. */ + public int getCurrentSize() + { + return numberOfEntries; + } // end getCurrentSize + +// STUBS: + + /** Removes one unspecified entry from this bag, if possible. + @return Either the removed entry, if the removal + was successful, or null. */ + public T remove() + { + T top = firstNode.data; + firstNode = firstNode.next; + + numberOfEntries--; + return top; + } // end remove + + /** Removes one occurrence of a given entry from this bag. + @param anEntry The entry to be removed. + @return True if the removal was successful, or false otherwise. */ + public boolean remove(T anEntry) + { + return false; // STUB + } // end remove + + /** Removes all entries from this bag. */ + public void clear() + { + // STUB + } // end clear + + /** Counts the number of times a given entry appears in this bag. + @param anEntry The entry to be counted. + @return The number of times anEntry appears in the bag. */ + public int getFrequencyOf(T anEntry) + { + return 0; // STUB + } // end getFrequencyOf + + /** Tests whether this bag contains a given entry. + @param anEntry The entry to locate. + @return True if the bag contains anEntry, or false otherwise. */ + public boolean contains(T anEntry) + { + return false; // STUB + } // end contains + + private class Node + { + private T data; // Entry in bag + private Node next; // Link to next node + + private Node(T dataPortion) + { + this(dataPortion, null); + } // end constructor + + private Node(T dataPortion, Node nextNode) + { + data = dataPortion; + next = nextNode; + } // end constructor + } // end Node +} // end LinkedBag1 + + + diff --git a/DataLabs/lab4/LinkedBagDemo.java b/DataLabs/lab4/LinkedBagDemo.java new file mode 100644 index 0000000..39f7af6 --- /dev/null +++ b/DataLabs/lab4/LinkedBagDemo.java @@ -0,0 +1,85 @@ +/** A test of the methods add, toArray, isEmpty, and getCurrentSize, + as defined in the first draft of the class LinkedBag. + @author Frank M. Carrano + @version 4.0 +*/ +public class LinkedBagDemo +{ + public static void main(String[] args) + { + System.out.println("Creating an empty bag."); + BagInterface aBag = new LinkedBag<>(); + testIsEmpty(aBag, true); + displayBag(aBag); + + String[] contentsOfBag = {"A", "D", "B", "A", "C", "A", "D"}; + testAdd(aBag, contentsOfBag); + testIsEmpty(aBag, false); + } // end main + + // Tests the method isEmpty. + // Precondition: If the bag is empty, the parameter empty should be true; + // otherwise, it should be false. + private static void testIsEmpty(BagInterface bag, boolean empty) + { + System.out.print("\nTesting isEmpty with "); + if (empty) + System.out.println("an empty bag:"); + else + System.out.println("a bag that is not empty:"); + + System.out.print("isEmpty finds the bag "); + if (empty && bag.isEmpty()) + System.out.println("empty: OK."); + else if (empty) + System.out.println("not empty, but it is: ERROR."); + else if (!empty && bag.isEmpty()) + System.out.println("empty, but it is not empty: ERROR."); + else + System.out.println("not empty: OK."); + } // end testIsEmpty + // Tests the method add. + private static void testAdd(BagInterface aBag, String[] content) + { + System.out.print("Adding the following " + content.length + + " strings to the bag: "); + for (int index = 0; index < content.length; index++) + { + if (aBag.add(content[index])) + System.out.print(content[index] + " "); + else + System.out.print("\nUnable to add " + content[index] + + " to the bag."); + } // end for + System.out.println(); + + displayBag(aBag); + } // end testAdd + + // Tests the method toArray while displaying the bag. + private static void displayBag(BagInterface aBag) + { + System.out.println("The bag contains the following string(s):"); + Object[] bagArray = aBag.toArray(); + for (int index = 0; index < bagArray.length; index++) + { + System.out.print(bagArray[index] + " "); + } // end for + + System.out.println(); + } // end displayBag +} // end LinkedBagDemo1 +/* + Creating an empty bag. + + Testing isEmpty with an empty bag: + isEmpty finds the bag empty: OK. + The bag contains the following string(s): + + Adding the following 7 strings to the bag: A D B A C A D + The bag contains the following string(s): + D A C A B D A + + Testing isEmpty with a bag that is not empty: + isEmpty finds the bag not empty: OK. +*/ diff --git a/DataLabs/lab5/ArrayQueue.java b/DataLabs/lab5/ArrayQueue.java new file mode 100644 index 0000000..057e50f --- /dev/null +++ b/DataLabs/lab5/ArrayQueue.java @@ -0,0 +1,149 @@ +/** + A class that implements the ADT queue by using an expandable + circular array with one unused location. + + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public final class ArrayQueue implements QueueInterface +{ + private T[] queue; // Circular array of queue entries and one unused location + private int frontIndex; + private int backIndex; + private boolean initialized = false; + private static final int DEFAULT_CAPACITY = 50; + private static final int MAX_CAPACITY = 10000; + + public ArrayQueue() + { + this(DEFAULT_CAPACITY); + } // end default constructor + + public ArrayQueue(int initialCapacity) + { + checkCapacity(initialCapacity); + + // The cast is safe because the new array contains null entries + @SuppressWarnings("unchecked") + T[] tempQueue = (T[]) new Object[initialCapacity + 1]; + queue = tempQueue; + frontIndex = 0; + backIndex = initialCapacity; + initialized = true; + } // end constructor + + public void enqueue(T newEntry) + { + checkInitialization(); + ensureCapacity(); + backIndex = (backIndex + 1) % queue.length; + queue[backIndex] = newEntry; + } // end enqueue + + public T getFront() + { + checkInitialization(); + if (isEmpty()) + throw new EmptyQueueException(); + else + return queue[frontIndex]; + } // end getFront + + public T dequeue() + { + checkInitialization(); + if (isEmpty()) + throw new EmptyQueueException(); + else + { + T front = queue[frontIndex]; + queue[frontIndex] = null; + frontIndex = (frontIndex + 1) % queue.length; + return front; + } // end if + } // end dequeue + + // Doubles the size of the array queue if it is full + // Precondition: checkInitialization has been called. + private void ensureCapacity() + { + if (frontIndex == ((backIndex + 2) % queue.length)) // if array is full, + { // double size of array + T[] oldQueue = queue; + int oldSize = oldQueue.length; + int newSize = 2 * oldSize; + checkCapacity(newSize); + + // The cast is safe because the new array contains null entries + @SuppressWarnings("unchecked") + T[] tempQueue = (T[]) new Object[2 * oldSize]; + queue = tempQueue; + for (int index = 0; index < oldSize - 1; index++) + { + queue[index] = oldQueue[frontIndex]; + frontIndex = (frontIndex + 1) % oldSize; + } // end for + + frontIndex = 0; + backIndex = oldSize - 2; + } // end if + } // end ensureCapacity + + public boolean isEmpty() + { + return frontIndex == ((backIndex + 1) % queue.length); + } // end isEmpty + + // Throws an exception if this object is not initialized. + private void checkInitialization() + { + if (!initialized) + { + throw new SecurityException ("ArrayQueue object is not initialized properly."); + } + } + + // Throws an exception if the client requests a capacity that is too large. + private void checkCapacity(int capacity) + { + if (capacity > MAX_CAPACITY) + { + throw new IllegalStateException("Attempt to create a queue " + + "whose capacity exceeds " + + "allowed maximum."); + } + } + + + + // Question 3, Chapter 11 + public void clear() + { + checkInitialization(); + if (!isEmpty()) + { // deallocates only the used portion + for (int index = frontIndex; index != backIndex; index = (index + 1) % queue.length) + { + queue[index] = null; + } + + queue[backIndex] = null; + } + + frontIndex = 0; + backIndex = queue.length - 1; + } + + /* + // Question 4, Chapter 11 + public void clear() + { + while (!isEmpty()) + { + dequeue(); + } + } + */ + +} // end ArrayQueue diff --git a/DataLabs/lab5/EmptyQueueException.java b/DataLabs/lab5/EmptyQueueException.java new file mode 100644 index 0000000..7cf500e --- /dev/null +++ b/DataLabs/lab5/EmptyQueueException.java @@ -0,0 +1,13 @@ +/** A class of runtime exceptions thrown when an attempt is made + to access or remove the front of a queue. @author Frank M. Carrano + */ +public class EmptyQueueException extends RuntimeException { + public EmptyQueueException() { + this(null); + } // end default + + public EmptyQueueException(String message) { + super(message); + } // end constructor + +} // end EmptyQueueException \ No newline at end of file diff --git a/DataLabs/lab5/Lab5.docx b/DataLabs/lab5/Lab5.docx new file mode 100644 index 0000000..9c70f91 Binary files /dev/null and b/DataLabs/lab5/Lab5.docx differ diff --git a/DataLabs/lab5/LinkedQueue.java b/DataLabs/lab5/LinkedQueue.java new file mode 100644 index 0000000..dbf7a21 --- /dev/null +++ b/DataLabs/lab5/LinkedQueue.java @@ -0,0 +1,101 @@ +/** + A class that implements the ADT queue by using a chain of nodes + that has both head and tail references. + + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public final class LinkedQueue implements QueueInterface +{ + private Node firstNode; // References node at front of queue + private Node lastNode; // References node at back of queue + + public LinkedQueue() + { + firstNode = null; + lastNode = null; + } // end default constructor + + public void enqueue(T newEntry) + { + Node newNode = new Node(newEntry, null); + + if (isEmpty()) + firstNode = newNode; + else + lastNode.setNextNode(newNode); + + lastNode = newNode; + } // end enqueue + + public T getFront() + { + if (isEmpty()) + throw new EmptyQueueException(); + else + return firstNode.getData(); + } // end getFront + + public T dequeue() + { + T front = getFront(); // Might throw EmptyQueueException + assert firstNode != null; + firstNode.setData(null); + firstNode = firstNode.getNextNode(); + + if (firstNode == null) + lastNode = null; + + return front; + } // end dequeue + + public boolean isEmpty() + { + return (firstNode == null) && (lastNode == null); + } // end isEmpty + + public void clear() + { + firstNode = null; + lastNode = null; + } // end clear + + private class Node + { + private T data; // Entry in queue + private Node next; // Link to next node + + private Node(T dataPortion) + { + data = dataPortion; + next = null; + } // end constructor + + private Node(T dataPortion, Node linkPortion) + { + data = dataPortion; + next = linkPortion; + } // end constructor + + private T getData() + { + return data; + } // end getData + + private void setData(T newData) + { + data = newData; + } // end setData + + private Node getNextNode() + { + return next; + } // end getNextNode + + private void setNextNode(Node nextNode) + { + next = nextNode; + } // end setNextNode + } // end Node +} // end LinkedQueue diff --git a/DataLabs/lab5/QueueInterface.java b/DataLabs/lab5/QueueInterface.java new file mode 100644 index 0000000..1da6bc5 --- /dev/null +++ b/DataLabs/lab5/QueueInterface.java @@ -0,0 +1,29 @@ +/** + An interface for the ADT queue. + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public interface QueueInterface +{ + /** Adds a new entry to the back of this queue. + @param newEntry An object to be added. */ + public void enqueue(T newEntry); + + /** Removes and returns the entry at the front of this queue. + @return The object at the front of the queue. + @throws EmptyQueueException if the queue is empty before the operation. */ + public T dequeue(); + + /** Retrieves the entry at the front of this queue. + @return The object at the front of the queue. + @throws EmptyQueueException if the queue is empty. */ + public T getFront(); + + /** Detects whether this queue is empty. + @return True if the queue is empty, or false otherwise. */ + public boolean isEmpty(); + + /** Removes all entries from this queue. */ + public void clear(); +} // end QueueInterface diff --git a/DataLabs/lab5/StockLedger.java b/DataLabs/lab5/StockLedger.java new file mode 100644 index 0000000..f47901b --- /dev/null +++ b/DataLabs/lab5/StockLedger.java @@ -0,0 +1,29 @@ +public class StockLedger { + private QueueInterface ledger; + + public StockLedger() { + ledger = new LinkedQueue<>(); + } + + public void buy(int sharesBought, double pricePerShare){ + while(!SharesBought) { + StockPurchase purchase = new StockPurchase(pricePerShare); + ledger.enqueue(purchase); + sharesBought--; + } + } + + public double sell(int sharesSold, double pricePerShare){ + double saleAmount = sharesSold*pricePerShare; + double totalCost = 0; + + while (!sharesSold){ + StockPurchase share = ledger.dequeue(); + double shareCost = share.getCostPerShare(); + totalCost += shareCost; + sharesSold--; + } + + return saleAmount - totalCost; + } +} diff --git a/DataLabs/lab6/ArrayDictionary.java b/DataLabs/lab6/ArrayDictionary.java new file mode 100644 index 0000000..1f474f4 --- /dev/null +++ b/DataLabs/lab6/ArrayDictionary.java @@ -0,0 +1,276 @@ +package dictionary; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + A class that implements the ADT dictionary by using a resizable array. + The dictionary is unsorted and has distinct search keys. + + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public class ArrayDictionary implements DictionaryInterface +{ + protected Entry[] dictionary; // Array of unsorted entries + protected int numberOfEntries; + private boolean initialized = false; + private final static int DEFAULT_CAPACITY = 25; + private static final int MAX_CAPACITY = 10000; + + public ArrayDictionary() + { + this(DEFAULT_CAPACITY); // Call next constructor + } // end default constructor + + public ArrayDictionary(int initialCapacity) + { + checkCapacity(initialCapacity); + // The cast is safe because the new array contains null entries + @SuppressWarnings("unchecked") + Entry[] tempDictionary = (Entry[])new Entry[initialCapacity]; + dictionary = tempDictionary; + numberOfEntries = 0; + initialized = true; + } // end constructor + + public V add(K key, V value) + { + checkInitialization(); + if ((key == null) || (value == null)) + throw new IllegalArgumentException("Cannot add null to a dictionary."); + else + { + V result = null; + int keyIndex = locateIndex(key); + if (keyIndex < numberOfEntries) + { + // Key found, return and replace entry's value + result = dictionary[keyIndex].getValue(); // Get old value + dictionary[keyIndex].setValue(value); // Replace value + } + else // Key not found; add new entry to dictionary + { + // Add at end of array + dictionary[numberOfEntries] = new Entry<>(key, value); + numberOfEntries++; + ensureCapacity(); // Ensure enough room for next add + } // end if + return result; + } // end if + } // end add + + // Returns the array index of the entry that contains key, or + // returns numberOfEntries if no such entry exists. + private int locateIndex(K key) + { + // Sequential search + int index = 0; + while ( (index < numberOfEntries) && !key.equals(dictionary[index].getKey()) ) + index++; + return index; + } // end locateIndex + + public V remove(K key) + { + checkInitialization(); + V result = null; + int keyIndex = locateIndex(key); + if (keyIndex < numberOfEntries) + { + // Key found; remove entry and return its value + result = dictionary[keyIndex].getValue(); + dictionary[keyIndex] = dictionary[numberOfEntries - 1]; + dictionary[numberOfEntries - 1] = null; + numberOfEntries--; + } // end if + // Else result is null + return result; + } // end remove + + public V getValue(K key) + { + checkInitialization(); + V result = null; + int keyIndex = locateIndex(key); + if (keyIndex < numberOfEntries) + { + result = dictionary[keyIndex].getValue(); // Key found; return value + } // end if + return result; + } // end getValue + + public boolean contains(K key) + { + return getValue(key) != null; + } // end contains + + public boolean isEmpty() + { + return numberOfEntries == 0; + } // end isEmpty + + public int getSize() + { + return numberOfEntries; + } // end getSize + + public final void clear() + { + checkInitialization(); + // Clear entries but retain array; no need to create a new array + for (int index = 0; index < numberOfEntries; index++) + dictionary[index] = null; + numberOfEntries = 0; + } // end clear + + protected void ensureCapacity() + { + if (numberOfEntries >= dictionary.length) + { + int newCapacity = 2 * dictionary.length; + checkCapacity(newCapacity); + dictionary = Arrays.copyOf(dictionary, newCapacity); + } // end if + } // end ensureCapacity + + // Throws an exception if this object is not initialized. + protected void checkInitialization() + { + if (!initialized) + { + throw new SecurityException ("ArrayDictionary object is not initialized properly."); + } + } + + // Throws an exception if the client requests a capacity that is too large. + protected void checkCapacity(int capacity) + { + if (capacity > MAX_CAPACITY) + { + throw new IllegalStateException("Attempt to create a HashedDictionary " + + "whose capacity exceeds " + + "allowed maximum."); + } + } + + + public Iterator getKeyIterator() + { + return new KeyIterator(); + } // end getKeyIterator + + public Iterator getValueIterator() + { + return new ValueIterator(); + } // end getValueIterator + + protected class Entry + { + private S key; + private T value; + + protected Entry(S searchKey, T dataValue) + { + key = searchKey; + value = dataValue; + } // end constructor + + protected S getKey() + { + return key; + } // end getKey + + protected T getValue() + { + return value; + } // end getValue + + protected void setValue(T dataValue) + { + value = dataValue; + } // end setValue + } // end Entry + + + + // Since iterators implement Iterator, methods must be public. + // Same as SortedArrayDictionary. + + private class KeyIterator implements Iterator + { + private int currentIndex; + + private KeyIterator() + { + currentIndex = 0; + } // end default constructor + + public boolean hasNext() + { + return currentIndex < numberOfEntries; + } // end hasNext + + public K next() + { + K result = null; + if (hasNext()) + { + Entry currentEntry = dictionary[currentIndex]; + result = currentEntry.getKey(); + currentIndex++; + } + else + { + throw new NoSuchElementException(); + } // end if + return result; + } // end next + + public void remove() + { + throw new UnsupportedOperationException(); + } // end remove + + } // end KeyIterator + + private class ValueIterator implements Iterator + { + private int currentIndex; + + private ValueIterator() + { + currentIndex = 0; + } // end default constructor + + public boolean hasNext() + { + return currentIndex < numberOfEntries; + } // end hasNext + + public V next() + { + V result = null; + if (hasNext()) + { + Entry currentEntry = dictionary[currentIndex]; + result = currentEntry.getValue(); + currentIndex++; + } + else + { + throw new NoSuchElementException(); + } // end if + return result; + } // end next + + public void remove() + { + throw new UnsupportedOperationException(); + } // end remove + + } // end getValueIterator + +} // end dictionary.ArrayDictionary diff --git a/DataLabs/lab6/DictionaryInterface.java b/DataLabs/lab6/DictionaryInterface.java new file mode 100644 index 0000000..24d59c5 --- /dev/null +++ b/DataLabs/lab6/DictionaryInterface.java @@ -0,0 +1,60 @@ +package dictionary; + +import java.util.Iterator; +/** + An interface for a dictionary with distinct search keys. + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public interface DictionaryInterface +{ + /** Adds a new entry to this dictionary. If the given search key already + exists in the dictionary, replaces the corresponding value. + @param key An object search key of the new entry. + @param value An object associated with the search key. + @return Either null if the new entry was added to the dictionary + or the value that was associated with key if that value + was replaced. */ + public V add(K key, V value); + + /** Removes a specific entry from this dictionary. + @param key An object search key of the entry to be removed. + @return Either the value that was associated with the search key + or null if no such object exists. */ + public V remove(K key); + + /** Retrieves from this dictionary the value associated with a given + search key. + @param key An object search key of the entry to be retrieved. + @return Either the value that is associated with the search key + or null if no such object exists. */ + public V getValue(K key); + + /** Sees whether a specific entry is in this dictionary. + @param key An object search key of the desired entry. + @return True if key is associated with an entry in the dictionary. */ + public boolean contains(K key); + + /** Creates an iterator that traverses all search keys in this dictionary. + @return An iterator that provides sequential access to the search + keys in the dictionary. */ + public Iterator getKeyIterator(); + + /** Creates an iterator that traverses all values in this dictionary. + @return An iterator that provides sequential access to the values + in this dictionary. */ + public Iterator getValueIterator(); + + /** Sees whether this dictionary is empty. + @return True if the dictionary is empty. */ + public boolean isEmpty(); + + /** Gets the size of this dictionary. + @return The number of entries (key-value pairs) currently + in the dictionary. */ + public int getSize(); + + /** Removes all entries from this dictionary. */ + public void clear(); +} // end dictionary.DictionaryInterface \ No newline at end of file diff --git a/DataLabs/lab6/Lab6.docx b/DataLabs/lab6/Lab6.docx new file mode 100644 index 0000000..da68680 Binary files /dev/null and b/DataLabs/lab6/Lab6.docx differ diff --git a/DataLabs/lab6/Name.java b/DataLabs/lab6/Name.java new file mode 100644 index 0000000..845edea --- /dev/null +++ b/DataLabs/lab6/Name.java @@ -0,0 +1,85 @@ +package dictionary; + +/** + A class that represents a person's name. + + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public class Name implements Comparable { + private String first; // First name + private String last; // Last name + + public Name() + { + } // end default constructor + + public Name(String firstName, String lastName) + { + first = firstName; + last = lastName; + } // end constructor + + public void setName(String firstName, String lastName) + { + setFirst(firstName); + setLast(lastName); + } // end setName + + public String getName() + { + return toString(); + } // end getName + + public void setFirst(String firstName) + { + first = firstName; + } // end setFirst + + public String getFirst() + { + return first; + } // end getFirst + + public void setLast(String lastName) + { + last = lastName; + } // end setLast + + public String getLast() + { + return last; + } // end getLast + + public void giveLastNameTo(Name aName) + { + aName.setLast(last); + } // end giveLastNameTo + + public String toString() + { + return first + " " + last; + } // end toString + + @Override + public int compareTo(Name name) { + int lastCmp = last.compareTo(name.last); + return (lastCmp != 0 ? lastCmp : first.compareTo(name.first)); + } + + @Override + public boolean equals(Object name) { + // If the object is compared with itself then return true + if (name == this) { + return true; + } + /* Check if o is an instance of Complex or not + "null instanceof [type]" also returns false */ + if (!(name instanceof Name)) { + return false; + } + + return compareTo( (Name)name ) == 0; + } +} // end Name \ No newline at end of file diff --git a/DataLabs/lab6/SortedArrayDictionary.java b/DataLabs/lab6/SortedArrayDictionary.java new file mode 100644 index 0000000..96759b0 --- /dev/null +++ b/DataLabs/lab6/SortedArrayDictionary.java @@ -0,0 +1,104 @@ +package dictionary; + +/** + A class that implements the ADT dictionary by using a resizable sorted array. + The dictionary has distinct search keys. + + @author Frank M. Carrano + @author Timothy M. Henry + @version 4.0 +*/ +public class SortedArrayDictionary, V> + extends ArrayDictionary implements DictionaryInterface +{ + /* < Constructors analogous to those in Listing 20-1. > + . . . */ + public SortedArrayDictionary() + { + super(); // Call next constructor + } // end default constructor + + public SortedArrayDictionary(int initialCapacity) + { + super(initialCapacity); + } // end constructor + + + + + // 20.11 + /** Precondition: key and value are not null. */ + public V add(K key, V value) + { + checkInitialization(); + if ((key == null) || (value == null)) + throw new IllegalArgumentException("Cannot add null to a dictionary."); + else + { + V result = null; + int keyIndex = locateIndex(key); + if ( (keyIndex < numberOfEntries) && + key.equals(dictionary[keyIndex].getKey()) ) + { + // Key found, return and replace entry's value + result = dictionary[keyIndex].getValue(); // Old value + dictionary[keyIndex].setValue(value); // Replace value + } + else // Key not found; add new entry to dictionary + { + makeRoom(keyIndex); // Make room for new entry + dictionary[keyIndex] = new Entry(key, value); // Insert new entry in array + numberOfEntries++; + ensureCapacity(); // Ensure enough room for next add + } // end if + + return result; + } // end if + } // end add + + /* < Implementations of other methods in dictionary.DictionaryInterface. > + . . . */ + + + + // 20.12 + // Returns the index of either the entry that contains key or + // the location that should contain key, if no such entry exists. + private int locateIndex(K key) + { + // Search until you either find an entry containing key or + // pass the point where it should be + int index = 0; + while ( (index < numberOfEntries) && + key.compareTo(dictionary[index].getKey()) > 0 ) + { + index++; + } // end while + + return index; + } // end locateIndex + + + // Makes room for a new entry at a given index by shifting + // array entries towards the end of the array. + // Precondition: keyIndex is valid; list length is old length. + private void makeRoom(int keyIndex) + { + assert (keyIndex >= 1) && (keyIndex <= numberOfEntries + 1); + int newIndex = keyIndex; + int lastIndex = numberOfEntries; + // Move each entry to next higher index, starting at end of + // dictionary and continuing until the entry at newIndex is moved + for (int index = lastIndex; index >= newIndex; index--) + dictionary[index + 1] = dictionary[index]; + } // end makeRoom + + + // Removes an entry at a given index by shifting array + // entries toward the entry to be removed. + private void removeArrayEntry(int keyIndex) + { + // . . . To be implemented + } // end removeArrayEntry + +} // end dictionary.SortedArrayDictionary \ No newline at end of file diff --git a/DataLabs/lab6/TelephoneDirectory.java b/DataLabs/lab6/TelephoneDirectory.java new file mode 100644 index 0000000..d21ebd0 --- /dev/null +++ b/DataLabs/lab6/TelephoneDirectory.java @@ -0,0 +1,13 @@ +import java.util.Iterator; +import java.util.Scanner; + +public class TelephoneDirectory +{ + private DictionaryInterface phoneBook; + + public TelephoneDirectory() + { + //phoneBook = new SortedArrayDictionary<>(); + phoneBook = new SortedLinkedDictionary<>(); //Currently Linked Directory + } // end default constructor + diff --git a/DataLabs/lab6/data.txt b/DataLabs/lab6/data.txt new file mode 100644 index 0000000..345b4e6 --- /dev/null +++ b/DataLabs/lab6/data.txt @@ -0,0 +1,5 @@ +Ali Koc 1234 +Mehmet Sezgin 4567 +Ayse Kahraman 8765 +Ela Bekir 324242 +Mehmet Sezgin 1111 \ No newline at end of file diff --git a/test/ListInterface.java b/test/ListInterface.java new file mode 100644 index 0000000..882d4c2 --- /dev/null +++ b/test/ListInterface.java @@ -0,0 +1,21 @@ +public interface ListInterface{ + public void add(T newEntry); + + public void add(int newPosition, T newEntry); + + public T remove(int givenPosition); + + public void clear(); + + public T replace(int givenPosition, T newEntry); + + public T getEntry(int givenPosition); + + public T[] toArray(); + + public boolean contains(T anEntry); + + public int getLenght(); + + public boolean isEmpty(); +} diff --git a/test/Llist.java b/test/Llist.java new file mode 100644 index 0000000..3f3f617 --- /dev/null +++ b/test/Llist.java @@ -0,0 +1,122 @@ +public class LList implements ListInterface{ + +private Node firstNode; +private int numOfEntries; + + public LList () { + initializeDataFields(); + } + + public void clear () { + initializeDataFields(); + } + + public void add (T newEntry) { + Node newNode = new Node(newEntry); + if (isEmpty) { + firstNode = newNode; + } else { + lastNode = getNodeAt(numOfEntries); + lastNode.setNextNode(newNode); + } + numOfEntries++; + } + + public void add (int newPos, T newEntry) { + if((newPos < numOfEntries) && (newPos > 0)) { + Node newNode = new Node(newEntry); + if (newPos == 1) { + newNode.setNextNode(firstNode); + firstNode = newNode; + } else { + Node nodeBefore = getNodeAt(newPos - 1); + Node nodeAfter = nodeBefore.getNextNode(); + newNode.setNextNode(nodeAfter); + nodeBefore.setNextNode(newNode); + } + numOfEntries++; + } else { + throw new e("Nope"); + } + } + + public boolean isEmpty(){ + return ((numOfEntries > 0)); + } + + public T[] toArray () { + @SuppressWarnings("unchecked") + T[] result = (T[])new Object[numOfEntries]; + Node currentNode = firstNode; + for (int i = 0; i < numOfEntries; i++) { + result[i] = currentNode.getData(); + currentNode = currentNode.getNextNode(); + } + return result; + } + + public T remove (int givenPos) { + T result = null; + if (givenPos <= numOfEntries && givenPos > 0) { + if (!isEmpty()) { + if (givenPos == 1) { + result = firstNode.getData(); + firstNode = firstNode.getNextNode(); + } else { + Node nodeBefore = getNodeAt(givenPos - 1); + Node nodeToRemove = nodeBefore.getNextNode(); + result = nodeToRemove.getData(); + Node nodeAfter = nodeToRemove.getNextNode(); + nodeBefore.setNextNode(nodeAfter); + } + numOfEntries--; + return result; + } else { + throw new e("NOOO"); + } + } + } + + public T replace (int givenPos, T newEntry) { + if(givenPos > 0 && givenPos <= numOfEntries) { + Node desiredNode = getNodeAt(givenPos); + T originalEntry = desiredNode.getData(); + desiredNode.setData(newEntry); + return originalEntry; + } else { + throw new e("NOOOOOO"); + } + } + +// Start from node + + private class Node { + private T data; + private Node next; + + private Node (T dataPortion) { + this(dataPortion, null); + } + + private Node (T dataPortion, Node nextNode) { + data = dataPortion; + next = nextNode; + } + + private T getData () { + return data; + } + + private void setData (T newData) { + data = newData; + } + + private Node getNextNode () { + return next; + } + + private Node setNextNode (Node nextNode) { + next = NextNode; + } + } +}