add examples in java 8 (#12)
* code for chapters 3-9 in Java * code for chapters 1 in Java * code for chapter 2 in Java * missing CheckVoter for chapter 5 in Java * add missing sample output for SetCovering as a comment
This commit is contained in:
committed by
Aditya Bhargava
parent
12265a8c61
commit
4631b7a156
@@ -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
|
||||
}
|
||||
}
|
||||
37
02_selection_sort/java/src/SelectionSort.java
Normal file
37
02_selection_sort/java/src/SelectionSort.java
Normal file
@@ -0,0 +1,37 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SelectionSort {
|
||||
|
||||
private static List<Integer> selectionSort(List<Integer> arr) {
|
||||
List<Integer> 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<Integer> 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<Integer> arr = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 10));
|
||||
System.out.println(selectionSort(arr)); //[2, 3, 5, 6, 10]
|
||||
}
|
||||
}
|
||||
33
02_selection_sort/java/src/SelectionSort2.java
Normal file
33
02_selection_sort/java/src/SelectionSort2.java
Normal file
@@ -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]
|
||||
}
|
||||
}
|
||||
17
03_recursion/java/01_countdown/src/Countdown.java
Normal file
17
03_recursion/java/01_countdown/src/Countdown.java
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
21
03_recursion/java/02_greet/src/Greet.java
Normal file
21
03_recursion/java/02_greet/src/Greet.java
Normal file
@@ -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");
|
||||
}
|
||||
}
|
||||
14
03_recursion/java/03_factorial/src/Factorial.java
Normal file
14
03_recursion/java/03_factorial/src/Factorial.java
Normal file
@@ -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));
|
||||
}
|
||||
}
|
||||
15
04_quicksort/java/01_loop_sum/src/LoopSum.java
Normal file
15
04_quicksort/java/01_loop_sum/src/LoopSum.java
Normal file
@@ -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
|
||||
}
|
||||
}
|
||||
16
04_quicksort/java/02_recursive_sum/src/RecursiveSum.java
Normal file
16
04_quicksort/java/02_recursive_sum/src/RecursiveSum.java
Normal file
@@ -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
|
||||
}
|
||||
}
|
||||
16
04_quicksort/java/03_recursive_count/src/RecursiveCount.java
Normal file
16
04_quicksort/java/03_recursive_count/src/RecursiveCount.java
Normal file
@@ -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
|
||||
}
|
||||
}
|
||||
17
04_quicksort/java/04_recursive_max/src/RecursiveMax.java
Normal file
17
04_quicksort/java/04_recursive_max/src/RecursiveMax.java
Normal file
@@ -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
|
||||
}
|
||||
}
|
||||
35
04_quicksort/java/05_quicksort/src/Quicksort.java
Normal file
35
04_quicksort/java/05_quicksort/src/Quicksort.java
Normal file
@@ -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<Integer> quicksort(List<Integer> 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<Integer> less = list.stream().skip(1).filter(el -> el <= pivot)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// sub-array of all the elements greater than the pivot
|
||||
List<Integer> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class PriceOfGroceries {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Map<String, Double> 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}
|
||||
}
|
||||
}
|
||||
21
05_hash_tables/java/02_check_voter/src/CheckVoter.java
Normal file
21
05_hash_tables/java/02_check_voter/src/CheckVoter.java
Normal file
@@ -0,0 +1,21 @@
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class CheckVoter {
|
||||
private static Map<String, Boolean> 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!
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import java.util.*;
|
||||
|
||||
public class BreadthFirstSearch {
|
||||
private static Map<String, List<String>> graph = new HashMap<>();
|
||||
|
||||
private static boolean search(String name) {
|
||||
Queue<String> searchQueue = new ArrayDeque<>(graph.get(name));
|
||||
// This list is how you keep track of which people you've searched before.
|
||||
List<String> 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");
|
||||
}
|
||||
}
|
||||
@@ -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<String, Map<String, Double>> graph = new HashMap<>();
|
||||
private static List<String> processed = new ArrayList<>();
|
||||
|
||||
private static String findLowestCostNode(Map<String, Double> costs) {
|
||||
Double lowestCost = Double.POSITIVE_INFINITY;
|
||||
String lowestCostNode = null;
|
||||
|
||||
// Go through each node
|
||||
for (Map.Entry<String, Double> 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<String, Double> costs = new HashMap<>();
|
||||
costs.put("a", 6.0);
|
||||
costs.put("b", 2.0);
|
||||
costs.put("fin", Double.POSITIVE_INFINITY);
|
||||
|
||||
// the parents table
|
||||
Map<String, String> 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<String, Double> 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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import java.util.*;
|
||||
|
||||
public class SetCovering {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Set<String> statesNeeded = new HashSet(Arrays.asList("mt", "wa", "or", "id", "nv", "ut", "ca", "az"));
|
||||
Map<String, Set<String>> 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<String> finalStations = new HashSet<String>();
|
||||
while (!statesNeeded.isEmpty()) {
|
||||
String bestStation = null;
|
||||
Set<String> statesCovered = new HashSet<>();
|
||||
|
||||
for (Map.Entry<String, Set<String>> station : stations.entrySet()) {
|
||||
Set<String> 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]
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user