From 45d12320a6958acd937cb6a4ea3cd60e9056d88e Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:14:42 -0400 Subject: [PATCH 01/47] Making a stack implementation --- source fles/GameEntry.java | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 source fles/GameEntry.java diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java new file mode 100644 index 0000000..879e1d7 --- /dev/null +++ b/source fles/GameEntry.java @@ -0,0 +1,37 @@ +//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 + + +public class GameEntry { + private String name; //name of the person earning the score + private int score; //score value + /* contructs 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 */ +public class HighScoreStack { + private GameEntry[] stack; + private int top; + private static final int CAPACITY = 10; // Or any default size you prefer + + public HighScoreStack() { + stack = new GameEntry[CAPACITY]; + top = -1; // Stack is initially empty + } + + // Implement stack operations here + } + +} From 41269db3f6c845ffd1e8da18e6451c02b11e22d8 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:15:36 -0400 Subject: [PATCH 02/47] Implement HighScoreStack class as a stack --- source fles/GameEntry.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 879e1d7..9d7eb21 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -20,7 +20,7 @@ public String toString() { return "(" + name + ", " + score + ")"; } - /* Implementing the HighScoreStack class here */ + /* Implementing the HighScoreStack class here to make it a stack */ public class HighScoreStack { private GameEntry[] stack; private int top; From 5a0a939df3ca333236f79f59fc82bca3ce1066be Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:17:57 -0400 Subject: [PATCH 03/47] Refactor GameEntry class: Fix typo in comment and add missing method documentation Refactor HighScoreStack class: Implement stack operations and add missing method documentation --- source fles/GameEntry.java | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 9d7eb21..3336425 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -6,32 +6,52 @@ public class GameEntry { private String name; //name of the person earning the score private int score; //score value - /* contructs a game entry with given parameters */ + + /* 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 */ -public class HighScoreStack { + public class HighScoreStack { private GameEntry[] stack; private int top; private static final int CAPACITY = 10; // Or any default size you prefer public HighScoreStack() { - stack = new GameEntry[CAPACITY]; - top = -1; // Stack is initially empty + // Initialize the stack here + } + + public void push(GameEntry entry) { + // Implement push operation + } + + public GameEntry pop() { + // Implement pop operation + } + + public GameEntry top() { + // Implement top operation } - // Implement stack operations here + public int size() { + // Implement size operation + } + + public boolean isEmpty() { + // Implement isEmpty operation + } } - -} +} \ No newline at end of file From 12cac6a2b0b521898aa6dc58900cfa262461efb3 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:29:02 -0400 Subject: [PATCH 04/47] Refactor GameEntry and implement HighScoreStack classes --- source fles/GameEntry.java | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 3336425..4757d34 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -28,18 +28,30 @@ public String toString() { public class HighScoreStack { private GameEntry[] stack; private int top; - private static final int CAPACITY = 10; // Or any default size you prefer + private static final int CAPACITY = 10; // just using 10 for simplicity public HighScoreStack() { - // Initialize the stack here + stack = new GameEntry [CAPACITY]; // Initializing the stack + top = -1; //we will create an empty stack } public void push(GameEntry entry) { - // Implement push operation + if (top == stack.length - 1) { //exception for if the stack is full + System.out.println(" The stack is full. You cannot add more elements. Use pop() to remove an element."); + return; + } + top++; //increment the top pointer + stack[top] = entry; // this will add the element to the top of the stack } public GameEntry pop() { - // Implement pop operation + if (isEmpty()) { //exception for if the stack is empty + System.out.println("The stack is empty. There are no elements to pop."); + return null; } + 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() { From 85fb928b541f410d54a6225c980ebb8b891acb55 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:32:54 -0400 Subject: [PATCH 05/47] Refactor GameEntry class: Fix typo in comment and add missing method documentation --- source fles/GameEntry.java | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 4757d34..acfbfed 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -54,16 +54,21 @@ public GameEntry pop() { return entry; //return the element that was removed } - public GameEntry top() { - // Implement top operation + public GameEntry top() { //this will return but not remove the top element + if (isEmpty()) { //exception for if the stack is empty + System.out.println("The stack is empty. There are no elements to return."); + return null; } + return stack[top]; //return the top element } - public int size() { - // Implement size operation - } - - public boolean isEmpty() { - // Implement isEmpty operation + public int size() { //this will return the size of the stack + if (isEmpty()) { //exception for if the stack is empty + System.out.println("No elements. The size is 0" ); + return 0; } + else { + return top + 1; //return the size of the stack + } + 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 + } \ No newline at end of file From db36b0565b9ec2ab5abdff2c9a2af8fbb7564a6d Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:34:11 -0400 Subject: [PATCH 06/47] Refactor GameEntry class: Fix typo in comment and add missing method documentation --- source fles/GameEntry.java | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index acfbfed..618360f 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -34,7 +34,6 @@ public HighScoreStack() { stack = new GameEntry [CAPACITY]; // Initializing the stack top = -1; //we will create an empty stack } - public void push(GameEntry entry) { if (top == stack.length - 1) { //exception for if the stack is full System.out.println(" The stack is full. You cannot add more elements. Use pop() to remove an element."); @@ -43,7 +42,6 @@ public void push(GameEntry entry) { top++; //increment the top pointer stack[top] = entry; // this will add the element to the top of the stack } - public GameEntry pop() { if (isEmpty()) { //exception for if the stack is empty System.out.println("The stack is empty. There are no elements to pop."); @@ -53,20 +51,14 @@ public GameEntry pop() { top--; //decrement the top pointer return entry; //return the element that was removed } - public GameEntry top() { //this will return but not remove the top element if (isEmpty()) { //exception for if the stack is empty System.out.println("The stack is empty. There are no elements to return."); return null; } return stack[top]; //return the top element } - public int size() { //this will return the size of the stack - if (isEmpty()) { //exception for if the stack is empty - System.out.println("No elements. The size is 0" ); - return 0; } - else { - return top + 1; //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 From 76b471845d0dda9d09e50d66013edcb11b685bcb Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:36:13 -0400 Subject: [PATCH 07/47] fixed indentation --- source fles/GameEntry.java | 74 +++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 618360f..4f697fc 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -25,42 +25,42 @@ public String toString() { } /* Implementing the HighScoreStack class here to make it a stack */ - public 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) { - if (top == stack.length - 1) { //exception for if the stack is full - System.out.println(" The stack is full. You cannot add more elements. Use pop() to remove an element."); - return; - } - top++; //increment the top pointer - stack[top] = entry; // this will add the element to the top of the stack - } - public GameEntry pop() { - if (isEmpty()) { //exception for if the stack is empty - System.out.println("The stack is empty. There are no elements to pop."); - return null; } - 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() { //this will return but not remove the top element - if (isEmpty()) { //exception for if the stack is empty - System.out.println("The stack is empty. There are no elements to return."); - return null; } - return stack[top]; //return the top element +public 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) { + if (top == stack.length - 1) { //exception for if the stack is full + System.out.println(" The stack is full. You cannot add more elements. Use pop() to remove an element."); + return; } - 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 + top++; //increment the top pointer + stack[top] = entry; // this will add the element to the top of the stack + } + public GameEntry pop() { + if (isEmpty()) { //exception for if the stack is empty + System.out.println("The stack is empty. There are no elements to pop."); + return null; } + 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() { //this will return but not remove the top element + if (isEmpty()) { //exception for if the stack is empty + System.out.println("The stack is empty. There are no elements to return."); + return null; } + return stack[top]; //return the top element + } + public int size() { //this will return the size of the stack + return top + 1; } - } \ No newline at end of file + 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 From 37ee13a02223e587889d28e86bc7f86da2364de0 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:51:04 -0400 Subject: [PATCH 08/47] fixed --- source fles/GameEntry.java | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/source fles/GameEntry.java b/source fles/GameEntry.java index 4f697fc..1f1a853 100644 --- a/source fles/GameEntry.java +++ b/source fles/GameEntry.java @@ -3,7 +3,7 @@ //i will make my own highscore stack class -public class GameEntry { + class GameEntry { private String name; //name of the person earning the score private int score; //score value @@ -23,7 +23,7 @@ public GameEntry(String n, int s) { public String toString() { return "(" + name + ", " + score + ")"; } - +} /* Implementing the HighScoreStack class here to make it a stack */ public class HighScoreStack { private GameEntry[] stack; @@ -63,4 +63,30 @@ public int size() { //this will return the size of the stack public boolean isEmpty() { //this will check if the stack is empty return top == -1; //return true if the stack is empty } +} + +/*here will be the main entry point */ + +public class Main { + public static void main(String[] args) { + // Create a HighScoreStack instance + HighScoreStack highScores = new HighScoreStack(); + + // 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)); + + // Display the top element + System.out.println("Top entry: " + highScores.top()); + + // Pop an element from the stack + System.out.println("Popped entry: " + highScores.pop()); + + // Display the size of the stack + System.out.println("Current stack size: " + highScores.size()); + + // Check if the stack is empty + System.out.println("Is stack empty? " + highScores.isEmpty()); + } } \ No newline at end of file From e241af78e42e44c33f036d41ee65e8b3df99fefb Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 21:51:53 -0400 Subject: [PATCH 09/47] Refactor GameEntry and HighScoreStack classes: Rename GameEntry.java to HighScoreStack.java and update class references --- .../{GameEntry.java => HighScoreStack.java} | 89 ++++++++++--------- 1 file changed, 49 insertions(+), 40 deletions(-) rename source fles/{GameEntry.java => HighScoreStack.java} (59%) diff --git a/source fles/GameEntry.java b/source fles/HighScoreStack.java similarity index 59% rename from source fles/GameEntry.java rename to source fles/HighScoreStack.java index 1f1a853..49ac793 100644 --- a/source fles/GameEntry.java +++ b/source fles/HighScoreStack.java @@ -1,9 +1,39 @@ +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 Main { + public static void main(String[] args) { + // Create a HighScoreStack instance + HighScoreStack highScores = new HighScoreStack(); + + try { + // 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)); + + // Display the top element + System.out.println("Top entry: " + highScores.top()); + + // Pop an element from the stack + System.out.println("Popped entry: " + highScores.pop()); + + // Display the size of the stack + System.out.println("Current stack size: " + highScores.size()); - class GameEntry { + // Check if the stack is empty + System.out.println("Is stack empty? " + highScores.isEmpty()); + } catch (Exception e) { + System.out.println("An error occurred: " + e.getMessage()); + } + } +} + +class GameEntry { private String name; //name of the person earning the score private int score; //score value @@ -24,69 +54,48 @@ public String toString() { return "(" + name + ", " + score + ")"; } } - /* Implementing the HighScoreStack class here to make it a stack */ -public class HighScoreStack { + +/* 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 + stack = new GameEntry[CAPACITY]; // Initializing the stack top = -1; //we will create an empty stack } - public void push(GameEntry entry) { + + public void push(GameEntry entry) throws StackOverflowError { if (top == stack.length - 1) { //exception for if the stack is full - System.out.println(" The stack is full. You cannot add more elements. Use pop() to remove an element."); - return; + 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() { + + public GameEntry pop() throws EmptyStackException { if (isEmpty()) { //exception for if the stack is empty - System.out.println("The stack is empty. There are no elements to pop."); - return null; } + 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() { //this will return but not remove the top element + + public GameEntry top() throws EmptyStackException { //this will return but not remove the top element if (isEmpty()) { //exception for if the stack is empty - System.out.println("The stack is empty. There are no elements to return."); - return null; } + 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 } -} - -/*here will be the main entry point */ -public class Main { - public static void main(String[] args) { - // Create a HighScoreStack instance - HighScoreStack highScores = new HighScoreStack(); - - // 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)); - - // Display the top element - System.out.println("Top entry: " + highScores.top()); - - // Pop an element from the stack - System.out.println("Popped entry: " + highScores.pop()); - - // Display the size of the stack - System.out.println("Current stack size: " + highScores.size()); - - // Check if the stack is empty - System.out.println("Is stack empty? " + highScores.isEmpty()); + 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 From 02d607748a63e44abf7cac5d556f8a273deeb0bc Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 22:03:23 -0400 Subject: [PATCH 10/47] Refactor Main class: Update class references and fix indentation --- .../{HighScoreStack.java => Main.java} | 44 +++++++++++++++---- 1 file changed, 35 insertions(+), 9 deletions(-) rename source fles/{HighScoreStack.java => Main.java} (67%) diff --git a/source fles/HighScoreStack.java b/source fles/Main.java similarity index 67% rename from source fles/HighScoreStack.java rename to source fles/Main.java index 49ac793..92cc53a 100644 --- a/source fles/HighScoreStack.java +++ b/source fles/Main.java @@ -11,25 +11,51 @@ public static void main(String[] args) { HighScoreStack highScores = new HighScoreStack(); try { - // Add some GameEntry objects to the stack + 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)); - // Display the top element - System.out.println("Top entry: " + highScores.top()); + System.out.println("Top entry: " + highScores.top()); // Display the top element - // Pop an element from the stack - System.out.println("Popped entry: " + highScores.pop()); + System.out.println("\nTesting pop:"); + System.out.println("Popped entry: " + highScores.pop()); // Pop an element from the stack - // Display the size of the stack - System.out.println("Current stack size: " + highScores.size()); + System.out.println("\nTesting size:"); + System.out.println("Current stack size: " + highScores.size()); // Display the size of the stack - // Check if the stack is empty - System.out.println("Is stack empty? " + highScores.isEmpty()); + 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."); + } } } From 5b7f0c3920283f232331fe64710406ebe96574be Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 22:06:30 -0400 Subject: [PATCH 11/47] Refactor Main class: Rename Main.java to ArrayStack.java and update class references --- source fles/{Main.java => ArrayStack.java} | 2 +- source fles/SinglyLinkedStack.java | 185 +++++++++++++++++++++ 2 files changed, 186 insertions(+), 1 deletion(-) rename source fles/{Main.java => ArrayStack.java} (99%) create mode 100644 source fles/SinglyLinkedStack.java diff --git a/source fles/Main.java b/source fles/ArrayStack.java similarity index 99% rename from source fles/Main.java rename to source fles/ArrayStack.java index 92cc53a..7986b6c 100644 --- a/source fles/Main.java +++ b/source fles/ArrayStack.java @@ -5,7 +5,7 @@ //i will make my own highscore stack class /*here will be the main entry point */ -public class Main { +public class ArrayStack { public static void main(String[] args) { // Create a HighScoreStack instance HighScoreStack highScores = new HighScoreStack(); diff --git a/source fles/SinglyLinkedStack.java b/source fles/SinglyLinkedStack.java new file mode 100644 index 0000000..c91d2d0 --- /dev/null +++ b/source fles/SinglyLinkedStack.java @@ -0,0 +1,185 @@ +// This is a simple implementation of a singly linked list in Java +public class SinglyLinkedList { //define the SinglyLinkedList class + private static class Node { //define the Node class as a nested class + private E element; //element stored in the node + private Node next; //point to the next node in the list to establish the chain + //-----------------------------------------// + public Node(E e, Node n) { //constructor to create a node with element "e" and next node "n" + element = e; //set the element of the node to the input element + next = n; //establish the next node in the list + } + + public E getElement() { return element; } + public Node getNext() { return next; } + public void setNext(Node n) { next = n; } + // Create an empty node + public Node() { + this(null, null); +} + } + + // Head of the list + private Node head; + // Tail of the list + private Node tail; + // Size of the list + private int size; + + // Constructor + public SinglyLinkedList() { //setting head and tail to null and size to 0 becasue the list is currently empty + head = null; + tail = null; + size = 0; + } + + // this is the 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 is empty + tail = head; //if the list is empty then we need to make the tail point to the head + size++; //increment the size of the list to keep track of the number of elements in 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 new first element + size--; //decrement the size of the list to adjust for the removal of the element + if (size == 0) + tail = null; + return answer; + } + + public E getFirst() { // Method to get the first element + 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 last element in the list + public E getLast() { + if (isEmpty()) return null; //check if the list is empty + return tail.getElement(); //return the element stored in the tail + } + + // Method to get the size of the list + public int size() { + return size; + } + + // Method to add an element to the end of the list + public void addLast(E e) { + Node newest = new Node<>(e, null); //create a new node with the element "e" with next node as null + if (isEmpty()) + head = newest; //if the list is empty we will point the head to the new node + else + tail.setNext(newest); //if the list is not empty we will point the tail to the new node + tail = newest; //update the tail to the new node + size++; //adjust the size of the list to account for the new element + } + + //method to traverse the list and print the elements + public void printList() { + Node current = head; //start at the first node + while (current != null) { //loop will end when we reach the end of the list + System.out.print(current.getElement() + " "); //print the element of the current node + current = current.getNext(); //move to the next node + } + System.out.println(); + } + + // Method to add a new node to a specified location (after a given node) + public void addAfter(E e, Node node) { //so once we find the node we want to add after, we can add the new node using this method + if (node == null) { //if the node is null, we will add the new node to the beginning of the list + addFirst(e); + return; + } + Node newest = new Node<>(e, node.getNext()); //create a new node with our content and point it to the next node of the given node + node.setNext(newest); //update the next node pointer + if (tail == node) //if the given node is the tail, we will update the tail pointer + tail = newest; + size++; //incrememt size + } + + // Method to delete any node in the linked list + public E remove(E e) { //we will remove the node with the element "e" + if (isEmpty()) return null; + if (head.getElement().equals(e)) return removeFirst(); //if the element is in the head, we will remove the head + + Node prev = head; + Node current = head.getNext(); + while (current != null && !current.getElement().equals(e)) { + prev = current; + current = current.getNext(); + } + + if (current != null) { + prev.setNext(current.getNext()); //if the element is found, we will update the next pointer of the previous node to the next node of the current node. hope i wrote that out right + size--; //decrement the size of the list + if (current == tail) //if the current node is the tail, we will update the tail pointer to the previous node so it is the new tail + tail = prev; + return current.getElement(); + } + return null; //if the element is not found, we will return null + } + + //method to create an empty node + public Node createEmptyNode() { + return new Node<>(); + } + // method to create a node with a given value + public Node createNodeE(E value) { + return new Node<>(value, null); + } + +//----------------TESTING-------------------------// + + public static void main(String[] args) { + SinglyLinkedList s = new SinglyLinkedList<>(); //using strings for this test, showing .addFirst, .addLast, .printList, and .remove. + s.addFirst("code"); + s.addFirst("my"); + s.addFirst("Testing"); + s.addLast("!"); + System.out.println("List after adding elements:"); + s.printList(); + System.out.println("First element: " + s.getFirst()); + System.out.println("Last element: " + s.getLast()); + System.out.println("Size of the list: " + s.size()); + System.out.println("Removed first element: " + s.removeFirst()); + System.out.println("List after removing first element:"); + s.printList(); + s.remove("my"); + System.out.println("List after removing 'my':"); + s.printList(); + + + System.out.println("\n--- More Test Cases ---"); + + SinglyLinkedList list = new SinglyLinkedList<>(); //using int this time + // Test isEmpty on a new list + System.out.println("Is new list empty? " + list.isEmpty()); //showcasing the isEmpty method. should return true + list.addFirst(3); //showcasing the addFirst method + list.addFirst(2); + list.addFirst(1); + list.addLast(4); //showcasing the addLast method + list.addLast(5); + System.out.println("List after adding elements:"); + list.printList(); //showcasing the printList method + System.out.println("Adding 0 after the second element to show .addAfter:"); + list.addAfter(0, list.head.getNext()); //showcasing the addAfter method + list.printList(); + + // Test creating an empty node + Node emptyNode = list.createEmptyNode(); //showcasing the createEmptyNode method + System.out.println("Empty node created: " + (emptyNode != null)); + + // Test creating a node with a value + Node valueNode = list.createNodeE(42); //showcasing the createNodeE method + System.out.println("Node with value created: " + (valueNode != null && valueNode.getElement() == 42)); +} +} \ No newline at end of file From c56cfa5a3564b4ccb9f691f820f27bbe59961ebb Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 22:10:12 -0400 Subject: [PATCH 12/47] Refactor LinkedListStack class: Implement a stack using a singly linked list in Java --- source fles/LinkedListStack.java | 143 +++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 source fles/LinkedListStack.java diff --git a/source fles/LinkedListStack.java b/source fles/LinkedListStack.java new file mode 100644 index 0000000..6e11298 --- /dev/null +++ b/source fles/LinkedListStack.java @@ -0,0 +1,143 @@ +import java.util.EmptyStackException; + +// This is an implementation of a stack using a singly linked list in Java +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 From c02eac3b6a6ea2c6398486153b1c70e3d351ea57 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 22 Sep 2024 22:13:21 -0400 Subject: [PATCH 13/47] Refactor LinkedListStack class: Update comments to clarify the purpose of the stack implementation --- source fles/LinkedListStack.java | 2 +- source fles/SinglyLinkedStack.java | 185 ----------------------------- 2 files changed, 1 insertion(+), 186 deletions(-) delete mode 100644 source fles/SinglyLinkedStack.java diff --git a/source fles/LinkedListStack.java b/source fles/LinkedListStack.java index 6e11298..8f0cc64 100644 --- a/source fles/LinkedListStack.java +++ b/source fles/LinkedListStack.java @@ -1,6 +1,6 @@ import java.util.EmptyStackException; -// This is an implementation of a stack using a singly linked list in Java +// 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 diff --git a/source fles/SinglyLinkedStack.java b/source fles/SinglyLinkedStack.java deleted file mode 100644 index c91d2d0..0000000 --- a/source fles/SinglyLinkedStack.java +++ /dev/null @@ -1,185 +0,0 @@ -// This is a simple implementation of a singly linked list in Java -public class SinglyLinkedList { //define the SinglyLinkedList class - private static class Node { //define the Node class as a nested class - private E element; //element stored in the node - private Node next; //point to the next node in the list to establish the chain - //-----------------------------------------// - public Node(E e, Node n) { //constructor to create a node with element "e" and next node "n" - element = e; //set the element of the node to the input element - next = n; //establish the next node in the list - } - - public E getElement() { return element; } - public Node getNext() { return next; } - public void setNext(Node n) { next = n; } - // Create an empty node - public Node() { - this(null, null); -} - } - - // Head of the list - private Node head; - // Tail of the list - private Node tail; - // Size of the list - private int size; - - // Constructor - public SinglyLinkedList() { //setting head and tail to null and size to 0 becasue the list is currently empty - head = null; - tail = null; - size = 0; - } - - // this is the 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 is empty - tail = head; //if the list is empty then we need to make the tail point to the head - size++; //increment the size of the list to keep track of the number of elements in 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 new first element - size--; //decrement the size of the list to adjust for the removal of the element - if (size == 0) - tail = null; - return answer; - } - - public E getFirst() { // Method to get the first element - 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 last element in the list - public E getLast() { - if (isEmpty()) return null; //check if the list is empty - return tail.getElement(); //return the element stored in the tail - } - - // Method to get the size of the list - public int size() { - return size; - } - - // Method to add an element to the end of the list - public void addLast(E e) { - Node newest = new Node<>(e, null); //create a new node with the element "e" with next node as null - if (isEmpty()) - head = newest; //if the list is empty we will point the head to the new node - else - tail.setNext(newest); //if the list is not empty we will point the tail to the new node - tail = newest; //update the tail to the new node - size++; //adjust the size of the list to account for the new element - } - - //method to traverse the list and print the elements - public void printList() { - Node current = head; //start at the first node - while (current != null) { //loop will end when we reach the end of the list - System.out.print(current.getElement() + " "); //print the element of the current node - current = current.getNext(); //move to the next node - } - System.out.println(); - } - - // Method to add a new node to a specified location (after a given node) - public void addAfter(E e, Node node) { //so once we find the node we want to add after, we can add the new node using this method - if (node == null) { //if the node is null, we will add the new node to the beginning of the list - addFirst(e); - return; - } - Node newest = new Node<>(e, node.getNext()); //create a new node with our content and point it to the next node of the given node - node.setNext(newest); //update the next node pointer - if (tail == node) //if the given node is the tail, we will update the tail pointer - tail = newest; - size++; //incrememt size - } - - // Method to delete any node in the linked list - public E remove(E e) { //we will remove the node with the element "e" - if (isEmpty()) return null; - if (head.getElement().equals(e)) return removeFirst(); //if the element is in the head, we will remove the head - - Node prev = head; - Node current = head.getNext(); - while (current != null && !current.getElement().equals(e)) { - prev = current; - current = current.getNext(); - } - - if (current != null) { - prev.setNext(current.getNext()); //if the element is found, we will update the next pointer of the previous node to the next node of the current node. hope i wrote that out right - size--; //decrement the size of the list - if (current == tail) //if the current node is the tail, we will update the tail pointer to the previous node so it is the new tail - tail = prev; - return current.getElement(); - } - return null; //if the element is not found, we will return null - } - - //method to create an empty node - public Node createEmptyNode() { - return new Node<>(); - } - // method to create a node with a given value - public Node createNodeE(E value) { - return new Node<>(value, null); - } - -//----------------TESTING-------------------------// - - public static void main(String[] args) { - SinglyLinkedList s = new SinglyLinkedList<>(); //using strings for this test, showing .addFirst, .addLast, .printList, and .remove. - s.addFirst("code"); - s.addFirst("my"); - s.addFirst("Testing"); - s.addLast("!"); - System.out.println("List after adding elements:"); - s.printList(); - System.out.println("First element: " + s.getFirst()); - System.out.println("Last element: " + s.getLast()); - System.out.println("Size of the list: " + s.size()); - System.out.println("Removed first element: " + s.removeFirst()); - System.out.println("List after removing first element:"); - s.printList(); - s.remove("my"); - System.out.println("List after removing 'my':"); - s.printList(); - - - System.out.println("\n--- More Test Cases ---"); - - SinglyLinkedList list = new SinglyLinkedList<>(); //using int this time - // Test isEmpty on a new list - System.out.println("Is new list empty? " + list.isEmpty()); //showcasing the isEmpty method. should return true - list.addFirst(3); //showcasing the addFirst method - list.addFirst(2); - list.addFirst(1); - list.addLast(4); //showcasing the addLast method - list.addLast(5); - System.out.println("List after adding elements:"); - list.printList(); //showcasing the printList method - System.out.println("Adding 0 after the second element to show .addAfter:"); - list.addAfter(0, list.head.getNext()); //showcasing the addAfter method - list.printList(); - - // Test creating an empty node - Node emptyNode = list.createEmptyNode(); //showcasing the createEmptyNode method - System.out.println("Empty node created: " + (emptyNode != null)); - - // Test creating a node with a value - Node valueNode = list.createNodeE(42); //showcasing the createNodeE method - System.out.println("Node with value created: " + (valueNode != null && valueNode.getElement() == 42)); -} -} \ No newline at end of file From 55940558dedbe872810db0aff1ded672dac334ea Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 13:40:57 -0400 Subject: [PATCH 14/47] Adding variable space --- source fles/queueArray.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 source fles/queueArray.java diff --git a/source fles/queueArray.java b/source fles/queueArray.java new file mode 100644 index 0000000..bf7d3cf --- /dev/null +++ b/source fles/queueArray.java @@ -0,0 +1,13 @@ +//here is where the variables will go + + + +public class queueArray { //constructor i will use to make the queue + //need class variables + //pointers etc + //structure  x + //enqueue method + //dequeue method + //isempty + //isfull +} From 456fab698dddaec1b546b754b361453dbaedbd3e Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 14:00:01 -0400 Subject: [PATCH 15/47] Added skeleton for top, enqueue, and isempty methods --- source fles/queueArray.java | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index bf7d3cf..d43602c 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -1,13 +1,28 @@ -//here is where the variables will go - - - 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 //structure  x - //enqueue method - //dequeue method - //isempty + + public void push(E element) { //need to update this to be enqueue + list.addFirst(element); // Add the element to the front of the list (top of the stack) + } + + //dequeue method will go here + + 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) + } + + public boolean isEmpty() { //this will check if the queue is empty + return top == -1; //return true if the stack is empty + } //isfull } From 049760c9709de7a1212d1e3a63875752a5d9c030 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 14:16:14 -0400 Subject: [PATCH 16/47] fixed isEmpty method Now using size == 0 --- source fles/queueArray.java | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index d43602c..89dfe84 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -1,3 +1,5 @@ +import java.util.EmptyQueueException; + public class queueArray { //constructor i will use to make the queue //need class variables //pointers etc @@ -6,23 +8,27 @@ public class queueArray { //constructor i will use to make the queue 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 + //structure  x - public void push(E element) { //need to update this to be enqueue - list.addFirst(element); // Add the element to the front of the list (top of the stack) + public void enqueue(int element) { //need to update this to be enqueue + queue.addFirst(); // Add the element to the front of the queue } //dequeue method will go here - - public E top() { + + public E first() { if (isEmpty()) { - throw new EmptyStackException(); // Throw an exception if the stack is empty + throw new EmptyQueueException(); // Throw an exception if the stack is empty } - return list.getFirst(); // Return the first element of the list (top of the stack) + return queue.getFirst(); // Return the first element of the list (top of the stack) } public boolean isEmpty() { //this will check if the queue is empty - return top == -1; //return true if the stack is empty + return size == 0; //return true if the queue is empty } - //isfull + + //isfull method will go here + + //size method will go here } From 67f0daaaa7ff7383d12db9f08dac22b5a4bda2f5 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 14:25:22 -0400 Subject: [PATCH 17/47] update element type to int type --- source fles/queueArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 89dfe84..372f8c5 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -17,7 +17,7 @@ public void enqueue(int element) { //need to update this to be enqueue //dequeue method will go here - public E first() { + public int first() { //this will give me the first element if (isEmpty()) { throw new EmptyQueueException(); // Throw an exception if the stack is empty } From fe4b778a0a413379f06432a6f4059f9aa1732816 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 14:34:34 -0400 Subject: [PATCH 18/47] fixed first() method --- source fles/queueArray.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 372f8c5..2c5c529 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -1,4 +1,4 @@ -import java.util.EmptyQueueException; +import java.util.NoSuchElementException; public class queueArray { //constructor i will use to make the queue //need class variables @@ -19,9 +19,9 @@ public void enqueue(int element) { //need to update this to be enqueue public int first() { //this will give me the first element if (isEmpty()) { - throw new EmptyQueueException(); // Throw an exception if the stack is empty + throw new NoSuchElementException("The Queue is currently empty"); // Throw an exception if the queue is empty } - return queue.getFirst(); // Return the first element of the list (top of the stack) + return queue[front]; //this will return the front element of the queue } public boolean isEmpty() { //this will check if the queue is empty From c1f0f5fe7605f31e14ba526b0cb4ec313e021811 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 14:40:48 -0400 Subject: [PATCH 19/47] Fixed enqueue method to use rear, so it can be first in, first out. --- source fles/queueArray.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 2c5c529..1606943 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -12,7 +12,13 @@ public class queueArray { //constructor i will use to make the queue //structure  x public void enqueue(int element) { //need to update this to be enqueue - queue.addFirst(); // Add the element to the front of the queue + //check if size == capacity + if (size == capacity) { + throw new IllegalStateException("Queue is currently full"); //if not, 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 } //dequeue method will go here From a3ad6f39254c5e06243fa1e57c566a855abe4763 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 21:31:26 -0400 Subject: [PATCH 20/47] Implemented isFull and Size methods --- source fles/queueArray.java | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 1606943..f95a84c 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -13,15 +13,25 @@ public class queueArray { //constructor i will use to make the queue public void enqueue(int element) { //need to update this to be enqueue //check if size == capacity - if (size == capacity) { - throw new IllegalStateException("Queue is currently full"); //if not, return an exception + 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 } - //dequeue method will go here + 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()) { @@ -34,7 +44,11 @@ public boolean isEmpty() { //this will check if the queue is empty return size == 0; //return true if the queue is empty } - //isfull method will go here + public boolean isFull() { + return (size == capacity); + } - //size method will go here + public int size() { + return size; + } } From 70c142ad16953701c63661c5c3b94b9730726d00 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 21:31:45 -0400 Subject: [PATCH 21/47] fixed spacing --- source fles/queueArray.java | 1 - 1 file changed, 1 deletion(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index f95a84c..70af8b1 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -9,7 +9,6 @@ public class queueArray { //constructor i will use to make the queue int size; //this will track how many elements we have int capacity; //this will store the maximum size of the array - //structure  x public void enqueue(int element) { //need to update this to be enqueue //check if size == capacity From ebd2212a85028927d7e61f176e4ce3c0210a2e10 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 21:32:58 -0400 Subject: [PATCH 22/47] fixed typo in enqueue() method --- source fles/queueArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 70af8b1..55f2f49 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -12,7 +12,7 @@ public class queueArray { //constructor i will use to make the queue public void enqueue(int element) { //need to update this to be enqueue //check if size == capacity - if isFull() { + 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 From f76f2520a131cd20cae79fffb4da6764e0d312c5 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 21:42:40 -0400 Subject: [PATCH 23/47] Added test cases --- source fles/queueArray.java | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 55f2f49..954f877 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -50,4 +50,57 @@ public boolean isFull() { 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); + try { + queue.enqueue(6); // 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(); + 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"); + } + } } From 824260324c1dcf5f8af626b46f4d77d90c6f3208 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 21:55:53 -0400 Subject: [PATCH 24/47] fixed test cases, now all pass --- source fles/queueArray.java | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/source fles/queueArray.java b/source fles/queueArray.java index 954f877..7b55c7b 100644 --- a/source fles/queueArray.java +++ b/source fles/queueArray.java @@ -9,6 +9,14 @@ public class queueArray { //constructor i will use to make the queue 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 @@ -53,40 +61,42 @@ public int 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(6); // This should throw an exception + 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 @@ -94,7 +104,7 @@ public static void main(String[] args) { } catch (IllegalStateException e) { System.out.println("Test 7: Passed"); } - + // Test 8: First on empty queue try { queue.first(); // This should throw an exception @@ -102,5 +112,5 @@ public static void main(String[] args) { } catch (NoSuchElementException e) { System.out.println("Test 8: Passed"); } - } + } } From a07443c01b2fec8e357ece5de12c3c239edf3ea9 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 2 Oct 2024 22:20:27 -0400 Subject: [PATCH 25/47] Turned array into linked list --- source fles/queueList.java | 134 +++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 source fles/queueList.java diff --git a/source fles/queueList.java b/source fles/queueList.java new file mode 100644 index 0000000..da27ada --- /dev/null +++ b/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"); + } + } +} From f9c4ba285c32a0c48913f730aabf8f2d50173273 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:17:34 -0400 Subject: [PATCH 26/47] Add Part1_Stack.java with stack implementation using Java's built-in Stack class --- Homework 4/Part1_Stack.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Homework 4/Part1_Stack.java diff --git a/Homework 4/Part1_Stack.java b/Homework 4/Part1_Stack.java new file mode 100644 index 0000000..2b391f6 --- /dev/null +++ b/Homework 4/Part1_Stack.java @@ -0,0 +1,27 @@ +// Part1_Stack.java + +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); + stack.push(20); + stack.push(30); + + // Test peek() method + System.out.println("Top element (peek): " + stack.peek()); + + // Test pop() method + System.out.println("Popped element: " + stack.pop()); + + // Test empty() method + System.out.println("Is stack empty? " + stack.empty()); + + // Add more test cases as needed... + } +} \ No newline at end of file From 145a2f0fba3cbf0180bf5b6d391906109da4524d Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:17:46 -0400 Subject: [PATCH 27/47] File structure commit --- Homework 4/Part2_Queue.java | 3 +++ Homework 4/Part3_List.java | 3 +++ Homework 4/Part4_Map.java | 3 +++ Homework 4/Part5_Set.java | 3 +++ 4 files changed, 12 insertions(+) create mode 100644 Homework 4/Part2_Queue.java create mode 100644 Homework 4/Part3_List.java create mode 100644 Homework 4/Part4_Map.java create mode 100644 Homework 4/Part5_Set.java diff --git a/Homework 4/Part2_Queue.java b/Homework 4/Part2_Queue.java new file mode 100644 index 0000000..0ff5c32 --- /dev/null +++ b/Homework 4/Part2_Queue.java @@ -0,0 +1,3 @@ +public class Part2_Queue { + +} diff --git a/Homework 4/Part3_List.java b/Homework 4/Part3_List.java new file mode 100644 index 0000000..de69b69 --- /dev/null +++ b/Homework 4/Part3_List.java @@ -0,0 +1,3 @@ +public class Part3_List { + +} diff --git a/Homework 4/Part4_Map.java b/Homework 4/Part4_Map.java new file mode 100644 index 0000000..22438d1 --- /dev/null +++ b/Homework 4/Part4_Map.java @@ -0,0 +1,3 @@ +public class Part4_Map { + +} diff --git a/Homework 4/Part5_Set.java b/Homework 4/Part5_Set.java new file mode 100644 index 0000000..c851a52 --- /dev/null +++ b/Homework 4/Part5_Set.java @@ -0,0 +1,3 @@ +public class Part5_Set { + +} From aead415777a844092598196dc02ccb7436060d22 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:42:03 -0400 Subject: [PATCH 28/47] Added more test cased --- Homework 4/Part1_Stack.java | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/Homework 4/Part1_Stack.java b/Homework 4/Part1_Stack.java index 2b391f6..2736fb8 100644 --- a/Homework 4/Part1_Stack.java +++ b/Homework 4/Part1_Stack.java @@ -9,19 +9,31 @@ public static void main(String[] args) { //my main method that uses an array of Stack stack = new Stack<>(); // Test push() method - stack.push(10); - stack.push(20); - stack.push(30); + 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()); + 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()); + 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()); - + 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 (Exception e) { + System.out.println("Exception caught: " + e); // Expected behavior. + } // Add more test cases as needed... } } \ No newline at end of file From 3467b530fe8885a9d64f9f7cdc54e23387b27df5 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:45:04 -0400 Subject: [PATCH 29/47] Updated Part1_Stack.java to handle additional test cases and improve code readability --- Homework 4/Part1_Stack.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/Homework 4/Part1_Stack.java b/Homework 4/Part1_Stack.java index 2736fb8..e3bb2f2 100644 --- a/Homework 4/Part1_Stack.java +++ b/Homework 4/Part1_Stack.java @@ -1,5 +1,6 @@ // 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 @@ -31,9 +32,17 @@ public static void main(String[] args) { //my main method that uses an array of // Edge case: Trying to pop from an empty stack (will throw EmptyStackException) try { stack.pop(); // This should cause an exception - } catch (Exception e) { + } catch (EmptyStackException e) { System.out.println("Exception caught: " + e); // Expected behavior. } - // Add more test cases as needed... + // 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 } -} \ No newline at end of file + } From 1dbee9d40c239220da5d14037bfde38f7a82c779 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:48:40 -0400 Subject: [PATCH 30/47] Refactor Part1_Stack.java to improve peek() behavior --- Homework 4/Part1_Stack.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Homework 4/Part1_Stack.java b/Homework 4/Part1_Stack.java index e3bb2f2..5473dcf 100644 --- a/Homework 4/Part1_Stack.java +++ b/Homework 4/Part1_Stack.java @@ -43,6 +43,6 @@ public static void main(String[] args) { //my main method that uses an array of // 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 + System.out.println("Peek 2: " + stack.peek()); // still 40, not removed, unlike pop } } From 5d9f0e5ab29ae70e9906cf104e1fe5472f9ecb1c Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:53:58 -0400 Subject: [PATCH 31/47] Added queue test cases --- Homework 4/Part2_Queue.java | 59 +++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/Homework 4/Part2_Queue.java b/Homework 4/Part2_Queue.java index 0ff5c32..4b50a23 100644 --- a/Homework 4/Part2_Queue.java +++ b/Homework 4/Part2_Queue.java @@ -1,3 +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 From 78c35f7836d5159901769b8c44ec15057cb9e0fb Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:54:06 -0400 Subject: [PATCH 32/47] Added list test cases --- Homework 4/Part3_List.java | 78 +++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/Homework 4/Part3_List.java b/Homework 4/Part3_List.java index de69b69..7cd2baa 100644 --- a/Homework 4/Part3_List.java +++ b/Homework 4/Part3_List.java @@ -1,3 +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); + list.add(20); + list.add(30); + System.out.println("List after adds: " + list); + + // Test add() at specific index + System.out.println("\nTesting add(index, element):"); + list.add(1, 15); + System.out.println("List after adding 15 at index 1: " + list); + + // Test get() method + System.out.println("\nTesting get() method:"); + System.out.println("Element at index 1: " + list.get(1)); + + // Test set() method + System.out.println("\nTesting set() method:"); + list.set(2, 25); + System.out.println("List after setting index 2 to 25: " + list); + + // Test remove() methods + System.out.println("\nTesting remove() methods:"); + list.remove(1); // Remove by index + 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)); + System.out.println("Contains 15? " + list.contains(15)); + + // Test indexOf() method + System.out.println("\nTesting indexOf() method:"); + System.out.println("Index of 25: " + list.indexOf(25)); + System.out.println("Index of 99 (not in list): " + list.indexOf(99)); + + // Test iterator + System.out.println("\nTesting iterator:"); + Iterator iterator = list.iterator(); + System.out.print("Iterating through list: "); + while (iterator.hasNext()) { + System.out.print(iterator.next() + " "); + } + System.out.println(); + + // Test subList + list.add(35); + list.add(40); + System.out.println("\nTesting subList:"); + List subList = list.subList(1, 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 From 31368cb39704b7cbb46e429a475cf03e971ba5df Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 22:57:48 -0400 Subject: [PATCH 33/47] added more comments --- Homework 4/Part3_List.java | 44 +++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Homework 4/Part3_List.java b/Homework 4/Part3_List.java index 7cd2baa..0a3dd31 100644 --- a/Homework 4/Part3_List.java +++ b/Homework 4/Part3_List.java @@ -9,56 +9,56 @@ public static void main(String[] args) { // Test add() method System.out.println("Testing add() method:"); - list.add(10); - list.add(20); - list.add(30); - System.out.println("List after adds: " + list); + 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); - System.out.println("List after adding 15 at index 1: " + list); + 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)); + 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); - System.out.println("List after setting index 2 to 25: " + list); + 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 + 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)); - System.out.println("Contains 15? " + list.contains(15)); + 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)); - System.out.println("Index of 99 (not in list): " + list.indexOf(99)); + 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(); + Iterator iterator = list.iterator(); // Create an iterator we will use to iterate through the list System.out.print("Iterating through list: "); - while (iterator.hasNext()) { - System.out.print(iterator.next() + " "); + 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); - list.add(40); - System.out.println("\nTesting subList:"); - List subList = list.subList(1, 3); + 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 From f0c7ecc9c348ee6de073bd55609df65516b9a5d9 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 6 Oct 2024 23:01:03 -0400 Subject: [PATCH 34/47] Refactor Part4_Map.java and Part5_Set.java to add test cases and improve code readability --- Homework 4/Part4_Map.java | 73 ++++++++++++++++++++++++++++++++- Homework 4/Part5_Set.java | 85 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 154 insertions(+), 4 deletions(-) diff --git a/Homework 4/Part4_Map.java b/Homework 4/Part4_Map.java index 22438d1..0f96475 100644 --- a/Homework 4/Part4_Map.java +++ b/Homework 4/Part4_Map.java @@ -1,3 +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/Homework 4/Part5_Set.java b/Homework 4/Part5_Set.java index c851a52..88b144a 100644 --- a/Homework 4/Part5_Set.java +++ b/Homework 4/Part5_Set.java @@ -1,3 +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 From cd22d2cd63520e4d6f442b80bbe2affd1814b266 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 19:14:21 -0400 Subject: [PATCH 35/47] Created HashMapImplementation.java --- Homework 5/HashMapImplementation.java | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Homework 5/HashMapImplementation.java diff --git a/Homework 5/HashMapImplementation.java b/Homework 5/HashMapImplementation.java new file mode 100644 index 0000000..3c0d8b3 --- /dev/null +++ b/Homework 5/HashMapImplementation.java @@ -0,0 +1,3 @@ +public class HashMapImplementation { + +} From a65af31524eb3f57b2d1998e08374a5be559270a Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 19:21:51 -0400 Subject: [PATCH 36/47] Add HashMap import and create HashMap object for word count --- Homework 5/HashMapImplementation.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Homework 5/HashMapImplementation.java b/Homework 5/HashMapImplementation.java index 3c0d8b3..ac423d9 100644 --- a/Homework 5/HashMapImplementation.java +++ b/Homework 5/HashMapImplementation.java @@ -1,3 +1,7 @@ +import java.util.HashMap; + + public class HashMapImplementation { + private HashMap wordcount; //creating a hashmap object to store the word count } From 6a81dc9dc5f8837a25042b4063c085ea5caee1ef Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 19:51:11 -0400 Subject: [PATCH 37/47] Refactor HashMapImplementation.java to improve code readability and add word count functionality --- Homework 5/HashMapImplementation.java | 80 ++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/Homework 5/HashMapImplementation.java b/Homework 5/HashMapImplementation.java index ac423d9..d03a647 100644 --- a/Homework 5/HashMapImplementation.java +++ b/Homework 5/HashMapImplementation.java @@ -1,7 +1,81 @@ import java.util.HashMap; - +import java.util.Map; public class HashMapImplementation { - private HashMap wordcount; //creating a hashmap object to store the word count + // 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"; + 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 From 9165da71ca6031769e302e926e37d7e64304f19a Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 19:58:00 -0400 Subject: [PATCH 38/47] Changed test text a bit --- Homework 5/HashMapImplementation.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Homework 5/HashMapImplementation.java b/Homework 5/HashMapImplementation.java index d03a647..1452162 100644 --- a/Homework 5/HashMapImplementation.java +++ b/Homework 5/HashMapImplementation.java @@ -14,7 +14,7 @@ public HashMapImplementation() { 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"; + 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(); From ee0169c6b7cf25356d39df975fb0538d276f2ec8 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 23:05:43 -0400 Subject: [PATCH 39/47] HashMap for a word counter but using seperate chaining this time --- .../SeparateChainingImplementation.java | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 Homework 5/SeparateChainingImplementation.java diff --git a/Homework 5/SeparateChainingImplementation.java b/Homework 5/SeparateChainingImplementation.java new file mode 100644 index 0000000..64ce531 --- /dev/null +++ b/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 From 40b104cb967173defb8cdd6153ee4e406b7017bc Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 23:08:51 -0400 Subject: [PATCH 40/47] Linear Probing Implementation --- Homework 5/LinearProbingImplementation.java | 95 +++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Homework 5/LinearProbingImplementation.java diff --git a/Homework 5/LinearProbingImplementation.java b/Homework 5/LinearProbingImplementation.java new file mode 100644 index 0000000..09d0e59 --- /dev/null +++ b/Homework 5/LinearProbingImplementation.java @@ -0,0 +1,95 @@ +public class LinearProbingImplementation { + private static final int TABLE_SIZE = 1009; // Prime number slightly larger than 1000 + private WordEntry[] table; + private int size; + + private static class WordEntry { + String word; + int count; + + WordEntry(String word) { + this.word = word; + this.count = 1; + } + } + + public LinearProbingImplementation() { + table = new WordEntry[TABLE_SIZE]; + size = 0; + } + + // Hash function using first letter as specified in assignment + private int hash(String word) { + if (word == null || word.isEmpty()) return 0; + // Using first letter and word length to reduce collisions + return ((word.charAt(0) - 'a') * 31 + word.length()) % TABLE_SIZE; + } + + public void put(String word) { + if (size >= TABLE_SIZE) { + throw new IllegalStateException("Hash table is full"); + } + + int index = hash(word); + + // Linear probing until we find an empty slot or the word + while (table[index] != null) { + if (table[index].word.equals(word)) { + table[index].count++; + return; + } + index = (index + 1) % TABLE_SIZE; + } + + // Found empty slot, insert new entry + table[index] = new WordEntry(word); + size++; + } + + public Integer get(String word) { + int index = hash(word); + + // Linear probe until we find the word or an empty slot + int startIndex = index; + while (table[index] != null) { + if (table[index].word.equals(word)) { + return table[index].count; + } + index = (index + 1) % TABLE_SIZE; + if (index == startIndex) break; // Wrapped around table + } + + return null; // Word not found + } + + public int size() { + return size; + } + + public void processText(String text) { + String[] words = text.split(" "); + for (String word : words) { + put(word); + } + } + + public void displayCounts() { + System.out.println("Word Counts (Linear Probing):"); + System.out.println("---------------------------"); + for (WordEntry entry : table) { + if (entry != null) { + System.out.printf("%-20s: %d%n", entry.word, entry.count); + } + } + } + + public static void main(String[] args) { + LinearProbingImplementation counter = new LinearProbingImplementation(); + 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"; + counter.processText(text); + counter.displayCounts(); + + System.out.println("\nCount for word 'test': " + counter.get("test")); + System.out.println("Total unique words: " + counter.size()); + } +} \ No newline at end of file From 3b18bca75d8b6fcce6aa52070b75c29eda22fee0 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sun, 27 Oct 2024 23:09:58 -0400 Subject: [PATCH 41/47] Added more comments explaining the new code --- Homework 5/LinearProbingImplementation.java | 52 +++++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/Homework 5/LinearProbingImplementation.java b/Homework 5/LinearProbingImplementation.java index 09d0e59..703a934 100644 --- a/Homework 5/LinearProbingImplementation.java +++ b/Homework 5/LinearProbingImplementation.java @@ -1,94 +1,128 @@ public class LinearProbingImplementation { - private static final int TABLE_SIZE = 1009; // Prime number slightly larger than 1000 + // 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 as specified in assignment + // 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 to reduce collisions + // 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 until we find an empty slot or the 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 + // found empty slot, insert new entry table[index] = new WordEntry(word); - size++; + 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); - // Linear probe until we find the word or an empty slot + // 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; - if (index == startIndex) break; // Wrapped around table + // break if we've wrapped around to where we started + if (index == startIndex) break; } - return null; // Word not found + // 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()); } From ef915b96501aa7d90bd6cc8bbadef71ed9c97e8b Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 11 Dec 2024 19:25:04 -0500 Subject: [PATCH 42/47] .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) 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 From 2dca372652e8aeea2d741d8ba659a893abc6eebd Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 11 Dec 2024 19:45:06 -0500 Subject: [PATCH 43/47] binarySearch --- src/Main.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/Main.java diff --git a/src/Main.java b/src/Main.java new file mode 100644 index 0000000..ab582c3 --- /dev/null +++ b/src/Main.java @@ -0,0 +1,21 @@ +public class Main { + 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); + } + } + + +} \ No newline at end of file From 07e05da6559415b9fe6831552f727b0241aa3b52 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Wed, 11 Dec 2024 21:56:42 -0500 Subject: [PATCH 44/47] reverse fuction --- src/Main.java | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Main.java b/src/Main.java index ab582c3..b5aa8c3 100644 --- a/src/Main.java +++ b/src/Main.java @@ -1,21 +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; + int mid = left + (right - left) / 2; //Check the middle element to see if it is the target - if (arr[mid] == target){ - return mid; + if (arr[mid] == target){ + return mid; } - if (target < arr[mid]) { - return binarySearch(arr, left,mid -1, target); + if (target < arr[mid]) { + return binarySearch(arr, left,mid -1, target); } - else{ - return binarySearch(arr, mid + 1, right, 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 From 83a7c08afd0658ede02a2c3aba92848c24f0094b Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sat, 21 Dec 2024 17:57:26 -0500 Subject: [PATCH 45/47] Moved old files into ./OLD --- {Homework 4 => OLD!/Homework 4}/Part1_Stack.java | 0 {Homework 4 => OLD!/Homework 4}/Part2_Queue.java | 0 {Homework 4 => OLD!/Homework 4}/Part3_List.java | 0 {Homework 4 => OLD!/Homework 4}/Part4_Map.java | 0 {Homework 4 => OLD!/Homework 4}/Part5_Set.java | 0 {Homework 5 => OLD!/Homework 5}/HashMapImplementation.java | 0 {Homework 5 => OLD!/Homework 5}/LinearProbingImplementation.java | 0 .../Homework 5}/SeparateChainingImplementation.java | 0 {source fles => OLD!/source fles}/ArrayStack.java | 0 {source fles => OLD!/source fles}/DoublyLinkedList.java | 0 {source fles => OLD!/source fles}/LinkedListStack.java | 0 {source fles => OLD!/source fles}/SinglyLinkedList.java | 0 {source fles => OLD!/source fles}/queueArray.java | 0 {source fles => OLD!/source fles}/queueList.java | 0 {src => OLD!/src}/Main.java | 0 15 files changed, 0 insertions(+), 0 deletions(-) rename {Homework 4 => OLD!/Homework 4}/Part1_Stack.java (100%) rename {Homework 4 => OLD!/Homework 4}/Part2_Queue.java (100%) rename {Homework 4 => OLD!/Homework 4}/Part3_List.java (100%) rename {Homework 4 => OLD!/Homework 4}/Part4_Map.java (100%) rename {Homework 4 => OLD!/Homework 4}/Part5_Set.java (100%) rename {Homework 5 => OLD!/Homework 5}/HashMapImplementation.java (100%) rename {Homework 5 => OLD!/Homework 5}/LinearProbingImplementation.java (100%) rename {Homework 5 => OLD!/Homework 5}/SeparateChainingImplementation.java (100%) rename {source fles => OLD!/source fles}/ArrayStack.java (100%) rename {source fles => OLD!/source fles}/DoublyLinkedList.java (100%) rename {source fles => OLD!/source fles}/LinkedListStack.java (100%) rename {source fles => OLD!/source fles}/SinglyLinkedList.java (100%) rename {source fles => OLD!/source fles}/queueArray.java (100%) rename {source fles => OLD!/source fles}/queueList.java (100%) rename {src => OLD!/src}/Main.java (100%) diff --git a/Homework 4/Part1_Stack.java b/OLD!/Homework 4/Part1_Stack.java similarity index 100% rename from Homework 4/Part1_Stack.java rename to OLD!/Homework 4/Part1_Stack.java diff --git a/Homework 4/Part2_Queue.java b/OLD!/Homework 4/Part2_Queue.java similarity index 100% rename from Homework 4/Part2_Queue.java rename to OLD!/Homework 4/Part2_Queue.java diff --git a/Homework 4/Part3_List.java b/OLD!/Homework 4/Part3_List.java similarity index 100% rename from Homework 4/Part3_List.java rename to OLD!/Homework 4/Part3_List.java diff --git a/Homework 4/Part4_Map.java b/OLD!/Homework 4/Part4_Map.java similarity index 100% rename from Homework 4/Part4_Map.java rename to OLD!/Homework 4/Part4_Map.java diff --git a/Homework 4/Part5_Set.java b/OLD!/Homework 4/Part5_Set.java similarity index 100% rename from Homework 4/Part5_Set.java rename to OLD!/Homework 4/Part5_Set.java diff --git a/Homework 5/HashMapImplementation.java b/OLD!/Homework 5/HashMapImplementation.java similarity index 100% rename from Homework 5/HashMapImplementation.java rename to OLD!/Homework 5/HashMapImplementation.java diff --git a/Homework 5/LinearProbingImplementation.java b/OLD!/Homework 5/LinearProbingImplementation.java similarity index 100% rename from Homework 5/LinearProbingImplementation.java rename to OLD!/Homework 5/LinearProbingImplementation.java diff --git a/Homework 5/SeparateChainingImplementation.java b/OLD!/Homework 5/SeparateChainingImplementation.java similarity index 100% rename from Homework 5/SeparateChainingImplementation.java rename to OLD!/Homework 5/SeparateChainingImplementation.java diff --git a/source fles/ArrayStack.java b/OLD!/source fles/ArrayStack.java similarity index 100% rename from source fles/ArrayStack.java rename to OLD!/source fles/ArrayStack.java 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/source fles/LinkedListStack.java b/OLD!/source fles/LinkedListStack.java similarity index 100% rename from source fles/LinkedListStack.java rename to OLD!/source fles/LinkedListStack.java 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/source fles/queueArray.java b/OLD!/source fles/queueArray.java similarity index 100% rename from source fles/queueArray.java rename to OLD!/source fles/queueArray.java diff --git a/source fles/queueList.java b/OLD!/source fles/queueList.java similarity index 100% rename from source fles/queueList.java rename to OLD!/source fles/queueList.java diff --git a/src/Main.java b/OLD!/src/Main.java similarity index 100% rename from src/Main.java rename to OLD!/src/Main.java From b1a5bf21673f512cd2b81e125e7429f80e982436 Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sat, 21 Dec 2024 17:58:28 -0500 Subject: [PATCH 46/47] New BinarySearch file --- src/BinarySearch.java | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/BinarySearch.java diff --git a/src/BinarySearch.java b/src/BinarySearch.java new file mode 100644 index 0000000..40b12fa --- /dev/null +++ b/src/BinarySearch.java @@ -0,0 +1,3 @@ +public class BinarySearch { + +} From 1be100d58ebb0a67ff6d96c8a4d3f8fd2505c90a Mon Sep 17 00:00:00 2001 From: Brock Jenkinson Date: Sat, 21 Dec 2024 17:58:41 -0500 Subject: [PATCH 47/47] Implement binary search algorithm with recursive helper function and main method for testing --- src/BinarySearch.java | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/BinarySearch.java b/src/BinarySearch.java index 40b12fa..b1cb35c 100644 --- a/src/BinarySearch.java +++ b/src/BinarySearch.java @@ -1,3 +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