diff --git a/.gitignore b/.gitignore index 524f096..2070218 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* replay_pid* +.DS_Store diff --git a/OLD!/Homework 4/Part1_Stack.java b/OLD!/Homework 4/Part1_Stack.java new file mode 100644 index 0000000..5473dcf --- /dev/null +++ b/OLD!/Homework 4/Part1_Stack.java @@ -0,0 +1,48 @@ +// Part1_Stack.java + +import java.util.EmptyStackException; //importing the EmptyStackException class from the Java util package +import java.util.Stack; //I will use the built in Java collections framework for this assignment + +public class Part1_Stack { //new class for the + + public static void main(String[] args) { //my main method that uses an array of strings to create a stack of integers + // Create a Stack instance + Stack stack = new Stack<>(); + + // Test push() method + stack.push(10); //pushing the integer 10 onto the stack + stack.push(20); //now pushing 20 + stack.push(30); //pushing 30 + + // Test peek() method + System.out.println("Top element (peek): " + stack.peek()); //should print 30 + System.out.println("Stack after pop: " + stack); // [10, 20] + + // Test pop() method + System.out.println("Popped element: " + stack.pop()); //this will remove the top element, 30, and print it + + // Test empty() method + System.out.println("Is stack empty? " + stack.empty()); //this should print false + + // Test pop() until stack is empty + stack.pop(); // Removes 20 + stack.pop(); // Removes 10 + System.out.println("Is stack empty after popping all elements? " + stack.empty()); // true because the stack is empty now + + // Edge case: Trying to pop from an empty stack (will throw EmptyStackException) + try { + stack.pop(); // This should cause an exception + } catch (EmptyStackException e) { + System.out.println("Exception caught: " + e); // Expected behavior. + } + // Additional test cases: + // Test pushing duplicate values + stack.push(40); + stack.push(40); + System.out.println("Stack after pushing duplicate values: " + stack); // [40, 40] + + // Test multiple peek() calls (peek should not remove elements) + System.out.println("Peek 1: " + stack.peek()); // should be 40 + System.out.println("Peek 2: " + stack.peek()); // still 40, not removed, unlike pop + } + } diff --git a/OLD!/Homework 4/Part2_Queue.java b/OLD!/Homework 4/Part2_Queue.java new file mode 100644 index 0000000..4b50a23 --- /dev/null +++ b/OLD!/Homework 4/Part2_Queue.java @@ -0,0 +1,58 @@ +import java.util.LinkedList; +import java.util.Queue; +import java.util.NoSuchElementException; + +public class Part2_Queue { + public static void main(String[] args) { + // Create a Queue instance using LinkedList array implementation + Queue queue = new LinkedList<>(); + + // Test offer() method (adds elements) + System.out.println("Testing offer() method:"); + queue.offer("First"); + queue.offer("Second"); + queue.offer("Third"); + System.out.println("Queue after offers: " + queue); // [First, Second, Third] + + // Test peek() method + System.out.println("\nTesting peek() method:"); + System.out.println("Front element (peek): " + queue.peek()); // Should be "First" + System.out.println("Queue after peek: " + queue); // Should be the same because its just peek + + // Test poll() method + System.out.println("\nTesting poll() method:"); + System.out.println("Removed element: " + queue.poll()); // Removes and returns "First" + System.out.println("Queue after poll: " + queue); // [Second, Third] + + // Test element() method + System.out.println("\nTesting element() method:"); + System.out.println("Front element: " + queue.element()); // Should be "Second" + + // Test size and isEmpty + System.out.println("\nTesting size and isEmpty:"); + System.out.println("Queue size: " + queue.size()); + System.out.println("Is queue empty? " + queue.isEmpty()); + + // Clear the queue + queue.clear(); + System.out.println("\nQueue after clear(): " + queue); + + // Test edge cases + System.out.println("\nTesting edge cases:"); + System.out.println("Poll from empty queue: " + queue.poll()); // Should return null + + try { + queue.element(); // Should throw exception + } catch (NoSuchElementException e) { + System.out.println("Exception caught when calling element() on empty queue: " + e); + } + + // Test adding null element to the queue to see if it throws an exception or not + try { + queue.offer(null); + System.out.println("Null element added successfully"); + } catch (NullPointerException e) { + System.out.println("Queue doesn't accept null elements"); + } + } +} \ No newline at end of file diff --git a/OLD!/Homework 4/Part3_List.java b/OLD!/Homework 4/Part3_List.java new file mode 100644 index 0000000..0a3dd31 --- /dev/null +++ b/OLD!/Homework 4/Part3_List.java @@ -0,0 +1,77 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Iterator; + +public class Part3_List { + public static void main(String[] args) { + // Create an ArrayList instance + List list = new ArrayList<>(); + + // Test add() method + System.out.println("Testing add() method:"); + list.add(10); //add element 10 to the list + list.add(20); //add 20, list should now be [10, 20] + list.add(30); //add 30, list should now be [10, 20, 30] + System.out.println("List after adds: " + list); //should print [10, 20, 30] + + // Test add() at specific index + System.out.println("\nTesting add(index, element):"); + list.add(1, 15); //add element 15 at the index 1 + System.out.println("List after adding 15 at index 1: " + list); //[10, 15, 20, 30] + + // Test get() method + System.out.println("\nTesting get() method:"); + System.out.println("Element at index 1: " + list.get(1)); //should print 15 as we just set + + // Test set() method + System.out.println("\nTesting set() method:"); + list.set(2, 25); // Set index 2 to 25 + System.out.println("List after setting index 2 to 25: " + list); //should print [10, 15, 25, 30] + + // Test remove() methods + System.out.println("\nTesting remove() methods:"); + list.remove(1); // Remove by index //should remove 15 + System.out.println("List after removing index 1: " + list); + list.remove(Integer.valueOf(30)); // Remove by value + System.out.println("List after removing value 30: " + list); + + // Test contains() method + System.out.println("\nTesting contains() method:"); + System.out.println("Contains 25? " + list.contains(25)); //should print true + System.out.println("Contains 15? " + list.contains(15)); //should print false, as we just removed it + + // Test indexOf() method + System.out.println("\nTesting indexOf() method:"); + System.out.println("Index of 25: " + list.indexOf(25)); //should print 2 + System.out.println("Index of 99 (not in list): " + list.indexOf(99));//should print -1 and not null (no exception either) + + // Test iterator + System.out.println("\nTesting iterator:"); + Iterator iterator = list.iterator(); // Create an iterator we will use to iterate through the list + System.out.print("Iterating through list: "); + while (iterator.hasNext()) { // While there are more elements in the list + System.out.print(iterator.next() + " "); // Print the next element + } + System.out.println(); + + // Test subList + list.add(35); // Add elemenet 35 to the list + list.add(40); // Add element 40 to the list + System.out.println("\nTesting subList:"); // Print the subList from index 1 to 3 + List subList = list.subList(1, 3); // Gets a subList from index 1 to 3 + System.out.println("SubList from index 1 to 3: " + subList); + + // Test edge cases + System.out.println("\nTesting edge cases:"); + try { + list.get(list.size()); // Should throw IndexOutOfBoundsException + } catch (IndexOutOfBoundsException e) { + System.out.println("Exception caught when accessing invalid index: " + e); + } + + // Test clear() and isEmpty() + System.out.println("\nTesting clear() and isEmpty():"); + list.clear(); + System.out.println("Is list empty after clear? " + list.isEmpty()); + } +} \ No newline at end of file diff --git a/OLD!/Homework 4/Part4_Map.java b/OLD!/Homework 4/Part4_Map.java new file mode 100644 index 0000000..0f96475 --- /dev/null +++ b/OLD!/Homework 4/Part4_Map.java @@ -0,0 +1,72 @@ +import java.util.HashMap; +import java.util.Map; + +public class Part4_Map { + public static void main(String[] args) { + // Create a HashMap instance + Map map = new HashMap<>(); + + // Test put() method + System.out.println("Testing put() method:"); + map.put("One", 1); // Add key "One" with value 1 + map.put("Two", 2); // Add key "Two" with value 2 + map.put("Three", 3); // Add key "Three" with value 3 + System.out.println("Map after puts: " + map); // Should print {One=1, Two=2, Three=3} + + // Test get() method + System.out.println("\nTesting get() method:"); + System.out.println("Value for key 'Two': " + map.get("Two")); // Should print 2 + System.out.println("Value for non-existent key: " + map.get("Four")); // Should print null because the key doesn't exist + + // Test getOrDefault() + System.out.println("\nTesting getOrDefault() method:"); + System.out.println("Value for 'Four' with default 0: " + map.getOrDefault("Four", 0)); // Returns 0 instead of null + + // Test containsKey() and containsValue() + System.out.println("\nTesting containsKey() and containsValue():"); + System.out.println("Contains key 'One'? " + map.containsKey("One")); // Should print true + System.out.println("Contains value 2? " + map.containsValue(2)); // Should print true + + // Test put() with existing key (replacement) + System.out.println("\nTesting put() with existing key:"); + Integer oldValue = map.put("One", 100); // Replace value for key "One", oldValue will be 1 + System.out.println("Old value: " + oldValue); // Should print 1 + System.out.println("Map after replacement: " + map); // Should show "One"=100 + + // Test putIfAbsent() + System.out.println("\nTesting putIfAbsent():"); + map.putIfAbsent("One", 1); // Won't change anything as key exists + map.putIfAbsent("Four", 4); // Will add new entry as key doesn't exist + System.out.println("Map after putIfAbsent: " + map); // Should show new "Four"=4 entry + + // Test keySet(), values(), and entrySet() + System.out.println("\nTesting collection views:"); + System.out.println("Keys: " + map.keySet()); // Shows all keys in the map + System.out.println("Values: " + map.values()); // Shows all values in the map + System.out.println("Entries: " + map.entrySet()); // Shows all key-value pairs + + // Test remove() methods + System.out.println("\nTesting remove() methods:"); + map.remove("Two"); // Simple remove by key + System.out.println("Map after removing 'Two': " + map); + boolean removed = map.remove("Three", 3); // Conditional remove - only removes if value matches + System.out.println("Was 'Three' removed? " + removed); // Should print true + System.out.println("Map after conditional remove: " + map); + + // Test compute methods + System.out.println("\nTesting compute methods:"); + map.compute("One", (k, v) -> v + 1); // Increment value of "One" by 1 + System.out.println("Map after compute: " + map); + + map.computeIfPresent("Four", (k, v) -> v * 2); // Double the value of "Four" if present + System.out.println("Map after computeIfPresent: " + map); + + map.computeIfAbsent("Five", k -> 5); // Add "Five"=5 only if key doesn't exist + System.out.println("Map after computeIfAbsent: " + map); + + // Test clear() and isEmpty() + System.out.println("\nTesting clear() and isEmpty():"); + map.clear(); // Remove all entries from map + System.out.println("Is map empty after clear? " + map.isEmpty()); // Should print true + } +} \ No newline at end of file diff --git a/OLD!/Homework 4/Part5_Set.java b/OLD!/Homework 4/Part5_Set.java new file mode 100644 index 0000000..88b144a --- /dev/null +++ b/OLD!/Homework 4/Part5_Set.java @@ -0,0 +1,84 @@ +import java.util.HashSet; +import java.util.Set; + +public class Part5_Set { + public static void main(String[] args) { + // Create a HashSet instance + Set set = new HashSet<>(); + + // Test add() method with fruit because i am hungry + System.out.println("Testing add() method:"); + set.add("Apple"); // Add first element + set.add("Banana"); // Add second element + set.add("Cherry"); // Add third element + System.out.println("Set after adds: " + set); // Order may vary as HashSet doesn't maintain insertion order + + // Test adding duplicate element + System.out.println("\nTesting duplicate addition:"); + boolean added = set.add("Apple"); // Try to add "Apple" again + System.out.println("Was duplicate 'Apple' added? " + added); // Should print false + System.out.println("Set after attempting to add duplicate: " + set); // Should be unchanged + + // Test contains() method + System.out.println("\nTesting contains() method:"); + System.out.println("Contains 'Apple'? " + set.contains("Apple")); // Should print true + System.out.println("Contains 'Orange'? " + set.contains("Orange")); // Should print false + + // Test size() method + System.out.println("\nTesting size() method:"); + System.out.println("Set size: " + set.size()); // Should print 3 + + // Test remove() method + System.out.println("\nTesting remove() method:"); + boolean removed = set.remove("Banana"); // Remove "Banana" from set + System.out.println("Was 'Banana' removed? " + removed); // Should print true + System.out.println("Set after removal: " + set); // Should show set without "Banana" + + // Test iteration + System.out.println("\nTesting iteration:"); + System.out.print("Iterating through set: "); + for (String element : set) { // Using enhanced for loop to iterate + System.out.print(element + " "); // Print each element + } + System.out.println(); + + // Test addAll() for union + Set otherSet = new HashSet<>(); // Create another set for testing set operations + otherSet.add("Cherry"); // Add some elements, including one that's already in our first set + otherSet.add("Date"); // Add unique element + otherSet.add("Elderberry"); // Add another unique element + System.out.println("\nTesting addAll() (union):"); + set.addAll(otherSet); // Combine both sets + System.out.println("Set after union: " + set); // Should show all unique elements from both sets + + // Test retainAll() for intersection + Set intersectSet = new HashSet<>(); + intersectSet.add("Cherry"); // Add element that exists in main set + intersectSet.add("Date"); // Add element that exists in main set + intersectSet.add("Fig"); // Add element that doesn't exist in main set + System.out.println("\nTesting retainAll() (intersection):"); + set.retainAll(intersectSet); // Keep only elements that exist in both sets + System.out.println("Set after intersection: " + set); // Should only show common elements + + // Test removeAll() for difference + Set removeSet = new HashSet<>(); + removeSet.add("Cherry"); // Add element to remove + System.out.println("\nTesting removeAll() (difference):"); + set.removeAll(removeSet); // Remove all elements that exist in removeSet + System.out.println("Set after difference: " + set); // Should show remaining elements + + // Test clear() and isEmpty() + System.out.println("\nTesting clear() and isEmpty():"); + set.clear(); // Remove all elements + System.out.println("Is set empty after clear? " + set.isEmpty()); // Should print true + + // Test null handling + System.out.println("\nTesting null handling:"); + try { + set.add(null); // Try to add null value + System.out.println("Null element added successfully"); // Will print if HashSet accepts null + } catch (NullPointerException e) { + System.out.println("Set doesn't accept null elements"); // Will print if HashSet rejects null + } + } +} \ No newline at end of file diff --git a/OLD!/Homework 5/HashMapImplementation.java b/OLD!/Homework 5/HashMapImplementation.java new file mode 100644 index 0000000..1452162 --- /dev/null +++ b/OLD!/Homework 5/HashMapImplementation.java @@ -0,0 +1,81 @@ +import java.util.HashMap; +import java.util.Map; + +public class HashMapImplementation { + // creating a hashmap object to store the word count, private so it can only be modified by this class + private HashMap wordCount; + + // here is the constructor + public HashMapImplementation() { + wordCount = new HashMap<>(); + } + + // main method + public static void main(String[] args) { + HashMapImplementation counter = new HashMapImplementation(); + // Example usage with a longer test case + String text = "this is a test this is only a test but this is also a longer test to show how the hashmap handles more words. test test test haha"; + counter.processText(text); + counter.displayCounts(); + + // demonstrating individual word lookup + System.out.println("\nCount for word 'test': " + counter.get("test")); + System.out.println("Total unique words: " + counter.size()); + } + + // Required methods from the assignment + public void put(String word) { + // this will put the word in the hashmap, if it is already there, increment the count by 1 + // using getOrDefault to handle the case when the word is not in the map yet + wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); + } + + public Integer get(String word) { + // returns the count of the word, or null if word doesn't exist + return wordCount.get(word); + } + + public int size() { + // returns the number of unique words + return wordCount.size(); + } + + // helper method to process entire text at once instead of word by word + public void processText(String text) { + // split the text into words using space as delimiter as specified in assignment + String[] words = text.split(" "); + // process each word using our put method + for (String word : words) { + put(word); + } + } + + // helper method to display the counts of all words + public void displayCounts() { + // using Map.Entry to iterate over both keys and values efficiently + System.out.println("Word Counts:"); + System.out.println("------------"); + for (Map.Entry entry : wordCount.entrySet()) { + // formatting output to align counts + System.out.printf("%-20s: %d%n", entry.getKey(), entry.getValue()); + } + } + + // helper method to check if hashmap is empty + public boolean isEmpty() { + // returns true if no words have been added yet + return wordCount.isEmpty(); + } + + // helper method to clear all counts + public void clear() { + // removes all entries from the hashmap + wordCount.clear(); + } + + // helper method to check if a word exists in our counts + public boolean containsWord(String word) { + // returns true if the word has been counted at least once + return wordCount.containsKey(word); + } +} \ No newline at end of file diff --git a/OLD!/Homework 5/LinearProbingImplementation.java b/OLD!/Homework 5/LinearProbingImplementation.java new file mode 100644 index 0000000..703a934 --- /dev/null +++ b/OLD!/Homework 5/LinearProbingImplementation.java @@ -0,0 +1,129 @@ +public class LinearProbingImplementation { + // size of hash table, using prime number slightly over 1000 as required in assignment + private static final int TABLE_SIZE = 1009; + // array to store the word entries, private so it can only be modified by this class + private WordEntry[] table; + // keeps track of number of unique words + private int size; + + // private inner class to store word-count pairs + private static class WordEntry { + String word; + int count; + + // constructor initializes a new word with count of 1 + WordEntry(String word) { + this.word = word; + this.count = 1; + } + } + + // constructor to initialize the hash table + public LinearProbingImplementation() { + table = new WordEntry[TABLE_SIZE]; + size = 0; + } + + // hash function using first letter and length to reduce collisions + private int hash(String word) { + // handle edge cases of null or empty strings + if (word == null || word.isEmpty()) return 0; + // using first letter and word length with multiplication to better distribute values + return ((word.charAt(0) - 'a') * 31 + word.length()) % TABLE_SIZE; + } + + // adds a word to the hash table or increments its count if already present + public void put(String word) { + // check if table is full before adding + if (size >= TABLE_SIZE) { + throw new IllegalStateException("Hash table is full"); + } + + // get initial index for this word + int index = hash(word); + + // linear probing: keep checking next slot until we find an empty spot or the word + while (table[index] != null) { + // if word found, increment count and return + if (table[index].word.equals(word)) { + table[index].count++; + return; + } + // move to next slot (wrapping around to start if needed) + index = (index + 1) % TABLE_SIZE; + } + + // found empty slot, insert new entry + table[index] = new WordEntry(word); + size++; // increment total unique words counter + } + + // returns the count of a given word, or null if word doesn't exist + public Integer get(String word) { + // get initial index for this word + int index = hash(word); + + // save starting point to detect if we've checked entire table + int startIndex = index; + + // keep checking slots until we find the word or an empty slot + while (table[index] != null) { + // if word found, return its count + if (table[index].word.equals(word)) { + return table[index].count; + } + // move to next slot + index = (index + 1) % TABLE_SIZE; + // break if we've wrapped around to where we started + if (index == startIndex) break; + } + + // word not found in table + return null; + } + + // returns the number of unique words in the hash table + public int size() { + return size; + } + + // helper method to process entire text at once instead of word by word + public void processText(String text) { + // split the text into words using space as delimiter as specified in assignment + String[] words = text.split(" "); + // process each word using our put method + for (String word : words) { + put(word); + } + } + + // helper method to display the counts of all words + public void displayCounts() { + System.out.println("Word Counts (Linear Probing):"); + System.out.println("---------------------------"); + // iterate through the entire table + for (WordEntry entry : table) { + // only display non-null entries (words that were added) + if (entry != null) { + // formatting output to align counts + System.out.printf("%-20s: %d%n", entry.word, entry.count); + } + } + } + + // main method to test the implementation + public static void main(String[] args) { + // create new instance of our hash table + LinearProbingImplementation counter = new LinearProbingImplementation(); + // test string with multiple repeated words to demonstrate counting + String text = "this is a slightly new test testing this program and once more this is only a test but this is also a longer test to show how linear probing handles more words than the other implementations. test test test haha test"; + // process the test text + counter.processText(text); + // display all word counts + counter.displayCounts(); + + // demonstrate individual word lookup + System.out.println("\nCount for word 'test': " + counter.get("test")); + System.out.println("Total unique words: " + counter.size()); + } +} \ No newline at end of file diff --git a/OLD!/Homework 5/SeparateChainingImplementation.java b/OLD!/Homework 5/SeparateChainingImplementation.java new file mode 100644 index 0000000..64ce531 --- /dev/null +++ b/OLD!/Homework 5/SeparateChainingImplementation.java @@ -0,0 +1,122 @@ +import java.util.LinkedList; + +// Helper class to store word and its count together +class WordEntry { + String word; + int count; + + // constructor initializes a new word with count of 1 + public WordEntry(String word) { + this.word = word; + this.count = 1; + } +} + +public class SeparateChainingImplementation { + // array of linked lists to store the word entries, private so it can only be modified by this class + private LinkedList[] table; + // keeps track of total number of unique words + private int size; + // initial size of hash table, one slot for each letter of the alphabet + private static final int INITIAL_CAPACITY = 26; + + // constructor to initialize the hash table + @SuppressWarnings("unchecked") + public SeparateChainingImplementation() { + // create array of LinkedLists + table = new LinkedList[INITIAL_CAPACITY]; + // Initialize all buckets with empty linked lists + for (int i = 0; i < INITIAL_CAPACITY; i++) { + table[i] = new LinkedList<>(); + } + size = 0; + } + + // hash function that uses first letter of word as specified in assignment + private int hash(String word) { + // handle edge cases of null or empty strings + if (word == null || word.isEmpty()) return 0; + // Convert first letter to 0-25 range using ASCII math + return (word.charAt(0) - 'a') % INITIAL_CAPACITY; + } + + // adds a word to the hash table or increments its count if already present + public void put(String word) { + // get the index where this word should be stored + int index = hash(word); + + // check if word already exists in the linked list at this index + for (WordEntry entry : table[index]) { + if (entry.word.equals(word)) { + // word found, increment its count + entry.count++; + return; + } + } + + // word not found in the list, add new entry + table[index].add(new WordEntry(word)); + size++; // increment total unique words counter + } + + // returns the count of a given word, or null if word doesn't exist + public Integer get(String word) { + // get the index where this word should be stored + int index = hash(word); + + // search the linked list at this index for the word + for (WordEntry entry : table[index]) { + if (entry.word.equals(word)) { + return entry.count; + } + } + + // word not found in the table + return null; + } + + // returns the number of unique words in the hash table + public int size() { + return size; + } + + // helper method to process entire text at once instead of word by word + public void processText(String text) { + // split the text into words using space as delimiter as specified in assignment + String[] words = text.split(" "); + // process each word using our put method + for (String word : words) { + put(word); + } + } + + // helper method to display the counts of all words + public void displayCounts() { + System.out.println("Word Counts (Separate Chaining):"); + System.out.println("------------------------------"); + // iterate through each bucket in the hash table + for (LinkedList bucket : table) { + // iterate through each entry in the current bucket + for (WordEntry entry : bucket) { + // formatting output to align counts + System.out.printf("%-20s: %d%n", entry.word, entry.count); + } + } + } + + // main method to test the implementation + public static void main(String[] args) { + // create new instance of our hash table + SeparateChainingImplementation counter = new SeparateChainingImplementation(); + // test string with multiple repeated words to demonstrate counting + String text = "this is a test this is only a test but this is also a longer test to show how the separate chaining handles more words but still no punctuation only words and more words and tests with words and such"; + // process the test text + counter.processText(text); + // display all word counts + counter.displayCounts(); + + // demonstrate individual word lookup + System.out.println("\nCount for word 'test': " + counter.get("test")); + System.out.println("Total unique words: " + counter.size()); + } +} \ No newline at end of file diff --git a/OLD!/source fles/ArrayStack.java b/OLD!/source fles/ArrayStack.java new file mode 100644 index 0000000..7986b6c --- /dev/null +++ b/OLD!/source fles/ArrayStack.java @@ -0,0 +1,127 @@ +import java.util.EmptyStackException; + +//code to declare an array +//example code based an based on the slides, showing Game leaderboard scores +//i will make my own highscore stack class + +/*here will be the main entry point */ +public class ArrayStack { + public static void main(String[] args) { + // Create a HighScoreStack instance + HighScoreStack highScores = new HighScoreStack(); + + try { + System.out.println("Testing push and top:"); + /* Add some GameEntry objects to the stack */ + highScores.push(new GameEntry("Alice", 100)); + highScores.push(new GameEntry("Bob", 150)); + highScores.push(new GameEntry("Charlie", 120)); + + System.out.println("Top entry: " + highScores.top()); // Display the top element + + System.out.println("\nTesting pop:"); + System.out.println("Popped entry: " + highScores.pop()); // Pop an element from the stack + + System.out.println("\nTesting size:"); + System.out.println("Current stack size: " + highScores.size()); // Display the size of the stack + + System.out.println("\nTesting push after pop:"); + highScores.push(new GameEntry("David", 200)); // Push another element to the stack for testing + + System.out.println("New top entry: " + highScores.top()); // Display the new top element + + System.out.println("Updated stack size: " + highScores.size()); // Display the size of the stack + + System.out.println("\nTesting isEmpty:"); + System.out.println("Is stack empty? " + highScores.isEmpty()); // Check if the stack is empty + + System.out.println("\nTesting push to full stack:"); + // Fill the stack + for (int i = 0; i < 7; i++) { + highScores.push(new GameEntry("Player" + i, i * 10)); + } + // This should cause a StackOverflowError + highScores.push(new GameEntry("OverflowPlayer", 1000)); + + } catch (StackOverflowError e) { + System.out.println("StackOverflowError caught as expected: " + e.getMessage()); + } catch (Exception e) { + System.out.println("An error occurred: " + e.getMessage()); + } + + System.out.println("\nTesting pop from empty stack:"); + HighScoreStack emptyStack = new HighScoreStack(); + try { + emptyStack.pop(); + } catch (EmptyStackException e) { + System.out.println("EmptyStackException caught as expected."); + } + } +} + +class GameEntry { + private String name; //name of the person earning the score + private int score; //score value + + /* constructs a game entry with given parameters */ + public GameEntry(String n, int s) { + name = n; + score = s; + } + + /* returns the name field */ + public String getName() { return name; } + + /* returns the score field */ + public int getScore() { return score; } + + /* returns a string representation of the entry */ + public String toString() { + return "(" + name + ", " + score + ")"; + } +} + +/* Implementing the HighScoreStack class here to make it a stack */ +class HighScoreStack { + private GameEntry[] stack; + private int top; + private static final int CAPACITY = 10; // just using 10 for simplicity + + public HighScoreStack() { + stack = new GameEntry[CAPACITY]; // Initializing the stack + top = -1; //we will create an empty stack + } + + public void push(GameEntry entry) throws StackOverflowError { + if (top == stack.length - 1) { //exception for if the stack is full + throw new StackOverflowError("The stack is full. You cannot add more elements."); + } + top++; //increment the top pointer + stack[top] = entry; // this will add the element to the top of the stack + } + + public GameEntry pop() throws EmptyStackException { + if (isEmpty()) { //exception for if the stack is empty + throw new EmptyStackException(); + } + GameEntry entry = stack[top]; //this will remove the top element + stack[top] = null; //this will remove the element from the stack + top--; //decrement the top pointer + return entry; //return the element that was removed + } + + public GameEntry top() throws EmptyStackException { //this will return but not remove the top element + if (isEmpty()) { //exception for if the stack is empty + throw new EmptyStackException(); + } + return stack[top]; //return the top element + } + + public int size() { //this will return the size of the stack + return top + 1; + } + + public boolean isEmpty() { //this will check if the stack is empty + return top == -1; //return true if the stack is empty + } +} \ No newline at end of file diff --git a/source fles/DoublyLinkedList.java b/OLD!/source fles/DoublyLinkedList.java similarity index 100% rename from source fles/DoublyLinkedList.java rename to OLD!/source fles/DoublyLinkedList.java diff --git a/OLD!/source fles/LinkedListStack.java b/OLD!/source fles/LinkedListStack.java new file mode 100644 index 0000000..8f0cc64 --- /dev/null +++ b/OLD!/source fles/LinkedListStack.java @@ -0,0 +1,143 @@ +import java.util.EmptyStackException; + +// This is an implementation of a stack, based on the code I did for the singly linked list in Java last week. +public class LinkedListStack { + private SinglyLinkedList list; // The underlying linked list to store stack elements + + // Constructor to initialize an empty stack + public LinkedListStack() { + list = new SinglyLinkedList<>(); + } + + // Method to add an element to the top of the stack + public void push(E element) { + list.addFirst(element); // Add the element to the front of the list (top of the stack) + } + + // Method to remove and return the top element from the stack + public E pop() { + if (isEmpty()) { + throw new EmptyStackException(); // Throw an exception if the stack is empty + } + return list.removeFirst(); // Remove and return the first element of the list (top of the stack) + } + + // Method to return the top element without removing it + public E top() { + if (isEmpty()) { + throw new EmptyStackException(); // Throw an exception if the stack is empty + } + return list.getFirst(); // Return the first element of the list (top of the stack) + } + + // Method to return the number of elements in the stack + public int size() { + return list.size(); // Return the size of the underlying list + } + + // Method to check if the stack is empty + public boolean isEmpty() { + return list.isEmpty(); // Check if the underlying list is empty + } + + //----------------TESTING-------------------------// + // Main method for testing the LinkedListStack implementation + public static void main(String[] args) { + LinkedListStack stack = new LinkedListStack<>(); + + System.out.println("Testing push and top:"); + stack.push(10); + stack.push(20); + stack.push(30); + System.out.println("Top element: " + stack.top()); + + System.out.println("\nTesting pop:"); + System.out.println("Popped element: " + stack.pop()); + System.out.println("New top element: " + stack.top()); + + System.out.println("\nTesting size:"); + System.out.println("Stack size: " + stack.size()); + + System.out.println("\nTesting isEmpty:"); + System.out.println("Is stack empty? " + stack.isEmpty()); + + System.out.println("\nPopping remaining elements:"); + while (!stack.isEmpty()) { + System.out.println("Popped: " + stack.pop()); + } + + System.out.println("Is stack empty now? " + stack.isEmpty()); + + // Test exception handling + try { + stack.pop(); + } catch (EmptyStackException e) { + System.out.println("Correctly threw EmptyStackException when popping from empty stack"); + } + } + + // Embedded SinglyLinkedList class to support the stack operations + private static class SinglyLinkedList { + // Node class to represent elements in the linked list + private static class Node { + private E element; // Element stored in the node + private Node next; // Reference to the next node in the list + + // Constructor to create a node with element "e" and next node "n" + public Node(E e, Node n) { + element = e; + next = n; + } + + public E getElement() { return element; } + public Node getNext() { return next; } + public void setNext(Node n) { next = n; } + } + + private Node head; // Head of the list + private Node tail; // Tail of the list + private int size; // Size of the list + + // Constructor to create an empty list + public SinglyLinkedList() { + head = null; + tail = null; + size = 0; + } + + // Method to add an element to the beginning of the list + public void addFirst(E e) { + head = new Node<>(e, head); + if (size == 0) // Check if the list was empty + tail = head; // If the list was empty, the new node is both head and tail + size++; // Increment the size of the list + } + + // Method to remove the first element + public E removeFirst() { + if (isEmpty()) return null; // Check if the list is empty + E answer = head.getElement(); + head = head.getNext(); // Update the head to the next node + size--; // Decrement the size of the list + if (size == 0) + tail = null; // If the list is now empty, update the tail + return answer; + } + + // Method to get the first element + public E getFirst() { + if (isEmpty()) return null; // Check if the list is empty + return head.getElement(); // Return the element stored in the head + } + + // Method to check if the list is empty + public boolean isEmpty() { + return size == 0; + } + + // Method to get the size of the list + public int size() { + return size; + } + } +} \ No newline at end of file diff --git a/source fles/SinglyLinkedList.java b/OLD!/source fles/SinglyLinkedList.java similarity index 100% rename from source fles/SinglyLinkedList.java rename to OLD!/source fles/SinglyLinkedList.java diff --git a/OLD!/source fles/queueArray.java b/OLD!/source fles/queueArray.java new file mode 100644 index 0000000..7b55c7b --- /dev/null +++ b/OLD!/source fles/queueArray.java @@ -0,0 +1,116 @@ +import java.util.NoSuchElementException; + +public class queueArray { //constructor i will use to make the queue + //need class variables + //pointers etc + int[] queue; //this will be my array to store the elements + int front; //this will be a pointer to the first element + int rear; //this will point to the tail element + int size; //this will track how many elements we have + int capacity; //this will store the maximum size of the array + + // Constructor + public queueArray(int capacity) { + this.capacity = capacity; + this.queue = new int[capacity]; + this.front = 0; + this.rear = -1; + this.size = 0; + } + + public void enqueue(int element) { //need to update this to be enqueue + //check if size == capacity + if (isFull()) { + throw new IllegalStateException("Queue is currently full"); //if so, return an exception + } + rear = (rear + 1) % capacity; //we need to set the rear to where our new element will go + queue[rear] = element; //add the element at the rear + size++; //increase the size to allow the element to be added + } + + public int dequeue() { //need to update this to be dequeue + //check if size == empty + if (isEmpty()){ + throw new IllegalStateException("Queue is currently empty! No item to remove"); //if it is, return an exception + } + int dequeuedElement = queue[front]; //store the front element as the element we will remove + front = (front + 1) % capacity; //move the front pointer and wrap around + size--; //decrease the size now that our element is gone + return dequeuedElement; //return the removed element + } + + + public int first() { //this will give me the first element + if (isEmpty()) { + throw new NoSuchElementException("The Queue is currently empty"); // Throw an exception if the queue is empty + } + return queue[front]; //this will return the front element of the queue + } + + public boolean isEmpty() { //this will check if the queue is empty + return size == 0; //return true if the queue is empty + } + + public boolean isFull() { + return (size == capacity); + } + + public int size() { + return size; + } + // Test cases + public static void main(String[] args) { + queueArray queue = new queueArray(5); + + // Test 1: isEmpty on a new queue + System.out.println("Test 1: " + (queue.isEmpty() ? "Passed" : "Failed")); + + // Test 2: Enqueue elements + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + System.out.println("Test 2: " + (queue.size() == 3 ? "Passed" : "Failed")); + + // Test 3: First element + System.out.println("Test 3: " + (queue.first() == 1 ? "Passed" : "Failed")); + + // Test 4: Dequeue + int dequeued = queue.dequeue(); + System.out.println("Test 4: " + (dequeued == 1 && queue.size() == 2 ? "Passed" : "Failed")); + + // Test 5: Enqueue to full capacity + queue.enqueue(4); + queue.enqueue(5); + queue.enqueue(6); // Enqueue the fifth element + try { + queue.enqueue(7); // This should throw an exception + System.out.println("Test 5: Failed"); + } catch (IllegalStateException e) { + System.out.println("Test 5: Passed"); + } + + // Test 6: Dequeue until empty + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + System.out.println("Test 6: " + (queue.isEmpty() ? "Passed" : "Failed")); + + // Test 7: Dequeue from empty queue + try { + queue.dequeue(); // This should throw an exception + System.out.println("Test 7: Failed"); + } catch (IllegalStateException e) { + System.out.println("Test 7: Passed"); + } + + // Test 8: First on empty queue + try { + queue.first(); // This should throw an exception + System.out.println("Test 8: Failed"); + } catch (NoSuchElementException e) { + System.out.println("Test 8: Passed"); + } + } +} diff --git a/OLD!/source fles/queueList.java b/OLD!/source fles/queueList.java new file mode 100644 index 0000000..da27ada --- /dev/null +++ b/OLD!/source fles/queueList.java @@ -0,0 +1,134 @@ +import java.util.NoSuchElementException; + +public class queueList { //constructor i will use to make the queue + //need class variables + //pointers etc + + // Node class + class Node { + int data; + Node next; + + Node(int data) { // Constructor for Node + this.data = data; + this.next = null; + } + } + + Node front; //this will be a pointer to the first element + Node rear; //this will point to the tail element + int size; //this will track how many elements we have + int capacity; //this will store the maximum size of the array + + // Constructor + public queueList(int capacity) { + this.capacity = capacity; + this.front = null; + this.rear = null; + this.size = 0; + } + + public void enqueue(int element) { //need to update this to be enqueue + //check if size == capacity + if (isFull()) { + throw new IllegalStateException("Queue is currently full"); //if so, return an exception + } + Node newNode = new Node(element); // create a new node with the element + if (rear == null) { // if queue is empty + front = rear = newNode; // both front and rear point to new node + } else { + rear.next = newNode; // add the new node at the end of the queue + rear = newNode; // move rear to point to the new node + } + size++; // increase the size to allow the element to be added + } + + public int dequeue() { //need to update this to be dequeue + //check if size == empty + if (isEmpty()){ + throw new IllegalStateException("Queue is currently empty! No item to remove"); //if it is, return an exception + } + int dequeuedElement = front.data; //store the front element as the element we will remove + front = front.next; //move the front pointer + if (front == null) { // if queue became empty after dequeue + rear = null; + } + size--; //decrease the size now that our element is gone + return dequeuedElement; //return the removed element + } + + + public int first() { //this will give me the first element + if (isEmpty()) { + throw new NoSuchElementException("The Queue is currently empty"); // Throw an exception if the queue is empty + } + return front.data; //this will return the front element of the queue + } + + public boolean isEmpty() { //this will check if the queue is empty + return size == 0; //return true if the queue is empty + } + + public boolean isFull() { + return (size == capacity); + } + + public int size() { + return size; + } + // Test cases + public static void main(String[] args) { + queueList queue = new queueList(5); + + // Test 1: isEmpty on a new queue + System.out.println("Test 1: " + (queue.isEmpty() ? "Passed" : "Failed")); + + // Test 2: Enqueue elements + queue.enqueue(1); + queue.enqueue(2); + queue.enqueue(3); + System.out.println("Test 2: " + (queue.size() == 3 ? "Passed" : "Failed")); + + // Test 3: First element + System.out.println("Test 3: " + (queue.first() == 1 ? "Passed" : "Failed")); + + // Test 4: Dequeue + int dequeued = queue.dequeue(); + System.out.println("Test 4: " + (dequeued == 1 && queue.size() == 2 ? "Passed" : "Failed")); + + // Test 5: Enqueue to full capacity + queue.enqueue(4); + queue.enqueue(5); + queue.enqueue(6); // Enqueue the fifth element + try { + queue.enqueue(7); // This should throw an exception + System.out.println("Test 5: Failed"); + } catch (IllegalStateException e) { + System.out.println("Test 5: Passed"); + } + + // Test 6: Dequeue until empty + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + queue.dequeue(); + System.out.println("Test 6: " + (queue.isEmpty() ? "Passed" : "Failed")); + + // Test 7: Dequeue from empty queue + try { + queue.dequeue(); // This should throw an exception + System.out.println("Test 7: Failed"); + } catch (IllegalStateException e) { + System.out.println("Test 7: Passed"); + } + + // Test 8: First on empty queue + try { + queue.first(); // This should throw an exception + System.out.println("Test 8: Failed"); + } catch (NoSuchElementException e) { + System.out.println("Test 8: Passed"); + } + } +} diff --git a/OLD!/src/Main.java b/OLD!/src/Main.java new file mode 100644 index 0000000..b5aa8c3 --- /dev/null +++ b/OLD!/src/Main.java @@ -0,0 +1,32 @@ +public class Main { + //binarySearch function + public static int binarySearch(int arr[], int right, int left, int target){ + if(left>right){ + return -1; + } + int mid = left + (right - left) / 2; + + //Check the middle element to see if it is the target + if (arr[mid] == target){ + return mid; + } + if (target < arr[mid]) { + return binarySearch(arr, left,mid -1, target); + } + else{ + return binarySearch(arr, mid + 1, right, target); + } + } + //reverse function + public static void reverse(int[] arr, int left, int right) { + if(left >= right){ + return; + } + //swap + int temp = arr[right]; + arr[right] = arr[left]; + arr[left] = temp; + + } + reverse(arr, left + 1, right - 1); +} \ No newline at end of file diff --git a/src/BinarySearch.java b/src/BinarySearch.java new file mode 100644 index 0000000..b1cb35c --- /dev/null +++ b/src/BinarySearch.java @@ -0,0 +1,43 @@ +public class BinarySearch { + // Main binary search function that matches the required signature + public int binarySearch(int[] arr, int k) { + // Call the recursive helper function with initial bounds + return binarySearchHelper(arr, 0, arr.length - 1, k); + } + + // Recursive helper function + private int binarySearchHelper(int[] arr, int left, int right, int target) { + // Base case: if bounds cross, element not found + if (left > right) { + return -1; + } + + // Calculate middle index + int mid = left + (right - left) / 2; + + // If element found at mid, return its index + if (arr[mid] == target) { + return mid; + } + + // If target is less than middle element, search left half + if (target < arr[mid]) { + return binarySearchHelper(arr, left, mid - 1, target); + } + + // If target is greater than middle element, search right half + return binarySearchHelper(arr, mid + 1, right, target); + } + + // Main method for testing + public static void main(String[] args) { + BinarySearch bs = new BinarySearch(); + + // Test case from assignment + int[] arr = {12, 45, 67, 89}; + + // Test cases + System.out.println("Searching for 67: " + bs.binarySearch(arr, 67)); // Should print 2 + System.out.println("Searching for 31: " + bs.binarySearch(arr, 31)); // Should print -1 + } +} \ No newline at end of file