diff --git a/01_introduction_to_algorithms/java/01_binary_search/src/BinarySearch.java b/01_introduction_to_algorithms/java/01_binary_search/src/BinarySearch.java new file mode 100644 index 0000000..c8f8fcc --- /dev/null +++ b/01_introduction_to_algorithms/java/01_binary_search/src/BinarySearch.java @@ -0,0 +1,30 @@ +public class BinarySearch { + + // has to return boxed integer in order to comfort to interface defined in the book + private static Integer binarySearch(int[] list, int item) { + int low = 0; + int high = list.length - 1; + + while (low <= high) { + int mid = (low + high) / 2; + int guess = list[mid]; + if (guess == item) { + return mid; + } + if (guess > item) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return null; + } + + public static void main(String[] args) { + int[] myList = {1, 3, 5, 7, 9}; + + System.out.println(binarySearch(myList, 3)); // 1 + System.out.println(binarySearch(myList, -1)); // null + } +} diff --git a/02_selection_sort/java/src/SelectionSort.java b/02_selection_sort/java/src/SelectionSort.java new file mode 100644 index 0000000..f2946b0 --- /dev/null +++ b/02_selection_sort/java/src/SelectionSort.java @@ -0,0 +1,37 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SelectionSort { + + private static List selectionSort(List arr) { + List newArr = new ArrayList<>(arr.size()); + + int size = arr.size(); + for (int i = 0; i < size; i++) { + int smallest = findSmallest(arr); + newArr.add(arr.get(smallest)); + + arr.remove(smallest); + } + + return newArr; + } + + private static int findSmallest(List arr) { + int smallest = arr.get(0); + int smallestIndex = 0; + for (int i = 0; i < arr.size(); i++) { + if (arr.get(i) < smallest) { + smallest = arr.get(i); + smallestIndex = i; + } + } + return smallestIndex; + } + + public static void main(String[] args) { + List arr = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 10)); + System.out.println(selectionSort(arr)); //[2, 3, 5, 6, 10] + } +} \ No newline at end of file diff --git a/02_selection_sort/java/src/SelectionSort2.java b/02_selection_sort/java/src/SelectionSort2.java new file mode 100644 index 0000000..b70e598 --- /dev/null +++ b/02_selection_sort/java/src/SelectionSort2.java @@ -0,0 +1,33 @@ +import java.util.Arrays; + +public class SelectionSort2 { + + // this version uses raw arrays instead of ArrayList + private static int[] selectionSort(int[] arr) { + int[] newArr = new int[]{arr.length}; + + for (int i = 0; i < newArr.length; i++) { + int smallest = findSmallest(arr, i); + newArr[i] = arr[smallest]; + } + + return newArr; + } + + private static int findSmallest(int[] arr, int low) { + int smallest = arr[low]; + int smallestIndex = low; + for (int i = low + 1; i < arr.length; i++) { + if (arr[i] < smallest) { + smallest = arr[i]; + smallestIndex = i; + } + } + return smallestIndex; + } + + public static void main(String[] args) { + int[] arr = {5, 3, 6, 2, 10}; + System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10] + } +} \ No newline at end of file diff --git a/03_recursion/java/01_countdown/src/Countdown.java b/03_recursion/java/01_countdown/src/Countdown.java new file mode 100644 index 0000000..d3d8f0e --- /dev/null +++ b/03_recursion/java/01_countdown/src/Countdown.java @@ -0,0 +1,17 @@ +public class Countdown { + + private static void countdown(int i) { + System.out.println(i); + + // base case + if (i <= 0) { + return; + } else { + countdown(i - 1); + } + } + + public static void main(String[] args) { + countdown(5); + } +} \ No newline at end of file diff --git a/03_recursion/java/02_greet/src/Greet.java b/03_recursion/java/02_greet/src/Greet.java new file mode 100644 index 0000000..5a6af46 --- /dev/null +++ b/03_recursion/java/02_greet/src/Greet.java @@ -0,0 +1,21 @@ +public class Greet { + + private static void greet2(String name) { + System.out.println("how are you, " + name + "?"); + } + + private static void bye() { + System.out.println("ok bye!"); + } + + private static void greet(String name) { + System.out.println("hello, " + name + "!"); + greet2(name); + System.out.println("getting ready to say bye..."); + bye(); + } + + public static void main(String[] args) { + greet("adit"); + } +} \ No newline at end of file diff --git a/03_recursion/java/03_factorial/src/Factorial.java b/03_recursion/java/03_factorial/src/Factorial.java new file mode 100644 index 0000000..ea426df --- /dev/null +++ b/03_recursion/java/03_factorial/src/Factorial.java @@ -0,0 +1,14 @@ +public class Factorial { + + private static int fact(int x) { + if (x == 1) { + return 1; + } else { + return x * fact(x - 1); + } + } + + public static void main(String[] args) { + System.out.println(fact(5)); + } +} \ No newline at end of file diff --git a/04_quicksort/java/01_loop_sum/src/LoopSum.java b/04_quicksort/java/01_loop_sum/src/LoopSum.java new file mode 100644 index 0000000..87baf25 --- /dev/null +++ b/04_quicksort/java/01_loop_sum/src/LoopSum.java @@ -0,0 +1,15 @@ +public class LoopSum { + + private static int sum(int[] arr) { + int total = 0; + for (int x = 0; x < arr.length; x++) { + total += arr[x]; + } + + return total; + } + + public static void main(String[] args) { + System.out.println(sum(new int[]{1, 2, 3, 4})); // 10 + } +} \ No newline at end of file diff --git a/04_quicksort/java/02_recursive_sum/src/RecursiveSum.java b/04_quicksort/java/02_recursive_sum/src/RecursiveSum.java new file mode 100644 index 0000000..6bc2da8 --- /dev/null +++ b/04_quicksort/java/02_recursive_sum/src/RecursiveSum.java @@ -0,0 +1,16 @@ +import java.util.Arrays; + +public class RecursiveSum { + + private static int sum(int[] arr) { + if (arr.length == 0) { + return 0; + } else { + return arr[0] + sum(Arrays.copyOfRange(arr, 1, arr.length)); + } + } + + public static void main(String[] args) { + System.out.println(sum(new int[]{1, 2, 3, 4})); // 10 + } +} \ No newline at end of file diff --git a/04_quicksort/java/03_recursive_count/src/RecursiveCount.java b/04_quicksort/java/03_recursive_count/src/RecursiveCount.java new file mode 100644 index 0000000..a701bf3 --- /dev/null +++ b/04_quicksort/java/03_recursive_count/src/RecursiveCount.java @@ -0,0 +1,16 @@ +import java.util.Arrays; + +public class RecursiveCount { + + private static int count(int[] list) { + if (list.length == 0) { + return 0; + } + + return 1 + count(Arrays.copyOfRange(list, 1, list.length)); + } + + public static void main(String[] args) { + System.out.println(count(new int[]{0, 1, 2, 3, 4, 5})); // 6 + } +} \ No newline at end of file diff --git a/04_quicksort/java/04_recursive_max/src/RecursiveMax.java b/04_quicksort/java/04_recursive_max/src/RecursiveMax.java new file mode 100644 index 0000000..9dfb57a --- /dev/null +++ b/04_quicksort/java/04_recursive_max/src/RecursiveMax.java @@ -0,0 +1,17 @@ +import java.util.Arrays; + +public class RecursiveMax { + + private static int max(int[] list) { + if (list.length == 2) { + return list[0] > list[1] ? list[0] : list[1]; + } + + int subMax = max(Arrays.copyOfRange(list, 1, list.length)); + return list[0] > subMax ? list[0] : subMax; + } + + public static void main(String[] args) { + System.out.println(max(new int[]{1, 5, 10, 25, 16, 1})); // 25 + } +} \ No newline at end of file diff --git a/04_quicksort/java/05_quicksort/src/Quicksort.java b/04_quicksort/java/05_quicksort/src/Quicksort.java new file mode 100644 index 0000000..432af28 --- /dev/null +++ b/04_quicksort/java/05_quicksort/src/Quicksort.java @@ -0,0 +1,35 @@ +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Quicksort { + public static void main(String[] args) { + System.out.println(quicksort(Arrays.asList(10, 5, 2, 3))); // [2, 3, 5, 10] + } + + private static List quicksort(List list) { + if (list.size() < 2) { + // base case, arrays with 0 or 1 element are already "sorted" + return list; + } else { + // recursive case + Integer pivot = list.get(0); + + // sub-array of all the elements less than the pivot + List less = list.stream().skip(1).filter(el -> el <= pivot) + .collect(Collectors.toList()); + + // sub-array of all the elements greater than the pivot + List greater = list.stream().skip(1).filter(el -> el > pivot) + .collect(Collectors.toList()); + + return Stream.of( + quicksort(less).stream(), + Stream.of(pivot), + quicksort(greater).stream()) + .flatMap(Function.identity()).collect(Collectors.toList()); + } + } +} \ No newline at end of file diff --git a/05_hash_tables/java/01_price_of_groceries/src/PriceOfGroceries.java b/05_hash_tables/java/01_price_of_groceries/src/PriceOfGroceries.java new file mode 100644 index 0000000..19e2062 --- /dev/null +++ b/05_hash_tables/java/01_price_of_groceries/src/PriceOfGroceries.java @@ -0,0 +1,17 @@ +import java.util.HashMap; +import java.util.Map; + +public class PriceOfGroceries { + + public static void main(String[] args) { + Map book = new HashMap<>(); + + // an apple costs 67 cents + book.put("apple", 0.67); + // milk costs $1.49 + book.put("milk", 1.49); + book.put("avocado", 1.49); + + System.out.println(book); // {apple=0.67, avocado=1.49, milk=1.49} + } +} \ No newline at end of file diff --git a/05_hash_tables/java/02_check_voter/src/CheckVoter.java b/05_hash_tables/java/02_check_voter/src/CheckVoter.java new file mode 100644 index 0000000..228adf9 --- /dev/null +++ b/05_hash_tables/java/02_check_voter/src/CheckVoter.java @@ -0,0 +1,21 @@ +import java.util.HashMap; +import java.util.Map; + +public class CheckVoter { + private static Map voted = new HashMap<>(); + + private static void checkVoter(String name) { + if (voted.containsKey(name)) { + System.out.println("kick them out!"); + } else { + voted.put(name, true); + System.out.println("let them vote!"); + } + } + + public static void main(String[] args) { + checkVoter("tom"); // let them vote! + checkVoter("mike"); // let them vote! + checkVoter("mike"); // kick them out! + } +} diff --git a/06_breadth-first_search/java/01_breadth_first_search/src/BreadthFirstSearch.java b/06_breadth-first_search/java/01_breadth_first_search/src/BreadthFirstSearch.java new file mode 100644 index 0000000..af02619 --- /dev/null +++ b/06_breadth-first_search/java/01_breadth_first_search/src/BreadthFirstSearch.java @@ -0,0 +1,44 @@ +import java.util.*; + +public class BreadthFirstSearch { + private static Map> graph = new HashMap<>(); + + private static boolean search(String name) { + Queue searchQueue = new ArrayDeque<>(graph.get(name)); + // This list is how you keep track of which people you've searched before. + List searched = new ArrayList<>(); + + while (!searchQueue.isEmpty()) { + String person = searchQueue.poll(); + // Only search this person if you haven't already searched them + if (!searched.contains(person)) { + if (person_is_seller(person)) { + System.out.println(person + " is a mango seller!"); + } else { + searchQueue.addAll(graph.get(person)); + // Marks this person as searched + searched.add(person); + } + } + } + + return false; + } + + private static boolean person_is_seller(String name) { + return name.endsWith("m"); + } + + public static void main(String[] args) { + graph.put("you", Arrays.asList("alice", "bob", "claire")); + graph.put("bob", Arrays.asList("anuj", "peggy")); + graph.put("alice", Arrays.asList("peggy")); + graph.put("claire", Arrays.asList("thom", "jonny")); + graph.put("anuj", Collections.emptyList()); + graph.put("peggy", Collections.emptyList()); + graph.put("thom", Collections.emptyList()); + graph.put("jonny", Collections.emptyList()); + + search("you"); + } +} diff --git a/07_dijkstras_algorithm/java/01_dijkstras_algorithm/src/DijkstrasAlgorithm.java b/07_dijkstras_algorithm/java/01_dijkstras_algorithm/src/DijkstrasAlgorithm.java new file mode 100644 index 0000000..3db5629 --- /dev/null +++ b/07_dijkstras_algorithm/java/01_dijkstras_algorithm/src/DijkstrasAlgorithm.java @@ -0,0 +1,82 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DijkstrasAlgorithm { + // the graph + private static Map> graph = new HashMap<>(); + private static List processed = new ArrayList<>(); + + private static String findLowestCostNode(Map costs) { + Double lowestCost = Double.POSITIVE_INFINITY; + String lowestCostNode = null; + + // Go through each node + for (Map.Entry node : costs.entrySet()) { + Double cost = node.getValue(); + // If it's the lowest cost so far and hasn't been processed yet... + if (cost < lowestCost && !processed.contains(node.getKey())) { + // ... set it as the new lowest-cost node. + lowestCost = cost; + lowestCostNode = node.getKey(); + } + } + + return lowestCostNode; + } + + public static void main(String[] args) { + graph.put("start", new HashMap<>()); + graph.get("start").put("a", 6.0); + graph.get("start").put("b", 2.0); + + graph.put("a", new HashMap<>()); + graph.get("a").put("fin", 1.0); + + graph.put("b", new HashMap<>()); + graph.get("b").put("a", 3.0); + graph.get("b").put("fin", 5.0); + + graph.put("fin", new HashMap<>()); + + // The costs table + Map costs = new HashMap<>(); + costs.put("a", 6.0); + costs.put("b", 2.0); + costs.put("fin", Double.POSITIVE_INFINITY); + + // the parents table + Map parents = new HashMap<>(); + parents.put("a", "start"); + parents.put("b", "start"); + parents.put("fin", null); + + String node = findLowestCostNode(costs); + while (node != null) { + Double cost = costs.get(node); + // Go through all the neighbors of this node + + Map neighbors = graph.get(node); + + for (String n : neighbors.keySet()) { + double newCost = cost + neighbors.get(n); + // If it's cheaper to get to this neighbor by going through this node + if (costs.get(n) > newCost) { + // ... update the cost for this node + costs.put(n, newCost); + // This node becomes the new parent for this neighbor. + parents.put(n, node); + } + } + // Mark the node as processed + processed.add(node); + + // Find the next node to process, and loop + node = findLowestCostNode(costs); + } + + System.out.println("Cost from the start to each node:"); + System.out.println(costs); // { a: 5, b: 2, fin: 6 } + } +} \ No newline at end of file diff --git a/08_greedy_algorithms/java/01_set_covering/src/SetCovering.java b/08_greedy_algorithms/java/01_set_covering/src/SetCovering.java new file mode 100644 index 0000000..86f0791 --- /dev/null +++ b/08_greedy_algorithms/java/01_set_covering/src/SetCovering.java @@ -0,0 +1,37 @@ +import java.util.*; + +public class SetCovering { + + public static void main(String[] args) { + Set statesNeeded = new HashSet(Arrays.asList("mt", "wa", "or", "id", "nv", "ut", "ca", "az")); + Map> stations = new LinkedHashMap<>(); + + stations.put("kone", new HashSet<>(Arrays.asList("id", "nv", "ut"))); + stations.put("ktwo", new HashSet<>(Arrays.asList("wa", "id", "mt"))); + stations.put("kthree", new HashSet<>(Arrays.asList("or", "nv", "ca"))); + stations.put("kfour", new HashSet<>(Arrays.asList("nv", "ut"))); + stations.put("kfive", new HashSet<>(Arrays.asList("ca", "az"))); + + Set finalStations = new HashSet(); + while (!statesNeeded.isEmpty()) { + String bestStation = null; + Set statesCovered = new HashSet<>(); + + for (Map.Entry> station : stations.entrySet()) { + Set covered = new HashSet<>(statesNeeded); + covered.retainAll(station.getValue()); + + if (covered.size() > statesCovered.size()) { + bestStation = station.getKey(); + statesCovered = covered; + } + statesNeeded.removeIf(statesCovered::contains); + + if (bestStation != null) { + finalStations.add(bestStation); + } + } + } + System.out.println(finalStations); // [ktwo, kone, kthree, kfive] + } +} \ No newline at end of file diff --git a/09_dynamic_programming/java/01_longest_common_subsequence/src/LongestCommonSubsequence.java b/09_dynamic_programming/java/01_longest_common_subsequence/src/LongestCommonSubsequence.java new file mode 100644 index 0000000..20079f7 --- /dev/null +++ b/09_dynamic_programming/java/01_longest_common_subsequence/src/LongestCommonSubsequence.java @@ -0,0 +1,50 @@ +import java.util.Arrays; + +public class LongestCommonSubsequence { + public static void main(String[] args) { +// if (word_a[i] == word_b[1]) { +// cell[i][j] = cell[i - 1][j - 1] + 1; +// } else { +// cell[i][j] = Math.Max(cell[i - 1][j], cell[i][j - 1]); +// } + + String wordA = "hish"; + String wordB = "fish"; + + int[][] cell = new int[wordA.length()][wordB.length()]; + + for (int i = 0; i < wordA.length(); i++) { + for (int j = 0; j < wordB.length(); j++) { + // The letters match + if (wordA.charAt(i) == wordB.charAt(j)) { + if (i > 0 && j > 0) { + cell[i][j] = cell[i - 1][j - 1] + 1; + } else { + cell[i][j] = 1; + } + } else { + // The letters don't match. + if (i > 0 && j > 0) { + cell[i][j] = Math.max(cell[i - 1][j], cell[i][j - 1]); + } else { + cell[i][j] = 0; + } + } + } + } + + printResult(cell); +// [0, 0, 0, 1] +// [0, 1, 1, 1] +// [0, 1, 2, 2] +// [0, 1, 2, 3] + + } + + private static void printResult(int[][] arr) { + for (int[] row : arr) { + System.out.println(Arrays.toString(row)); + } + } + +} \ No newline at end of file