diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..816a04449 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,140 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "java", + "name": "DepthFirstTester", + "request": "launch", + "mainClass": "DepthFirstTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "TreeDemo", + "request": "launch", + "mainClass": "TreeDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "TreeTester", + "request": "launch", + "mainClass": "TreeTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "QueueTester", + "request": "launch", + "mainClass": "QueueTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "SizeTester", + "request": "launch", + "mainClass": "SizeTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "ListTester", + "request": "launch", + "mainClass": "ListTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "HTMLChecker", + "request": "launch", + "mainClass": "HTMLChecker", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "FloodFillTester", + "request": "launch", + "mainClass": "FloodFillTester", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "DrivewayDemo", + "request": "launch", + "mainClass": "DrivewayDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "Current File", + "request": "launch", + "mainClass": "${file}" + }, + { + "type": "java", + "name": "FirstLetterMap", + "request": "launch", + "mainClass": "FirstLetterMap", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "Gradebook", + "request": "launch", + "mainClass": "Gradebook", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "ListDemo", + "request": "launch", + "mainClass": "ListDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "MapDemo", + "request": "launch", + "mainClass": "MapDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "PriorityQueueDemo", + "request": "launch", + "mainClass": "PriorityQueueDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "QueueDemo", + "request": "launch", + "mainClass": "QueueDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "StackDemo", + "request": "launch", + "mainClass": "StackDemo", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "SudokuSolver", + "request": "launch", + "mainClass": "SudokuSolver", + "projectName": "data-structures_addf3fee" + }, + { + "type": "java", + "name": "WordAnalysis", + "request": "launch", + "mainClass": "WordAnalysis", + "projectName": "data-structures_addf3fee" + } + ] +} \ No newline at end of file diff --git a/Chapter 15 Activities/Downsize/src/Business.java b/Chapter 15 Activities/Downsize/src/Business.java index 0769e2634..6f64de50e 100644 --- a/Chapter 15 Activities/Downsize/src/Business.java +++ b/Chapter 15 Activities/Downsize/src/Business.java @@ -13,6 +13,6 @@ public class Business */ public static void downsize(LinkedList employeeNames, int n) { - ... + } } diff --git a/Chapter 15 Activities/Driveway/src/Driveway.java b/Chapter 15 Activities/Driveway/src/Driveway.java index 64c94cfc1..3dbcf58b9 100644 --- a/Chapter 15 Activities/Driveway/src/Driveway.java +++ b/Chapter 15 Activities/Driveway/src/Driveway.java @@ -10,10 +10,12 @@ public class Driveway /** * Stack representing the cars in the driveway. */ + private Stack driveway; /** * Stack representing the cars in the street. */ + private Stack street; /** @@ -21,8 +23,8 @@ public class Driveway */ public Driveway() { - // Complete the constructor - ... + driveway = new Stack<>(); + street= new Stack<>(); } @@ -35,7 +37,7 @@ public Driveway() public void add(int licensePlate) { // Complete this method - ... + driveway.push(licensePlate); } @@ -48,23 +50,32 @@ public void add(int licensePlate) public void remove(int licensePlate) { // Complete this method - ... - + while (!driveway.isEmpty() && driveway.peek() != licensePlate) { + int car = driveway.pop(); + street.push(car);} - } + if (!driveway.isEmpty() && driveway.peek() == licensePlate) { + driveway.pop();} + +//after a car is taken out, the ones on the street are always returned to the driveway + while (!street.isEmpty()) { + int car = street.pop(); + driveway.push(car);}} /** * Prints the driveway and street details to the screen. */ public void print() - { - System.out.println("In Driveway, starting at first in (one license plate per line):"); - // Print the cars in the driveway here - ... - - System.out.println("In Street, starting at first in (one license plate per line):"); - // Print the cars in the street here - ... +{ + System.out.println("In Driveway, starting at first in (one license plate per line):"); + for (int car : driveway) { + System.out.println(car); + } + System.out.println("In Street, starting at first in (one license plate per line):"); + for (int car : street) { + System.out.println(car); } } + +} diff --git a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java index 826e6eb93..a693f8434 100644 --- a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java +++ b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/FirstLetterMap.java @@ -12,13 +12,12 @@ public class FirstLetterMap { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/FirstLetterMap/FirstLetterMap1/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here - ... + Map> firstLetterMap = new TreeMap<>(); while (in.hasNext()) { @@ -27,13 +26,23 @@ public static void main(String[] args) // Update the map here // Use the Java 8 merge method - . . . + if (word.length() > 0) { + + // Use the Java 8 merge method to update the map + firstLetterMap.merge(c, new TreeSet<>(Set.of(word)), (existingSet, newSet) -> { + existingSet.addAll(newSet); + return existingSet; + }); + } } // Print the map here in this form // a: [a, able, aardvark] - . . . + + for (Map.Entry> entry : firstLetterMap.entrySet()) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); @@ -53,5 +62,5 @@ public static String clean(String s) } return r.toLowerCase(); } - + //in.close(); } diff --git a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java index d1e2075e4..486de0a2f 100644 --- a/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java +++ b/Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/FirstLetterMap.java @@ -4,21 +4,20 @@ * Read all words from a file and add them to a map * whose keys are the first letters of the words and * whose values are sets of words that start with - * that same letter. Then print out the word sets in - * alphabetical order. Update the map by modifying - * Worked Example 15.1. + * that same letter. + * Then print out the word sets in alphabetical order. + * Use the Java 8 merge() feature. */ public class FirstLetterMap { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/FirstLetterMap/FirstLetterMap2/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here - ... + Map> firstLetterMap = new TreeMap<>(); while (in.hasNext()) { @@ -26,15 +25,29 @@ public static void main(String[] args) Character c = word.charAt(0); // Update the map here - // Modify Worked Example 15.1 - . . . + if (word.length() > 0) { - - } + if (firstLetterMap.containsKey(c)) { + // If the key exists, add the word to the corresponding set + Set existingSet = firstLetterMap.get(c); + existingSet.add(word); // Add word to the set + } else { + // If the key does not exist, create a new set with the word + Set newSet = new TreeSet<>(); // TreeSet to automatically sort + newSet.add(word); + firstLetterMap.put(c, newSet); // Put the new set in the map + } + } + } + // Print the map here in this form // a: [a, able, aardvark] - . . . + + + for (Map.Entry> entry : firstLetterMap.entrySet()) { + System.out.println(entry.getKey() + ": " + entry.getValue()); + } } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); @@ -54,4 +67,5 @@ public static String clean(String s) } return r.toLowerCase(); } + //in.close(); } diff --git a/Chapter 15 Activities/FloodFill/src/Grid.java b/Chapter 15 Activities/FloodFill/src/Grid.java index 1280e3eb3..8c55c0644 100644 --- a/Chapter 15 Activities/FloodFill/src/Grid.java +++ b/Chapter 15 Activities/FloodFill/src/Grid.java @@ -1,16 +1,53 @@ +import java.util.Stack; + public class Grid { private static final int SIZE = 10; int[][] pixels = new int[SIZE][SIZE]; - . . . + + + + private static class Pair { + int row, col; + Pair(int row, int col) { + this.row = row; + this.col = col; + } + } /** * Flood fill, starting with the given row and column. */ - public void floodfill(int row, int column) + public void floodfill(int startRow, int startCol) { - . . . + Stack stack = new Stack<>(); + int fillValue = 1; + + stack.push(new Pair(startRow, startCol)); + + while (!stack.isEmpty()) { + Pair current = stack.pop(); + int row = current.row; + int col = current.col; + + if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) { + continue; + } + + if (pixels[row][col] != 0) { + continue; + } + + pixels[row][col] = fillValue; + fillValue++; + + stack.push(new Pair(row - 1, col)); // North + stack.push(new Pair(row, col + 1)); // East + stack.push(new Pair(row + 1, col)); // South + stack.push(new Pair(row, col - 1)); // West + } } + @Override public String toString() diff --git a/Chapter 15 Activities/FloodFillQueue/src/Grid.java b/Chapter 15 Activities/FloodFillQueue/src/Grid.java index 181f97b00..0529037ad 100644 --- a/Chapter 15 Activities/FloodFillQueue/src/Grid.java +++ b/Chapter 15 Activities/FloodFillQueue/src/Grid.java @@ -1,25 +1,52 @@ -. . . -public class Grid -{ +import java.util.LinkedList; +import java.util.Queue; + +public class Grid { private static final int SIZE = 10; int[][] pixels = new int[SIZE][SIZE]; - . . . /** * Flood fill, starting with the given row and column. - */ - public void floodfill(int row, int column) - { - . . . + */ + public void floodfill(int startRow, int startCol) { + Queue queue = new LinkedList<>(); + int fillValue = 1; + + queue.add(new Pair(startRow, startCol)); + + while (!queue.isEmpty()) { + Pair current = queue.remove(); + int row = current.getRow(); + int col = current.getColumn(); + + // Bounds check + if (row < 0 || row >= SIZE || col < 0 || col >= SIZE) { + continue; + } + + // Already filled + if (pixels[row][col] != 0) { + continue; + } + + // Fill pixel + pixels[row][col] = fillValue++; + + // Enqueue neighbors in N, E, S, W order + queue.add(new Pair(row - 1, col)); // North + queue.add(new Pair(row, col + 1)); // East + queue.add(new Pair(row + 1, col)); // South + queue.add(new Pair(row, col - 1)); // West + } } - public String toString() - { + @Override + public String toString() { String r = ""; - for (int i = 0; i < SIZE; i++) - { - for (int j = 0; j < SIZE; j++) - r = r + String.format("%3d", pixels[i][j]); + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + r = r + String.format("%4d", pixels[i][j]); + } r = r + "\n"; } return r; diff --git a/Chapter 15 Activities/Gradebook/src/Gradebook.java b/Chapter 15 Activities/Gradebook/src/Gradebook.java index 3e4b59f92..738a14ca2 100644 --- a/Chapter 15 Activities/Gradebook/src/Gradebook.java +++ b/Chapter 15 Activities/Gradebook/src/Gradebook.java @@ -1,40 +1,68 @@ -import java.util.Scanner; -. . . + /** - * A program to add, remove, modify or print - * student names and grades. + * Shriya Kunnanath + * 9/14/25 + * gradebook program */ -public class Gradebook -{ - public static void main(String[] args) - { - Scanner in = new Scanner(System.in); +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import java.util.Set; - . . . +public class Gradebook { + public static void main(String[] args) { + // Create scanner and gradebook map + Scanner in = new Scanner(System.in); + Map gradebook = new HashMap<>(); + // Loop until user chooses to quit boolean done = false; - while(!done) - { + + while (!done) { + // Prompt for user action System.out.println("A)dd R)emove M)odify P)rint Q)uit"); String input = in.next().toUpperCase(); - if (input.equals("Q")) - { + + // Quit the program + if (input.equals("Q")) { done = true; - } else if (input.equals("A")) - { - . . . - - } else if (input.equals("R")) - { - . . . - } else if (input.equals("M")) - { - . . . - } else if (input.equalsIgnoreCase("P")) - { - . . . - } else - { + + // Add a student and their grade + } else if (input.equals("A")) { + String name = in.next(); + String grade = in.next(); + gradebook.put(name, grade); + + // Remove a student + } else if (input.equals("R")) { + String name = in.next(); + if (gradebook.containsKey(name)) { + gradebook.remove(name); + } + + // Modify a student's grade + } else if (input.equals("M")) { + String name = in.next(); + if (gradebook.containsKey(name)) { + String grade = in.next(); + gradebook.put(name, grade); + } + + // Print all students and grades in alphabetical order + } else if (input.equals("P")) { + System.out.println(); + List names = new ArrayList<>(gradebook.keySet()); + Collections.sort(names); + + for (String name : names) { + System.out.println(name + ": " + gradebook.get(name)); + } + System.out.println(); + + } else { done = true; } } diff --git a/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java b/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java index 87fee8638..641a7003e 100644 --- a/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java +++ b/Chapter 15 Activities/HTMLChecker/src/HTMLChecker.java @@ -2,33 +2,54 @@ import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Stack; + /** - * Write a program that checks whether a sequence of HTML tags - * is properly nested. For each opening tag, such as

, there - * must be a closing tag

. A tag such as

may have other - * tags inside, for example

- *

- * The inner tags must be closed before the outer ones. - * Your program should process a file containing tags. - * For simplicity, assume that the tags are separated by - * spaces, and that there is no text inside the tags. -*/ -public class HTMLChecker -{ - public static void main(String[] args) - { - String filename = "src/TagSample1.html"; + * Checks whether HTML tags are properly nested. + */ +public class HTMLChecker { + public static void main(String[] args) { + String filename = "Chapter 15 Activities/HTMLChecker/src/TagSample1.html"; + Stack tagStack = new Stack<>(); + boolean check = true; + + try (Scanner in = new Scanner(new File(filename))) { + while (in.hasNext()) { + String tag = in.next(); - try (Scanner in = new Scanner(new File(filename))) - { - // Your code goes here - . . . + if (tag.startsWith(" with no opening tag."); + check = false; + break; + } + String open = tagStack.pop(); + if (!open.equals(close)) { + System.out.println("Error: Tag mismatch. Expected , found ."); + check = false; + break; + } + } else if (tag.startsWith("<")) { + // Opening tag + String open = tag.substring(1, tag.length() - 1); + tagStack.push(open); + } + } - } catch (FileNotFoundException e) - { + if (check) { + if (tagStack.isEmpty()) { + System.out.println("Tags are properly nested."); + } else { + System.out.println("Error: Unclosed tags remaining:"); + while (!tagStack.isEmpty()) { + System.out.println("Unclosed: <" + tagStack.pop() + ">"); + } + } + } + + } catch (FileNotFoundException e) { System.out.println("Cannot open: " + filename); } - } } diff --git a/Chapter 15 Activities/Reverse/src/ListUtil.java b/Chapter 15 Activities/Reverse/src/ListUtil.java index d3e8e9f83..ac43b98ac 100644 --- a/Chapter 15 Activities/Reverse/src/ListUtil.java +++ b/Chapter 15 Activities/Reverse/src/ListUtil.java @@ -1,4 +1,13 @@ +/* + * Shriya Kunnanath + * 8/29/2025 + * Software Engineering 1 + * Reverse List Program + */ + +import java.util.ArrayList; import java.util.LinkedList; +import java.util.ListIterator; /** * This class supplies a utility method to reverse the entries in a linked list. @@ -12,6 +21,19 @@ public class ListUtil */ public static void reverse(LinkedList strings) { - ... + //made a list iterator and arraylist to set up the reversed list and an iterator to go through the linkedlist + ListIterator iterator = strings.listIterator(); + ArrayList tempList = new ArrayList<>(); + + //the while loop goes through the list + while(iterator.hasNext()){ + iterator.next(); + + //the first value is added to templist and then removed from the original linkedlist + tempList.add(0, strings.getFirst()); + iterator.remove(); + } + //all the content from tempList is transfered into the empty strings linkedlist + strings.addAll(tempList); } } \ No newline at end of file diff --git a/Chapter 15 Activities/Reverse/src/ReverseTester.java b/Chapter 15 Activities/Reverse/src/ReverseTester.java index 0a710b1aa..0b1c8b45a 100644 --- a/Chapter 15 Activities/Reverse/src/ReverseTester.java +++ b/Chapter 15 Activities/Reverse/src/ReverseTester.java @@ -1,4 +1,6 @@ +import java.util.ArrayList; import java.util.LinkedList; +import java.util.ListIterator; /** diff --git a/Chapter 15 Activities/Sieve/src/Sieve.java b/Chapter 15 Activities/Sieve/src/Sieve.java index 297f5da6a..7c809e2d2 100644 --- a/Chapter 15 Activities/Sieve/src/Sieve.java +++ b/Chapter 15 Activities/Sieve/src/Sieve.java @@ -1,7 +1,12 @@ +import java.util.ArrayList; +import java.util.HashSet; import java.util.Scanner; +import java.util.Set; /** + * Shriya Kunnanath + * 9/8/25 * A program that implements the sieve of Eratosthenes. */ public class Sieve @@ -11,15 +16,35 @@ public static void main(String[] args) Scanner in = new Scanner(System.in); System.out.println("Compute primes up to which integer?"); int n = in.nextInt(); + - // Your work goes here - . . . - + Set prime = new HashSet<>(); + for (int i=2; i<= n; i++){ + prime.add(i); + } + //made an arraylist that has the numbers in the range from the original value of n + ArrayList numbers = new ArrayList<>(prime); + // Loop through numbers starting from 2 up to the square root of n + for (int i = 2; i * i <= n; i++) { + // Only proceed if 'i' is still in the set + if (prime.contains(i)) { + // Loop through all multiples of 'i' starting from i*2 up to n + for (int j = i * 2; j <= n; j += i) { + // Remove 'j' from the set since it's a multiple of 'i' and not a prime + prime.remove(j); + } + } +} + //print prime numbers + numbers = new ArrayList<>(prime); + numbers.sort(null); // sort the list + System.out.println(numbers); + System.out.println(prime); } } diff --git a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java index 0a3f44a4e..452920047 100644 --- a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java +++ b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap.java @@ -12,26 +12,30 @@ public class StringLengthMap { public static void main(String[] args) throws FileNotFoundException { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/StringLengthMap/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - - // Create your map here - + Map freq = new TreeMap<>(); while (in.hasNext()) { String word = clean(in.next()); Integer len = word.length(); - - // Update the map here - // Modify Worked Example 15.1 - - - + if(word.length()>0){ + if(freq.containsKey(len)){ + String current = freq.get(len); + freq.put(len, current +","+ word); + } + else{ + freq.put(len,word); + } + + + }} + for (Integer len : freq.keySet()) { + System.out.println(len + ": " + freq.get(len)); } - // Print the strings, in increasing order of their length // Use this format: 1: i, a, i } catch (FileNotFoundException e) diff --git a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java index bfc5eff95..79ea3f90f 100644 --- a/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java +++ b/Chapter 15 Activities/StringLengthMap/src/StringLengthMap2.java @@ -12,26 +12,33 @@ public class StringLengthMap2 { public static void main(String[] args) { - String filename = "src/test1.txt"; + String filename = "Chapter 15 Activities/StringLengthMap/src/test1.txt"; try (Scanner in = new Scanner(new File(filename))) { - // Create your map here + Map freq = new TreeMap<>(); while (in.hasNext()) { String word = clean(in.next()); Integer len = word.length(); + if (word.length() > 0) { + // Use merge to add or update the entry + freq.merge(len, word, (existing, newWord) -> existing + "," + newWord);} + } + // Update the map here // Use the Java 8 merge() method + + for (Integer len : freq.keySet()) { + System.out.println(len + ": " + freq.get(len)); } - // Print the strings, in increasing order of their length // Use this format: 1: i, a, i } catch (FileNotFoundException e) diff --git a/Chapter 15 Activities/Sudoku/src/SudokuSolver.java b/Chapter 15 Activities/Sudoku/src/SudokuSolver.java index b24090a24..58b3c5402 100644 --- a/Chapter 15 Activities/Sudoku/src/SudokuSolver.java +++ b/Chapter 15 Activities/Sudoku/src/SudokuSolver.java @@ -13,6 +13,8 @@ public class SudokuSolver { public SudokuSolver(String fileName) { // read the puzzle file + System.out.println(System.getProperty("user.dir")); + try (Scanner in = new Scanner(new File(fileName))) { this.grid = new int[N][N]; @@ -35,11 +37,64 @@ public SudokuSolver(String fileName) { System.out.println("Cannot open: " + fileName); } + Set losRow = new HashSet<>(); + this.rows = new ArrayList<>(); + //losRow.size[N]; + //System.out.println(grid); // create the list of sets for each row (this.rows) + for (int i = 0; i < N; i++) { + losRow = new HashSet<>(); + //put each row in a set and then put it in a list. + for (int j = 0; j < N; j++) { + losRow.add(this.grid[i][j]); + + //System.out.print(losRow); + //rows.add(losRow); + //System.out.println(); + } + this.rows.add(losRow); + //System.out.println(losRow); + + //losRow = new HashSet<>(); + + + + //System.out.println(rows); + + + } + // ... // create the list of sets for each col (this.cols) // ... + //Set losCol = new HashSet<>(); + this.cols = new ArrayList<>(); + + for (int j = 0; j < N; j++) { + //put each row in a set and then put it in a list. + Set losCol = new HashSet<>(); + for (int i = 0; i < N; i++) { + + losCol.add(this.grid[i][j]); + + //System.out.print(losCol); + //rows.add(losRow); + //System.out.println(); + } + this.cols.add(losCol); + //System.out.println(losCol); + + //losCol = new HashSet<>(); + + + + //System.out.println(rows); + + + } + + // create the list of sets for each square (this.squares) /* the squares are added to the list row-by-row: @@ -49,9 +104,42 @@ public SudokuSolver(String fileName) { */ // ... + //Set SquareRow = new HashSet<>(); + + this.squares = new ArrayList<>(); + for (int squareRow = 0; squareRow < M; squareRow++) { + for (int squareCol = 0; squareCol < M; squareCol++) { + Set squareSet = new HashSet<>(); + for (int row = squareRow * M; row < (squareRow + 1) * M; row++) { + for (int col = squareCol * M; col < (squareCol + 1) * M; col++) { + if (this.grid[row][col] != 0) { + squareSet.add(this.grid[row][col]); + } + } + } + this.squares.add(squareSet); + } +} + + + + //System.out.println(rows); + + + + + + + // create a hash set for [1..9] (this.nums) // ... + this.nums = new HashSet<>(); + for (int i = 1; i <= N; i++) { + this.nums.add(i); + } + + // visually inspect that all the sets are correct for (int row = 0; row < N; row++) { System.out.println("row " + row + ": " + this.rows.get(row)); @@ -96,7 +184,17 @@ corresponding to nextRow, nextCol, and the corresponding square (use the */ Set possibleNums = new HashSet(); possibleNums.addAll(this.nums); - + + //remove nums alr in row + possibleNums.removeAll(this.rows.get(nextRow)); + + // remove nums already in the column + possibleNums.removeAll(this.cols.get(nextCol)); + + // calculate square index and remove numbers alr in square + int squareIndex = (nextRow / M) * M + (nextCol / M); + possibleNums.removeAll(this.squares.get(squareIndex)); + // ... // if there are no possible numbers, we cannot solve the board in its current state @@ -106,22 +204,26 @@ corresponding to nextRow, nextCol, and the corresponding square (use the // try each possible number for (Integer possibleNum : possibleNums) { - // update the grid and all three corresponding sets with possibleNum - // ... - - // recursively solve the board - if (this.solve()) { - // the board is solved! - return true; - } else { - /* - Undo the move before trying another possible number by setting the corresponding - element in the grid back to 0 and removing possibleNum from all three corresponding - sets. - */ - // ... - } - } + // Update the grid and all three corresponding sets with possibleNum + this.grid[nextRow][nextCol] = possibleNum; + this.rows.get(nextRow).add(possibleNum); + this.cols.get(nextCol).add(possibleNum); + //int squareIndex = (nextRow / M) * M + (nextCol / M); + this.squares.get(squareIndex).add(possibleNum); + + // Recursively solve the board + if (this.solve()) { + // The board is solved! + return true; + } else { + // Undo the move before trying another possible number + this.grid[nextRow][nextCol] = 0; + this.rows.get(nextRow).remove(possibleNum); + this.cols.get(nextCol).remove(possibleNum); + this.squares.get(squareIndex).remove(possibleNum); + } +} + return false; } @@ -141,8 +243,8 @@ public String toString() { } public static void main(String[] args) { - String fileName = "src/puzzle1.txt"; - + String fileName = "Chapter 15 Activities/Sudoku/src/puzzle1.txt"; + //String fileName = "data-structures/Chapter 15 Activities/Sudoku/src/puzzle1.txt"; //PERSONAL HOME USE SudokuSolver solver = new SudokuSolver(fileName); System.out.println(solver); if (solver.solve()) { diff --git a/Chapter 15 Class Notes/src/ListDemo.java b/Chapter 15 Class Notes/src/ListDemo.java index b6f9afc08..24532ed1c 100644 --- a/Chapter 15 Class Notes/src/ListDemo.java +++ b/Chapter 15 Class Notes/src/ListDemo.java @@ -9,6 +9,85 @@ public class ListDemo { public static void main(String[] args) { - - } + /* the addLast method can be used to populate a list */ + LinkedList staff = new LinkedList<>(); + staff.addLast("Tony"); + staff.addLast("Natasha"); + staff.addLast("Peter"); + staff.addLast("Steve"); + + System.out.println(staff); + + //The list is currently: TNPS + + /* + * The listIterator method creates a new list iterator that is positioned at the head of the list. + * The | is used to represent the iterator position + */ + ListIterator iterator = staff.listIterator(); // |TNPS iterator is right before the linkedlist + + /* The next method advances the iterator OVER the next element in the list. */ + iterator.next(); // T| NPS + /* The next method also returns the element that the iterator passes over. */ + String avenger = iterator.next(); + // TN|PS + System.out.println(avenger); //should print natasha + + /* The add method inserts an element at the iterator position. + * The iterator is then positioned AFTER the element that was added + */ + iterator.add("Clint"); //TNC|PS + iterator.add("Bruce"); //TNCB|PS + System.out.println(staff); + /* The remove method can ONLY be called after calling next or previous */ + // iterator.remove(); This line would cause an IllegalStateException error + //The remove method removes the element returned after calling next or previous (removes the one right before the next) + iterator.next(); + iterator.remove(); //Peter is removed -> TNCB|S + System.out.println(staff); + + /* + * The set method updates the element returned by the last call to next or previous + */ + iterator.previous(); //TNC|BS + iterator.set("Thor"); //Bruce is replaced by Thor TNC|TS + //passed over Bruce when previous was called to bruce was replaced by thor + System.out.println(staff); + + /* The hasNext method is used to deterine if there is a next node after the iterator (make sure ur not at the end of the list). The hasNext method is often used + * in the condition of a while loop + */ + iterator = staff.listIterator(); //|TNCTS + while (iterator.hasNext()) { + String n = iterator.next(); + if (n.equals("Natasha")){ //TN|CTS + iterator.remove(); //T|CTS + } + } //TCST| + /*Enhanced for loop works with linkedlist as well */ + for (String n: staff){ + System.out.println(n+" "); + } + System.out.println(); + + /*ConcurrentModificationException + * CANNOT modify a linkedlist while using an iterator + * UNLESS you use the iterator to do the modification + */ + iterator = staff.listIterator(); //|TCTS + while(iterator.hasNext()){ + String n = iterator.next(); + if (n.equals("Tony")){ + //staff.remove(); ConcurrentModificationException + } + } + //automatic iterator in the background already in the for each loop like the one below + for (String n: staff){ + if (n.equals("Tony")){ + staff.add("T'Challa"); + } + } + System.out.println(staff); + + } } diff --git a/Chapter 15 Class Notes/src/MapDemo.java b/Chapter 15 Class Notes/src/MapDemo.java index 835c1ba27..758192a0c 100644 --- a/Chapter 15 Class Notes/src/MapDemo.java +++ b/Chapter 15 Class Notes/src/MapDemo.java @@ -11,5 +11,30 @@ public class MapDemo { public static void main(String[] args) { + /* The Map interface is generic. + * The first type given is the key. + * The second type given is the value. + */ + Map favColors = new HashMap<>(); + + // Add elements to the map using the put method + favColors.put("Sreeram", Color.GREEN); + favColors.put("Cam", Color.BLUE); + favColors.put("Nimai", Color.RED); + + // Two different elements with the same value + favColors.put("Kaitlyn", Color.GREEN); + + // The same key CANNOT have two different values + // Using put on a key that exists, changes the value + favColors.put("Cam", Color.ORANGE); + + // Create a set of the keys in a map + Set keys = favColors.keySet(); + for (String key: keys) { + // [name] ([hasCode]): [color] + System.out.println(key + "("+key.hashCode()+"): "+favColors.get(key)); + } + } -} +} \ No newline at end of file diff --git a/Chapter 15 Class Notes/src/PriorityQueueDemo.java b/Chapter 15 Class Notes/src/PriorityQueueDemo.java index e27bc2c81..c211413cc 100644 --- a/Chapter 15 Class Notes/src/PriorityQueueDemo.java +++ b/Chapter 15 Class Notes/src/PriorityQueueDemo.java @@ -10,5 +10,41 @@ public class PriorityQueueDemo { public static void main(String[] args) { - } -} + + //create a priority queue of strings + //a priority needs to be composed of comparable objects + + Queue students = new PriorityQueue<>(); + students.add("Neel"); + students.add("Jonathan"); + students.add("Cam"); + students.add("Kaitlyn"); + students.add("Dylan"); + + // the next highest priorty object is moved to the front of the queue + //when the head of the queue is removed + while(students.size()>0){ + System.out.println(students.remove()); + } + + //create a to-do lis + //the workorder class has a priority and description + Queue toDo = new PriorityQueue<>(); + + //lower priority is more important + toDo.add(new WorkOrder(3,"Water Plants")); + toDo.add(new WorkOrder(2,"Make Dinner")); + toDo.add(new WorkOrder(1,"Conquer World")); + toDo.add(new WorkOrder(9,"Play Videogames")); + toDo.add(new WorkOrder(1,"Study for the test")); + + //objects are NOT stored in priority order + System.out.println(toDo); + + //objects will be removed in priority order + while(toDo.size()>0){ + System.out.println(toDo.remove()); + } + + +}} diff --git a/Chapter 15 Class Notes/src/QueueDemo.java b/Chapter 15 Class Notes/src/QueueDemo.java index 1da9ca974..b19ff1282 100644 --- a/Chapter 15 Class Notes/src/QueueDemo.java +++ b/Chapter 15 Class Notes/src/QueueDemo.java @@ -9,5 +9,40 @@ public class QueueDemo { public static void main(String[] args) { + // create a print queue of strings using a linkedlist + Queue jobs = new LinkedList<>(); + + //add some print jobs + jobs.add("Harry: Quarter 2 Expense Report"); + jobs.add("Conner: Recipe for banana bread"); + jobs.add("Katherine: Top secret document"); + + System.out.println("Printing: "+jobs.remove()); + + //add some more print jobs + jobs.add("Vardhan: Grocery List"); + jobs.add("Katherine: Really top secret document"); + jobs.add("Katherine: Can I get fired for this?"); + + System.out.println("Printing: "+jobs.remove()); + System.out.println("Printing: "+jobs.remove()); + + jobs.add("Boss: Katherine Termination Letter"); + + //print the rest of the jobs in the queue + /* + int numjobs = jobs.size(); + for(int i=0;i0){ + System.out.println("Printing" +jobs.remove()); + } } } diff --git a/Chapter 15 Class Notes/src/StackDemo.java b/Chapter 15 Class Notes/src/StackDemo.java index e8523604c..83a00c47e 100644 --- a/Chapter 15 Class Notes/src/StackDemo.java +++ b/Chapter 15 Class Notes/src/StackDemo.java @@ -9,5 +9,22 @@ public class StackDemo { public static void main(String[] args) { + Stack commands = new Stack<>(); + //push a bunch of commands onto the top of the stack + commands.push("Insert: 'Hello'"); + commands.push("Insert: ','"); + commands.push("Insert: ' '"); + commands.push("Insert: 'World;"); + commands.push("Insert: '?'"); + commands.push("Insert: '!'"); + + //print the stack the top of the stack is the far right + System.out.println(commands); + + //simulate the user pressing undo 4 times + for (int i=0; i<4; i++){ + System.out.println("Undo "+commands.pop()); + } + System.out.println(commands); } } diff --git a/Chapter 15 Class Notes/src/WordAnalysis.java b/Chapter 15 Class Notes/src/WordAnalysis.java index ffe5bc7af..ea97e1da6 100644 --- a/Chapter 15 Class Notes/src/WordAnalysis.java +++ b/Chapter 15 Class Notes/src/WordAnalysis.java @@ -13,6 +13,33 @@ public class WordAnalysis public static void main(String[] args) throws FileNotFoundException { + //Determine the current working directory + System.out.println(System.getProperty("user.dir")); + + //Read the dictionary file and the novel file + //Chapter 15 Class Notes/src/ + Set dictionaryWords = readWords("data-structures/Chapter 15 Class Notes/src/words"); + Set novelWords = readWords("data-structures\\Chapter 15 Class Notes\\src\\war-and-peace.txt"); + + //print all the words that are in the novel, but not the dictionary + for (String words: novelWords){ + if (!dictionaryWords.contains(words)){ + System.out.println(words); + } + } + + //print out the number of unique words in the novel + System.out.println("There are "+novelWords.size()+" unique words in the novel"); + + //Print the number of unique words with >3 letters + Iterator iterator = novelWords.iterator(); + while (iterator.hasNext()){ + if(iterator.next().length() <=3){ + iterator.remove(); + } + } + + System.out.println("There are "+novelWords.size()+" unique words with more than 3 letters"); } /** @@ -25,6 +52,16 @@ public static void main(String[] args) public static Set readWords(String filename) throws FileNotFoundException { - return null; + //we use a HashSet instead of a TreeSet because the order doens't matter + Set words = new HashSet<>(); + Scanner in = new Scanner(new File(filename), "UTF-8"); + //Use any character that's not a letter as a delimiter + in.useDelimiter("[^a-zA-Z]+"); + while(in.hasNext()){ + //add words to the set (duplicates are automatically ignored) + words.add(in.next().toLowerCase()); + + } + return words; } } diff --git a/Chapter 16 Activities/Contains/src/LinkedList.java b/Chapter 16 Activities/Contains/src/LinkedList.java index e8eb656bd..9ef00d84a 100644 --- a/Chapter 16 Activities/Contains/src/LinkedList.java +++ b/Chapter 16 Activities/Contains/src/LinkedList.java @@ -35,19 +35,58 @@ public int size() } /** - Checks if this linked list contains the given object. + Checks if this linked list contains the given object (recursive version). @param obj The object to be checked for. - @return If the object exists in the list. + @return true if the object exists in the list, false otherwise. */ public boolean contains(Object obj) { - // ... + return contains(first, obj); } + + /* CONTAINS METHOD WITHOUT ITERATOR + public boolean contains(Object obj) + { + Node current = first; + while (current != null) + { + if (obj == null && current.data == null) { + return true; + } + if (obj != null && obj.equals(current.data)) { + return true; + } + current = current.next; + } + return false; + }*/ + + + /** - Returns the first element in the linked list. - @return the first element in the linked list + Recursive helper method for contains. + @param start The current node in the recursion. + @param obj The object to search for. + @return true if found, false otherwise. */ + private static boolean contains(Node start, Object obj) + { + if (start == null) { + return false; + } + + if (obj == null && start.data == null) { + return true; + } + + if (obj != null && obj.equals(start.data)) { + return true; + } + + return contains(start.next, obj); + } + public Object getFirst() { if (first == null) @@ -55,10 +94,6 @@ public Object getFirst() return first.data; } - /** - Removes the first element in the linked list. - @return the removed element - */ public Object removeFirst() { if (first == null) @@ -66,17 +101,11 @@ public Object removeFirst() Object element = first.data; first = first.next; currentSize--; - // clear old cached data last = null; lastIndex = -1; - // return removed element return element; } - /** - Adds an element to the front of the linked list. - @param element the element to add - */ public void addFirst(Object element) { Node newNode = new Node(); @@ -84,16 +113,10 @@ public void addFirst(Object element) newNode.next = first; first = newNode; currentSize++; - // clear old cached data last = null; lastIndex = -1; } - /** - Gets the object at the given index. - @param n The index of the object. - @return The object at the given index. - */ public Object get(int n) { if ((lastIndex == -1) || (lastIndex >= n)) @@ -109,23 +132,12 @@ public Object get(int n) return last.data; } - /** - Sets the object at the given index. - @param n The index of the object to be set. - @param newElement The object to set. - */ public void set(int n, Object newElement) { Node node = getNode(first, n); node.data = newElement; } - /** - Gets the node at the given index. - @param start The start node to count from. - @param distance The index of the object to get. - @return The node at the given object. - */ private static Node getNode(Node start, int distance) { if ((distance <= 0) || (start == null)) @@ -133,10 +145,6 @@ private static Node getNode(Node start, int distance) return getNode(start.next, distance - 1); } - /** - Returns an iterator for iterating through this list. - @return an iterator for iterating through this list - */ public ListIterator listIterator() { return new LinkedListIterator(); @@ -153,40 +161,24 @@ private class LinkedListIterator implements ListIterator private Node position; private Node previous; - /** - Constructs an iterator that points to the front - of the linked list. - */ public LinkedListIterator() { position = null; previous = null; } - /** - Moves the iterator past the next element. - @return the traversed element - */ public Object next() { if (!hasNext()) throw new NoSuchElementException(); - previous = position; // Remember for remove - + previous = position; if (position == null) position = first; else position = position.next; - return position.data; } - /** - Tests if there is an element after the iterator - position. - @return true if there is an element after the iterator - position - */ public boolean hasNext() { if (position == null) @@ -195,11 +187,6 @@ public boolean hasNext() return position.next != null; } - /** - Adds an element before the iterator position - and moves the iterator past the inserted element. - @param element the element to add - */ public void add(Object element) { if (position == null) @@ -219,15 +206,10 @@ public void add(Object element) previous = position; } - /** - Removes the last traversed element. This method may - only be called after a call to the next() method. - */ public void remove() { if (previous == position) throw new IllegalStateException(); - if (position == first) { removeFirst(); @@ -240,11 +222,6 @@ public void remove() position = previous; } - /** - Sets the last traversed element to a different - value. - @param element the element to set - */ public void set(Object element) { if (position == null) diff --git a/Chapter 16 Activities/Contains/src/ListTester.java b/Chapter 16 Activities/Contains/src/ListTester.java index 03c6c9b43..abd14a9e2 100644 --- a/Chapter 16 Activities/Contains/src/ListTester.java +++ b/Chapter 16 Activities/Contains/src/ListTester.java @@ -23,7 +23,7 @@ public static void main(String[] args) System.out.print((names.contains("Harry") ? "true" : "false")); System.out.println(); System.out.println("Expected: true"); - + System.out.print((names.contains("Tom") ? "true" : "false")); System.out.println(); System.out.println("Expected: true"); diff --git a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java index 349635151..9a3e6cf75 100644 --- a/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java +++ b/Chapter 16 Activities/FirstToLast/src/LinkedListQueue.java @@ -23,8 +23,15 @@ public LinkedListQueue() */ public void firstToLast() { - . . . - + if (head == null || head.next == null) + { + return; + } + Node first = head; + head=head.next; + first.next = null; + tail.next = first; + } diff --git a/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java b/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java index c636cb1ef..9579a177f 100644 --- a/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java +++ b/Chapter 16 Activities/LastToFirst/src/LinkedListQueue.java @@ -22,11 +22,21 @@ public LinkedListQueue() */ public void lastToFirst() { - . . . - - - - + if (head == null || head.next == null) + { + return; + } + Node current=head; + Node prev = tail; + while (current.next != null) + { + prev = current; + current = current.next; + } + prev.next = null; + tail = prev; + current.next = head; + head = current; } diff --git a/Chapter 16 Activities/Size/src/LinkedList.java b/Chapter 16 Activities/Size/src/LinkedList.java index bc0ff8757..e3efc9aac 100644 --- a/Chapter 16 Activities/Size/src/LinkedList.java +++ b/Chapter 16 Activities/Size/src/LinkedList.java @@ -19,13 +19,41 @@ public LinkedList() } /** - Computes the size of the linked list. - @return the number of elements in the list - */ + Computes the size of the linked list by traversing the nodes. + @return the number of elements in the list + public int size() { - . . . - } + int count = 0; + Node current = first; + while (current != null) + { + count++; + current = current.next; + } + return count; + }*/ + +/** + Computes the size of the linked list recursively. + @return the number of elements in the list +*/ +public int size() +{ + return size(first); +} + +/** + Recursive helper method to compute size. + @param start The node to start counting from. + @return The number of nodes from start to end. +*/ +private static int size(Node start) +{ + if (start == null) + return 0; + return 1 + size(start.next); +} /** Returns the first element in the linked list. diff --git a/Chapter 16 Class Notes/src/CircularArrayQueue.java b/Chapter 16 Class Notes/src/CircularArrayQueue.java index bee3df2f6..38b9dd0aa 100644 --- a/Chapter 16 Class Notes/src/CircularArrayQueue.java +++ b/Chapter 16 Class Notes/src/CircularArrayQueue.java @@ -7,13 +7,21 @@ public class CircularArrayQueue { private Object[] elements; //private data - + private int currentSize; + private int head; + private int tail; /** Constructs an empty queue. */ - + public CircularArrayQueue(){ + final int INITIAL_SIZE = 3; + this.elements = new Object[INITIAL_SIZE]; + head =0; + tail=0; + currentSize=0; //queue is empty when we first created it + } @@ -23,7 +31,9 @@ public class CircularArrayQueue Checks whether this queue is empty. @return true if this queue is empty */ - + public boolean empty(){ + return currentSize==0; + } @@ -31,7 +41,15 @@ public class CircularArrayQueue Adds an element to the tail of this queue. @param newElement the element to add */ - + public void add(Object element){ + this.currentSize++; + this.elements[this.tail] = element; + this.tail++; + //reset the tail to 0 when it reaches the size of the array + this.tail %= this.elements.length; + + growIfNecessary(); + } @@ -40,7 +58,17 @@ public class CircularArrayQueue Removes an element from the head of this queue. @return the removed element */ + public Object remove(){ + if(this.empty()){ + throw new NoSuchElementException(); + } + this.currentSize--; + Object element = this.elements[this.head]; + //reset the head to 0 if we reach the end of the array + this.head = (this.head +1)% this.elements.length; + return element; + } @@ -50,7 +78,7 @@ public class CircularArrayQueue */ private void growIfNecessary() { - /* + if(this.currentSize == this.elements.length) { Object[] newElements = new Object[2 * this.elements.length]; @@ -62,7 +90,7 @@ private void growIfNecessary() this.head = 0; this.tail = this.currentSize; } - */ + } diff --git a/Chapter 16 Class Notes/src/LinkedList.java b/Chapter 16 Class Notes/src/LinkedList.java index 11b0b9ba1..784fe6510 100644 --- a/Chapter 16 Class Notes/src/LinkedList.java +++ b/Chapter 16 Class Notes/src/LinkedList.java @@ -9,11 +9,18 @@ public class LinkedList { + //first refers to the first node in the list + //if the list is empty, first will be null + private Node first; + /** Constructs an empty linked list. */ + public LinkedList(){ + this.first = null; + } @@ -21,15 +28,26 @@ public class LinkedList Returns the first element in the linked list. @return the first element in the linked list */ - - + public Object element(){ + if(this.first == null){ + throw new NoSuchElementException(); + } + return this.first.data; + } /** Removes the first element in the linked list. @return the removed element */ - + public Object removeFirst(){ + if(this.first == null){ + throw new NoSuchElementException(); + } + Object element = this.first.data; + this.first = this.first.next; + return element; + } @@ -38,8 +56,12 @@ public class LinkedList Adds an element to the front of the linked list. @param element the element to add */ - - + public void addFirst(Object e){ + Node newNode = new Node(); + newNode.data = e; + newNode.next = this.first; + this.first = newNode; + } @@ -47,30 +69,68 @@ public class LinkedList Returns an iterator for iterating through this list. @return an iterator for iterating through this list */ + public ListIterator listIterator(){ + return new LinkedListIterator(); + } - - + public String toString(){ + ListIterator listIterator = listIterator(); + String allElements = "["; + while(listIterator.hasNext()){ + allElements += listIterator.next()+", "; + } + return allElements+"]"; + } //Class Node + //Node is static because it does NOT need to access anything in LinkedList + //The object will store information, not interact + static class Node{ + public Node next; + public Object data; + } - class LinkedListIterator //implements ListIterator + class LinkedListIterator implements ListIterator { //private data + private Node position; + private Node previous; + private boolean isAfterNext; /** Constructs an iterator that points to the front of the linked list. */ - + public LinkedListIterator(){ + position=null; + previous=null; + isAfterNext = false; + } /** Moves the iterator past the next element. @return the traversed element */ + public Object next(){ + if (!hasNext()){ + throw new NoSuchElementException(); + } + previous = position; + if (position==null){ + position=first; + } + else{ + position=position.next; + } + isAfterNext = true; + + return position.data; + + } @@ -80,13 +140,40 @@ class LinkedListIterator //implements ListIterator @return true if there is an element after the iterator position */ + public boolean hasNext(){ + //check if list is empty + if(position == null){ + return first !=null; + } + + //the iterator has moved so check the next node + return position.next != null; + } + /** Adds an element before the iterator position and moves the iterator past the inserted element. @param element the element to add */ + public void add(Object element){ + //check if the iterator is at the beginning of the list + if (position==null){ + addFirst(element); + position=first; + } + else{ + Node newNode = new Node(); + newNode.data = element; + newNode.next = position.next; + //set the next element of the CURRENT position to point to our new node + position.next = newNode; + position = newNode; + } + + isAfterNext = false; + } @@ -96,7 +183,23 @@ class LinkedListIterator //implements ListIterator Removes the last traversed element. This method may only be called after a call to the next() method. */ + public void remove(){ + if(!isAfterNext){ + throw new IllegalStateException(); + } + + //check if the iterator is at the beginninng + if(position==first){ + removeFirst(); + position = null; + } + else{ + previous.next = position.next; + position=previous; + } + isAfterNext = false; + } @@ -107,9 +210,22 @@ only be called after a call to the next() method. Sets the last traversed element to a different value. @param element the element to set */ + public void set(Object element){ + if(!isAfterNext){ + throw new IllegalStateException(); + } + position.data = element; + //we don't have to reset isAfterNext because the structure of the list has not changed + } }//LinkedListIterator + + + public boolean contains(String string) { + // TODO Auto-generated method stub + throw new UnsupportedOperationException("Unimplemented method 'contains'"); + } }//LinkedList diff --git a/Chapter 16 Class Notes/src/LinkedListStack.java b/Chapter 16 Class Notes/src/LinkedListStack.java index e12647ae1..38fa72d60 100644 --- a/Chapter 16 Class Notes/src/LinkedListStack.java +++ b/Chapter 16 Class Notes/src/LinkedListStack.java @@ -20,6 +20,13 @@ public LinkedListStack() * * @param element the element to add */ + public void push (Object element){ + // Always push elements to the front of the linked list + Node newNode = new Node(); + newNode.data = element; + newNode.next = this.first; + this.first = newNode; + } @@ -30,7 +37,14 @@ public LinkedListStack() Removes the element from the top of the stack. @return the removed element */ - + public Object pop(){ + if(this.empty()){ + throw new NoSuchElementException(); + } + Object element = this.first.data; + this.first = this.first.next; + return element; + } @@ -43,6 +57,9 @@ public LinkedListStack() * * @return true if the stack is empty */ + public boolean empty(){ + return this.first==null; + } static class Node diff --git a/Chapter 16 Class Notes/src/ListDemo.java b/Chapter 16 Class Notes/src/ListDemo.java index 36dcfe962..86549eadd 100644 --- a/Chapter 16 Class Notes/src/ListDemo.java +++ b/Chapter 16 Class Notes/src/ListDemo.java @@ -5,5 +5,13 @@ public class ListDemo { public static void main(String[] args) { + LinkedList students = new LinkedList(); + + students.addFirst("Cam"); + students.addFirst("Conner"); + students.addFirst("Catherine"); + students.addFirst("Jonathan"); + + System.out.println(students); } } diff --git a/Chapter 16 Class Notes/src/QueueDemo.java b/Chapter 16 Class Notes/src/QueueDemo.java index 696b7f3f2..7b7399425 100644 --- a/Chapter 16 Class Notes/src/QueueDemo.java +++ b/Chapter 16 Class Notes/src/QueueDemo.java @@ -2,12 +2,13 @@ public class QueueDemo { public static void main(String[] args) { - /* + CircularArrayQueue queue = new CircularArrayQueue(); queue.add("Tom"); queue.add("Diana"); queue.add("Harry"); + queue.add("sam"); System.out.println(queue.remove()); // remove Tom queue.add("Romeo"); System.out.println(queue.remove()); // remove Diana @@ -20,6 +21,6 @@ public static void main(String[] args) } System.out.println("Expected output: Tom, Diana, Harry, Romeo, Juliet, Maria"); - */ + } } diff --git a/Chapter 16 Class Notes/src/StackDemo.java b/Chapter 16 Class Notes/src/StackDemo.java index d093e087a..c23f82261 100644 --- a/Chapter 16 Class Notes/src/StackDemo.java +++ b/Chapter 16 Class Notes/src/StackDemo.java @@ -2,7 +2,7 @@ public class StackDemo { public static void main(String[] args) { - /* + LinkedListStack stack = new LinkedListStack(); stack.push("Tom"); @@ -15,6 +15,6 @@ public static void main(String[] args) } System.out.println("Expected: Harry Diana Tom"); - */ + } } diff --git a/Chapter 17 Activities/CountLeaves/src/Tree.java b/Chapter 17 Activities/CountLeaves/src/Tree.java index 0853af2f7..65c43c3ae 100644 --- a/Chapter 17 Activities/CountLeaves/src/Tree.java +++ b/Chapter 17 Activities/CountLeaves/src/Tree.java @@ -24,6 +24,20 @@ public int size() for (Node child : children) { sum = sum + child.size(); } return 1 + sum; } + + public int leafCount() + { + + if (children.isEmpty()) { + return 1; + } else { + int count = 0; + for (Node child : children) { + count += child.leafCount(); + } + return count; + } + } } /** @@ -63,5 +77,15 @@ public int size() else { return root.size(); } } + public int leafCount() + { + if (root == null) { + return 0; + } else { + return root.leafCount(); + } + } + + // Additional methods will be added in later sections. } diff --git a/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java b/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java index b0bec272c..bd8230817 100644 --- a/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java +++ b/Chapter 17 Activities/CountNodesWithOneChild/src/BinaryTree.java @@ -1,7 +1,4 @@ -//HIDE -/** - A binary tree in which each node has two children. -*/ +// BinaryTree.java public class BinaryTree { private Node root; @@ -34,15 +31,13 @@ public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) root = new Node(); root.data = rootData; - if( left != null ) - { - root.left = left.root; - } + if (left != null) { + root.left = left.root; + } - if( right != null ) - { - root.right = right.root; - } + if (right != null) { + root.right = right.root; + } } class Node @@ -102,4 +97,33 @@ public BinaryTree right() result.root = root.right; return result; } + + /** + Counts the number of nodes with exactly one child. + @return the number of nodes with exactly one child + */ + public int countNodesWithOneChild() + { + return countNodesWithOneChild(root); + } + + /** + Helper method to count nodes with exactly one child. + @param node the current node in the tree + @return the number of nodes with exactly one child + */ + private int countNodesWithOneChild(Node node) + { + if (node == null) { + return 0; + } + + int count = 0; + + if ((node.left != null && node.right == null) || (node.left == null && node.right != null)) { + count = 1; + } + + return count + countNodesWithOneChild(node.left) + countNodesWithOneChild(node.right); + } } diff --git a/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java b/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java index 6a28a67ae..8db1b6619 100644 --- a/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java +++ b/Chapter 17 Activities/DepthFirst/src/DepthFirstTester.java @@ -33,4 +33,7 @@ public static void main(String[] args) System.out.println("Expected: Anne Peter Sonia Mike Jane Sam Zara"); } + + + } diff --git a/Chapter 17 Activities/DepthFirst/src/Tree.java b/Chapter 17 Activities/DepthFirst/src/Tree.java index 7842532b1..d75b29187 100644 --- a/Chapter 17 Activities/DepthFirst/src/Tree.java +++ b/Chapter 17 Activities/DepthFirst/src/Tree.java @@ -65,4 +65,47 @@ public int size() } // Additional methods will be added in later sections. + + public void depthFirst(Visitor v) + { + if (root == null) return; + depthFirst(root, v); + } + + + private boolean depthFirst(Node n, Visitor v) + { + if (n == null) return true; + + boolean continueTraversal = v.visit(n.data); + if (!continueTraversal) return false; + + for (Node child : n.children) + { + if (!depthFirst(child, v)) return false; + } + + return true; + } + + + public void postorder(Visitor v) + { + if (root == null) return; + postorder(root, v); + } + + + private boolean postorder(Node n, Visitor v) + { + if (n == null) return true; + + for (Node child : n.children) + { + if (!postorder(child, v)) return false; + } + + boolean continueTraversal = v.visit(n.data); + return continueTraversal; + } } diff --git a/Chapter 17 Class Notes/src/BinarySearchTree.java b/Chapter 17 Class Notes/src/BinarySearchTree.java index 6720a3152..883221a19 100644 --- a/Chapter 17 Class Notes/src/BinarySearchTree.java +++ b/Chapter 17 Class Notes/src/BinarySearchTree.java @@ -12,7 +12,7 @@ public class BinarySearchTree */ public BinarySearchTree() { - + this.root = null; } /** @@ -21,7 +21,17 @@ public BinarySearchTree() */ public void add(Comparable obj) { - + Node newNode = new Node(); + newNode.data = obj; + newNode.left = null; + newNode.right = null; + + if (this.root == null) { + this.root = newNode; + } + else { + this.root.addNode(newNode); + } } /** @@ -31,6 +41,20 @@ public void add(Comparable obj) */ public boolean find(Comparable obj) { + Node current = this.root; + while (current != null) { + int diff = obj.compareTo(current.data); + if (diff == 0) { + return true; + } + else if (diff < 0) { + current = current.left; + } + else { + current = current.right; + } + } + return false; } @@ -41,7 +65,76 @@ public boolean find(Comparable obj) */ public void remove(Comparable obj) { - + Node toBeRemoved = this.root; + boolean found = false; + Node parent = null; + + while (!found && toBeRemoved != null) { + int diff = obj.compareTo(toBeRemoved.data); + if (diff == 0) { + found = true; + } + else if (diff < 0) { + parent = toBeRemoved; + toBeRemoved = toBeRemoved.left; + } + else { + parent = toBeRemoved; + toBeRemoved = toBeRemoved.right; + } + } + + if (!found) { + return; + } + + // Case 1 and Case 2 (At least one child is null) + if (toBeRemoved.left == null || toBeRemoved.right == null) { + Node newChild; + + if (toBeRemoved.left == null) { + newChild = toBeRemoved.right; + } + else { + newChild = toBeRemoved.left; + } + + // Remove the root if the parent is null + if (parent == null) { + this.root = newChild; + } + else if (parent.left == toBeRemoved) { + parent.left = newChild; + } + else { + parent.right = newChild; + } + + return; + } + + // Case 3: Remove a node with two children + + // Find the least element of the right subtree + // The least element will replace the removed node + Node leastParent = toBeRemoved; + Node least = toBeRemoved.right; + while (least.left != null) { + leastParent = least; + least = least.left; + } + + // Move the data to the node being removed + toBeRemoved.data = least.data; + + // Unlink the least child + if (leastParent == toBeRemoved) { + leastParent.right = least.right; + } + else { + leastParent.left = least.right; + } + } /** @@ -49,7 +142,9 @@ public void remove(Comparable obj) */ public void print() { - + // Print the tree using inorder traversal + print(this.root); + System.out.println(); } /** @@ -58,7 +153,13 @@ public void print() */ private static void print(Node parent) { - + if (parent == null) { + return; + } + + print(parent.left); + System.out.println(parent.data + " "); + print(parent.right); } /** @@ -67,7 +168,10 @@ private static void print(Node parent) */ static class Node { - + // A BST MUST BE made of Comparable Objects + public Comparable data; + public Node left; + public Node right; /** Inserts a new node as a descendant of this node. @@ -75,10 +179,26 @@ static class Node */ public void addNode(Node newNode) { + // If diff < 0, newNode is to the left of this node + // If diff > 0, newNode is to the right of this node + int diff = newNode.data.compareTo(data); + if (diff < 0) { + if (left == null) { + left = newNode; + } + else { + left.addNode(newNode); + } + } + else if (diff > 0) { + if (right == null) { + right = newNode; + } + else { + right.addNode(newNode); + } + } } } -} - - - +} \ No newline at end of file diff --git a/Chapter 17 Class Notes/src/BinaryTree.java b/Chapter 17 Class Notes/src/BinaryTree.java index 5877b6326..d03edbac6 100644 --- a/Chapter 17 Class Notes/src/BinaryTree.java +++ b/Chapter 17 Class Notes/src/BinaryTree.java @@ -10,7 +10,7 @@ public class BinaryTree */ public BinaryTree() { - + root = null; } /** @@ -19,7 +19,10 @@ public BinaryTree() */ public BinaryTree(Object rootData) { - + this.root = new Node(); + this.root.data = rootData; + this.root.left = null; + this.root.right = null; } /** @@ -30,12 +33,16 @@ public BinaryTree(Object rootData) */ public BinaryTree(Object rootData, BinaryTree left, BinaryTree right) { - + this(rootData); + this.root.left = left.root; + this.root.right = right.root; } static class Node { - + public Object data; + public Node left; + public Node right; } /** @@ -45,7 +52,13 @@ static class Node */ private static int height(Node n) { - return 0; + if (n == null) { + return 0; + } + else { + return 1 + Math.max(BinaryTree.height(n.left), BinaryTree.height(n.right)); + } + } /** @@ -54,7 +67,7 @@ private static int height(Node n) */ public int height() { - return 0; + return BinaryTree.height(this.root); } /** @@ -63,7 +76,7 @@ public int height() */ public boolean isEmpty() { - return false; + return this.root == null; } /** @@ -72,7 +85,7 @@ public boolean isEmpty() */ public Object data() { - return null; + return this.root.data; } /** @@ -81,7 +94,10 @@ public Object data() */ public BinaryTree left() { - return null; + BinaryTree subtree = new BinaryTree(); + subtree.root = this.root.left; + return subtree; + // return this.root.left <--- root.left is a Node, not a BinaryTree } /** @@ -90,6 +106,8 @@ public BinaryTree left() */ public BinaryTree right() { - return null; + BinaryTree subtree = new BinaryTree(); + subtree.root = this.root.right; + return subtree; } -} +} \ No newline at end of file diff --git a/Chapter 17 Class Notes/src/Tree.java b/Chapter 17 Class Notes/src/Tree.java index a856e4347..6289ecb2e 100644 --- a/Chapter 17 Class Notes/src/Tree.java +++ b/Chapter 17 Class Notes/src/Tree.java @@ -6,10 +6,12 @@ */ public class Tree { + private Node root; static class Node { - + public Object data; + public List children; /** Computes the size of the subtree whose root is this node. @@ -17,7 +19,11 @@ static class Node */ public int size() { - return 0; + int total = 1; + for (Node child: this.children) { + total += child.size(); + } + return total; } } @@ -27,7 +33,9 @@ public int size() */ public Tree(Object rootData) { - + this.root = new Node(); + this.root.data = rootData; + this.root.children = new ArrayList<>(); } /** @@ -35,7 +43,7 @@ public Tree(Object rootData) */ public void addSubtree(Tree subtree) { - + this.root.children.add(subtree.root); } /** @@ -44,8 +52,46 @@ public void addSubtree(Tree subtree) */ public int size() { - return 0; + return this.root.size(); } // Additional methods will be added in later sections. -} + + /* + * A visitor method is called for each visited node + * during a tree traversal. + */ + public interface Visitor { + /* + * The visit method is called for each visited node. + * @param data: The data of the node being visited + */ + void visit(Object data); + + } + + /* + * Traverse this tree in preorder. + * @param v: The visitor to be invoked on each node. + */ + public void preorder(Visitor v) { + Tree.preorder(this.root, v); + } + + /* + * Traverse the tree with a given root in preorder. + @param n: The root of the tree to traverse + @param v: The visitor to be invoked on each node + */ + private static void preorder(Node n, Visitor v) { + if (n == null) { + return; + } + + v.visit(n.data); + + for (Node child: n.children) { + Tree.preorder(child, v); + } + } +} \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 000000000..cca103c11 --- /dev/null +++ b/index.html @@ -0,0 +1,23 @@ + + + + + + + +First Website + + + + + + Visit Weather Website + + + + + +