[] adj;
18 | private static boolean[] marked;
19 | private static int[] dist;
20 |
21 | public static void main(String[] args) {
22 |
23 | Scanner in = new Scanner(System.in);
24 | createGraph(in);
25 |
26 | int s = in.nextInt();
27 | marked = new boolean[adj.length];
28 | dist = new int[adj.length];
29 |
30 | marked[s] = true;
31 | dist[s] = 0;
32 |
33 | dfs(s);
34 | System.out.println(Arrays.toString(dist));
35 | }
36 |
37 | private static void dfs(int i) {
38 | for (int v : adj[i]) {
39 | if (!marked[v]) {
40 | marked[v] = true;
41 | dist[v] = dist[i] + 1;
42 | dfs(v);
43 | }
44 | }
45 | }
46 |
47 | private static void createGraph(Scanner in) {
48 | // Vertices
49 | int v = in.nextInt();
50 | adj = new LinkedList[v];
51 | for (int i = 0; i < v; i++) {
52 | adj[i] = new LinkedList<>();
53 | }
54 |
55 | // Edges
56 | int e = in.nextInt();
57 | for (int i = 0; i < e; i++) {
58 | int v1 = in.nextInt();
59 | int v2 = in.nextInt();
60 | adj[v1].add(v2);
61 | }
62 | }
63 |
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/algorithms/sorting/HeapSort.java:
--------------------------------------------------------------------------------
1 | package algorithms.sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class HeapSort {
7 |
8 | public static void main(String[] args) {
9 | Scanner in = new Scanner(System.in);
10 | int t = in.nextInt();
11 |
12 | int n[] = new int[t];
13 | for (int i = 0; i < t; i++) {
14 | n[i] = in.nextInt();
15 | }
16 |
17 | for (int i = 0; i < (t / 2 - 1); i++) {
18 | heapify(n, i, n.length);
19 | }
20 | System.out.println(Arrays.toString(n));
21 |
22 | int heapsize = n.length;
23 | for (int i = n.length - 1; i > 0; i--) {
24 | swap(n, 0, i);
25 | heapsize--;
26 | heapify(n, 0, heapsize);
27 | System.out.println(Arrays.toString(n));
28 | }
29 | System.out.println(Arrays.toString(n));
30 | }
31 |
32 | private static void heapify(int[] n, int i, int size) {
33 | int l = left(i);
34 | int r = right(i);
35 | int largest = i;
36 | if (l < size && n[l] > n[i]) {
37 | largest = l;
38 | }
39 | if (r < size && n[r] > n[largest]) {
40 | largest = r;
41 | }
42 | if (largest != i) {
43 | swap(n, largest, i);
44 | heapify(n, largest, size);
45 | }
46 | }
47 |
48 | private static void swap(int[] n, int i, int j) {
49 | int temp = n[i];
50 | n[i] = n[j];
51 | n[j] = temp;
52 | }
53 |
54 | private static int right(int i) {
55 | return 2 * i + 2;
56 | }
57 |
58 | private static int left(int i) {
59 | return 2 * i + 1;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/algorithms/sorting/InsertionSort.java:
--------------------------------------------------------------------------------
1 | package algorithms.sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class InsertionSort {
7 |
8 | public static void main(String[] args) {
9 | Scanner in = new Scanner(System.in);
10 | int t = in.nextInt();
11 |
12 | int n[] = new int[t];
13 | for (int i = 0; i < t; i++) {
14 | n[i] = in.nextInt();
15 | }
16 | sort(n);
17 | System.out.println(Arrays.toString(n));
18 | }
19 |
20 | private static void sort(int[] n) {
21 | for (int i = 1; i < n.length; i++) {
22 | int k = n[i];
23 | int j = i - 1;
24 | while (j >= 0 && n[j] > k) {
25 | n[j + 1] = n[j];
26 | j--;
27 | }
28 | n[j + 1] = k;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/algorithms/sorting/MergeSort.java:
--------------------------------------------------------------------------------
1 | package algorithms.sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class MergeSort {
7 |
8 | public static void main(String[] args) {
9 | Scanner in = new Scanner(System.in);
10 | int t = in.nextInt();
11 |
12 | int n[] = new int[t];
13 | for (int i = 0; i < t; i++) {
14 | n[i] = in.nextInt();
15 | }
16 | sort(n, 0, n.length - 1);
17 | System.out.println(Arrays.toString(n));
18 | }
19 |
20 | private static void sort(int[] n, int p, int r) {
21 | if (p < r) {
22 | int q = (p + r) / 2;
23 | sort(n, p, q);
24 | sort(n, q + 1, r);
25 | merge(n, p, q, r);
26 | }
27 | }
28 |
29 | private static void merge(int[] n, int p, int q, int r) {
30 | int n1 = q - p + 1;
31 | int n2 = r - q;
32 |
33 | int left[] = new int[n1 + 1];
34 | int right[] = new int[n2 + 1];
35 | System.arraycopy(n, p, left, 0, n1);
36 | System.arraycopy(n, q + 1, right, 0, n2);
37 |
38 | left[n1] = Integer.MAX_VALUE;
39 | right[n2] = Integer.MAX_VALUE;
40 |
41 | int k = p;
42 | int i = 0, j = 0;
43 | while (k <= r) {
44 | if (left[i] <= right[j]) {
45 | n[k] = left[i];
46 | i++;
47 | } else {
48 | n[k] = right[j];
49 | j++;
50 | }
51 | k++;
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/algorithms/sorting/QuickSort.java:
--------------------------------------------------------------------------------
1 | package algorithms.sorting;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | public class QuickSort {
7 |
8 | public static void main(String[] args) {
9 | Scanner in = new Scanner(System.in);
10 | int t = in.nextInt();
11 |
12 | int n[] = new int[t];
13 | for (int i = 0; i < t; i++) {
14 | n[i] = in.nextInt();
15 | }
16 |
17 | sort(n, 0, n.length - 1);
18 | System.out.println(Arrays.toString(n));
19 | }
20 |
21 | private static void sort(int[] n, int start, int end) {
22 | if (start < end) {
23 | int mid = partition(n, start, end);
24 | sort(n, start, mid - 1);
25 | sort(n, mid + 1, end);
26 | }
27 | }
28 |
29 | private static int partition(int[] n, int start, int end) {
30 | int x = n[end];
31 | int j = start, i = start - 1;
32 | while (j < end) {
33 | if (n[j] < x) {
34 | i++;
35 | swap(n, i, j);
36 | }
37 | j++;
38 | }
39 | swap(n, i + 1, end);
40 | return i + 1;
41 | }
42 |
43 | private static void swap(int[] n, int i, int j) {
44 | int temp = n[i];
45 | n[i] = n[j];
46 | n[j] = temp;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/book/crackingcodinginterview/OneAway.java:
--------------------------------------------------------------------------------
1 | package book.crackingcodinginterview;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Given 2 strings print true if one string can be transformed into another
7 | * by only changing/removing/adding one character
8 | */
9 | public class OneAway {
10 |
11 | public static void main(String[] args) {
12 |
13 | Scanner in = new Scanner(System.in);
14 | String s1 = in.next();
15 | String s2 = in.next();
16 | int n1 = s1.length();
17 | int n2 = s2.length();
18 |
19 | if (Math.abs(n1 - n2) > 1) {
20 | System.out.println(false);
21 | } else {
22 | int c = 0;
23 | for (int i = 0, j = 0; i < n1 && j < n2; i++, j++) {
24 | if (s1.charAt(i) != s2.charAt(j)) {
25 | if (i + 1 < n1 && s1.charAt(i + 1) == s2.charAt(j)) {
26 | i++;
27 | } else if (j + 1 < n2 && s1.charAt(i) == s2.charAt(j + 1)) {
28 | j++;
29 | }
30 | c++;
31 | }
32 | }
33 | if (c <= 1) {
34 | System.out.println(true);
35 | } else {
36 | System.out.println(false);
37 | }
38 | }
39 |
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/book/crackingcodinginterview/RotateMatrix.java:
--------------------------------------------------------------------------------
1 | package book.crackingcodinginterview;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Rotate n*n matrix in-place
7 | */
8 | public class RotateMatrix {
9 |
10 | public static void main(String[] args) {
11 |
12 | Scanner in = new Scanner(System.in);
13 | int n = in.nextInt();
14 | int m[][] = getInput(in, n);
15 |
16 | for (int i = 0; i < n / 2; i++) {
17 | for (int j = i; j < n - i - 1; j++) {
18 | int temp = m[i][j];
19 | m[i][j] = m[n - j - 1][i];
20 | m[n - j - 1][i] = m[n - j - 1][n - i - 1];
21 | m[n - j - 1][n - i - 1] = m[j][n - i - 1];
22 | m[j][n - i - 1] = temp;
23 | }
24 | }
25 |
26 | print(m);
27 | }
28 |
29 | private static void print(int m[][]) {
30 | for (int i = 0; i < m.length; i++) {
31 | for (int j = 0; j < m[i].length; j++) {
32 | System.out.print(m[i][j] + " ");
33 | }
34 | System.out.println();
35 | }
36 | }
37 |
38 | private static int[][] getInput(Scanner in, int n) {
39 | int[][] m = new int[n][n];
40 | for (int i = 0; i < n; i++) {
41 | for (int j = 0; j < n; j++) {
42 | m[i][j] = in.nextInt();
43 | }
44 | }
45 | return m;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/daily/Problem_12_Number_Of_Ways_To_Climb_Stairs.java:
--------------------------------------------------------------------------------
1 | package daily;
2 |
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time.
8 | * Given N, write a function that returns the number of unique ways you can climb the staircase.
9 | * The order of the steps matters.
10 | *
11 | * For example, if N is 4, then there are 5 unique ways:
12 | *
13 | * 1, 1, 1, 1
14 | * 2, 1, 1
15 | * 1, 2, 1
16 | * 1, 1, 2
17 | * 2, 2
18 | *
19 | * What if, instead of being able to climb 1 or 2 steps at a time,
20 | * you could climb any number from a set of positive integers X?
21 | * For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
22 | */
23 | public class Problem_12_Number_Of_Ways_To_Climb_Stairs {
24 |
25 | public static void main(String[] args) {
26 |
27 | int N = 4;
28 | int[] memo = new int[N + 1];
29 | Arrays.fill(memo, 0);
30 |
31 | int ways = countWays(N, memo, 0);
32 | System.out.println(ways);
33 | }
34 |
35 | private static int countWays(int steps, int[] memo, int count) {
36 |
37 | if (steps == 1 || steps == 2) {
38 | return steps;
39 | }
40 |
41 | if (memo[steps] != 0) {
42 | return memo[steps];
43 | }
44 |
45 | count = countWays(steps - 1, memo, count) + countWays(steps - 2, memo, count);
46 | memo[steps] = count;
47 | return count;
48 | }
49 | }
50 |
51 |
52 |
--------------------------------------------------------------------------------
/src/main/java/daily/Problem_9_Max_Sum_Non_Adjacent.java:
--------------------------------------------------------------------------------
1 | package daily;
2 |
3 |
4 | import java.util.Arrays;
5 |
6 | public class Problem_9_Max_Sum_Non_Adjacent {
7 |
8 | public static void main(String[] args) {
9 | // int[] numbers = {1, 0, 3, 9, 2};
10 | // int[] numbers = {2, 4, 6, 2, 5};
11 | int[] numbers = {5, 1, 1, 5};
12 | maxNonAdjacentSum(numbers);
13 | }
14 |
15 | private static void maxNonAdjacentSum(int[] numbers) {
16 |
17 | int[] memo = new int[numbers.length];
18 | Arrays.fill(memo, Integer.MIN_VALUE);
19 |
20 | int max = maxSumAt(numbers, memo, 0);
21 | System.out.println(max);
22 | }
23 |
24 | private static int maxSumAt(int[] numbers, int[] memo, int index) {
25 |
26 | if (index >= numbers.length) {
27 | return 0;
28 | }
29 |
30 | if (memo[index] >= 0) {
31 | return memo[index];
32 | }
33 |
34 | int maxWithCurrent = numbers[index] + maxSumAt(numbers, memo, index + 2);
35 | int maxWithNext = maxSumAt(numbers, memo, index + 1);
36 | int max = Math.max(maxWithCurrent, maxWithNext);
37 | memo[index] = max;
38 | return max;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/geeksforgeeks/ChocolateDistribution.java:
--------------------------------------------------------------------------------
1 | package geeksforgeeks;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * http://www.geeksforgeeks.org/chocolate-distribution-problem/
7 | */
8 | public class ChocolateDistribution {
9 | public static void main(String[] args) {
10 | System.out.println(findMinDiff(new int[]{7, 3, 2, 4, 9, 12, 56}, 3));
11 | System.out.println(findMinDiff(new int[]{3, 4, 1, 9, 56, 7, 9, 12}, 5));
12 | System.out.println(findMinDiff(new int[]{12, 4, 7, 9, 2, 23, 25, 41,
13 | 30, 40, 28, 42, 30, 44, 48,
14 | 43, 50}, 7));
15 | }
16 |
17 | private static int findMinDiff(int[] arr, int m) {
18 | if (arr == null || arr.length == 0) {
19 | return -1;
20 | }
21 | if (m > arr.length) {
22 | return -1;
23 | }
24 |
25 | Arrays.sort(arr);
26 |
27 | int minDiff = Integer.MAX_VALUE;
28 | for (int i = 0; i + m - 1 < arr.length; i++) {
29 | int diff = arr[i + m - 1] - arr[i];
30 | if (diff < minDiff) {
31 | minDiff = diff;
32 | }
33 | }
34 |
35 | return minDiff;
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/geeksforgeeks/FindPerimeteFromMatrix.java:
--------------------------------------------------------------------------------
1 | package geeksforgeeks;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/find-perimeter-shapes-formed-1s-binary-matrix/
5 | */
6 | public class FindPerimeteFromMatrix {
7 | public static void main(String[] args) {
8 | System.out.println(solve(new int[][]{
9 | {0, 1, 0, 0, 0},
10 | {1, 1, 1, 0, 0},
11 | {1, 0, 0, 0, 0},
12 | }));
13 | }
14 |
15 | private static int solve(int[][] values) {
16 |
17 | int m = values.length;
18 | int n = values[0].length;
19 |
20 | int perimeter = 0;
21 | for (int i = 0; i < m; i++) {
22 | for (int j = 0; j < n; j++) {
23 | if (values[i][j] == 1) {
24 | perimeter += 4;
25 | if (isOne(values, i + 1, j)) {
26 | perimeter--;
27 | }
28 | if (isOne(values, i, j + 1)) {
29 | perimeter--;
30 | }
31 | if (isOne(values, i - 1, j)) {
32 | perimeter--;
33 | }
34 | if (isOne(values, i, j - 1)) {
35 | perimeter--;
36 | }
37 | }
38 | }
39 | }
40 |
41 | return perimeter;
42 | }
43 |
44 | private static boolean isOne(int[][] values, int i, int j) {
45 | return i >= 0 && j >= 0
46 | && i < values.length && j < values[0].length
47 | && values[i][j] == 1;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/geeksforgeeks/TrappingRainWater.java:
--------------------------------------------------------------------------------
1 | package geeksforgeeks;
2 |
3 | /**
4 | * http://www.geeksforgeeks.org/trapping-rain-water/
5 | */
6 | public class TrappingRainWater {
7 | public static void main(String[] args) {
8 | System.out.println(solve(new int[]{2, 0, 2}));
9 | System.out.println(solve(new int[]{3, 0, 0, 2, 0, 4}));
10 | System.out.println(solve(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
11 | }
12 |
13 | private static int solve(int[] heights) {
14 |
15 | int n = heights.length;
16 | int left[] = new int[n];
17 | int right[] = new int[n];
18 |
19 | left[0] = heights[0];
20 | for (int i = 1; i < n; i++) {
21 | left[i] = Math.max(left[i - 1], heights[i]);
22 | }
23 |
24 | right[n - 1] = heights[n - 1];
25 | for (int i = n - 2; i >= 0; i--) {
26 | right[i] = Math.max(right[i + 1], heights[i]);
27 | }
28 |
29 | int water = 0;
30 | for (int i = 0; i < n; i++) {
31 | water += Math.min(left[i], right[i]) - heights[i];
32 | }
33 |
34 | return water;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/general/java/LargestNFromBillion.java:
--------------------------------------------------------------------------------
1 | package general.java;
2 |
3 | import java.util.Scanner;
4 | import java.util.TreeSet;
5 |
6 | /**
7 | * Find largest 10 integers from say, a billion integers.
8 | *
9 | * Trick is not to store any of the billion integers neither to sort them.
10 | * Only thing to care about is the list of top 10 integers
11 | *
12 | * Sample input
13 | * 14
14 | * 1 2 3 4 5 6 7 9 0 12 43 56 34 23
15 | */
16 | public class LargestNFromBillion {
17 |
18 | private static final int THRESHOLD = 10;
19 | private static final TreeSet set = new TreeSet<>();
20 |
21 | public static void main(String[] args) {
22 | Scanner in = new Scanner(System.in);
23 | int n = in.nextInt();
24 |
25 | for (int j = 0; j < n; j++) {
26 | int i = in.nextInt();
27 | addIfBigger(i);
28 | }
29 |
30 | System.out.println(set);
31 | }
32 |
33 | private static void addIfBigger(int i) {
34 | // If considering concurrency, then use read and write locks
35 | if (set.size() < THRESHOLD) {
36 | set.add(i);
37 | } else if (i > set.first() && !set.contains(i)) {
38 | // Contains check necessary to avoid adding duplicate and accidentally removing smallest
39 | set.pollFirst();
40 | set.add(i);
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/general/java/criteriaqueue/Criteria.java:
--------------------------------------------------------------------------------
1 | package general.java.criteriaqueue;
2 |
3 | public interface Criteria {
4 | String getCriteria();
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/general/java/criteriaqueue/test/Candy.java:
--------------------------------------------------------------------------------
1 | package general.java.criteriaqueue.test;
2 |
3 | import general.java.criteriaqueue.Criteria;
4 |
5 | public class Candy implements Criteria {
6 |
7 | private String color;
8 |
9 | public Candy(String color) {
10 | this.color = color;
11 | }
12 |
13 | @Override
14 | public String getCriteria() {
15 | return color;
16 | }
17 |
18 | @Override
19 | public String toString() {
20 | return "Candy{" +
21 | "color='" + color + '\'' +
22 | '}';
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/general/java/criteriaqueue/test/CandyFactory.java:
--------------------------------------------------------------------------------
1 | package general.java.criteriaqueue.test;
2 |
3 | import java.util.Random;
4 |
5 | public class CandyFactory {
6 |
7 | public static final String[] colors = {"RED", "GREEN", "BLUE"};
8 | public static final Random random = new Random();
9 |
10 | public static Candy getCandy() {
11 | String color = colors[random.nextInt(colors.length)];
12 | return new Candy(color);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/general/java/elevator/Direction.java:
--------------------------------------------------------------------------------
1 | package general.java.elevator;
2 |
3 | public enum Direction {
4 | UP, DOWN, STOP
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/general/java/elevator/Floor.java:
--------------------------------------------------------------------------------
1 | package general.java.elevator;
2 |
3 | public class Floor {
4 |
5 | private final int number;
6 | private final boolean isMax;
7 | private final boolean isMin;
8 | private boolean lightStatus;
9 | private FloorRequestManager requestManager;
10 |
11 | public Floor(int floorNumber, boolean isMax, boolean isMin, FloorRequestManager requestManager) {
12 | this.number = floorNumber;
13 | this.isMax = isMax;
14 | this.isMin = isMin;
15 | this.requestManager = requestManager;
16 | this.lightStatus = false;
17 | }
18 |
19 | public void request(Direction direction) {
20 | if (direction == Direction.DOWN) {
21 | requestDown();
22 | } else if (direction == Direction.UP) {
23 | requestUp();
24 | }
25 | }
26 |
27 | public void requestUp() {
28 | if (!isMax) {
29 | requestManager.addRequest(Direction.UP, number);
30 | }
31 | }
32 |
33 | public void requestDown() {
34 | if (!isMin) {
35 | requestManager.addRequest(Direction.DOWN, number);
36 | }
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/general/java/elevator/test/TestElevatorSystem.java:
--------------------------------------------------------------------------------
1 | package general.java.elevator.test;
2 |
3 | import general.java.elevator.Direction;
4 | import general.java.elevator.ElevatorSystemManager;
5 |
6 | public class TestElevatorSystem {
7 |
8 | public static void main(String[] args) throws InterruptedException {
9 | ElevatorSystemManager system = new ElevatorSystemManager(4, 0, 10);
10 |
11 | // Elevator requests
12 | system.addElevatorRequest(1, 3);
13 | system.addElevatorRequest(2, 6);
14 | system.addElevatorRequest(3, 8);
15 |
16 | // Floor requests
17 | system.addFloorRequest(Direction.UP, 4);
18 | system.addFloorRequest(Direction.DOWN, 10);
19 |
20 | while (true) {
21 | system.logState();
22 | Thread.sleep(1000);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/google/codejam/y2016/qualification/CountingSheep.java:
--------------------------------------------------------------------------------
1 | package google.codejam.y2016.qualification;
2 |
3 | import java.util.HashSet;
4 | import java.util.Scanner;
5 | import java.util.Set;
6 |
7 | /**
8 | * https://code.google.com/codejam/contest/6254486/dashboard#s=p0
9 | */
10 | public class CountingSheep {
11 |
12 | public static void main(String[] args) {
13 |
14 | Scanner in = new Scanner(System.in);
15 | int t = in.nextInt();
16 | for (int i = 0; i < t; i++) {
17 | int n = in.nextInt();
18 | if (n == 0) {
19 | System.out.printf("case #%d: INSOMNIA\n", i + 1);
20 | } else {
21 | Set d = digits();
22 | int v = 0;
23 | for (int j = 1; !d.isEmpty(); j++) {
24 | v = n * j;
25 | removeDigits(d, v);
26 | }
27 | System.out.printf("case #%d: %d\n", i + 1, v);
28 | }
29 | }
30 | }
31 |
32 | private static void removeDigits(Set d, int n) {
33 | while (n > 0) {
34 | d.remove(n % 10);
35 | n = n / 10;
36 | }
37 | }
38 |
39 | private static Set digits() {
40 | Set digits = new HashSet<>(10);
41 | for (int i = 0; i < 10; i++) {
42 | digits.add(i);
43 | }
44 | return digits;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/google/codejam/y2016/round1a/BestFriend.java:
--------------------------------------------------------------------------------
1 | package google.codejam.y2016.round1a;
2 |
3 | import java.util.HashSet;
4 | import java.util.Scanner;
5 | import java.util.Set;
6 |
7 | /**
8 | * https://code.google.com/codejam/contest/4304486/dashboard#s=p2
9 | *
10 | * First and last person in the circle need to be friend?
11 | */
12 | public class BestFriend {
13 |
14 | public static void main(String[] args) {
15 |
16 | Scanner in = new Scanner(System.in);
17 | int t = in.nextInt();
18 | for (int k = 0; k < t; k++) {
19 |
20 | int n = in.nextInt();
21 | int[] bff = new int[n + 1];
22 | for (int i = 1; i <= n; i++) {
23 | bff[i] = in.nextInt();
24 | }
25 |
26 | int max = 0;
27 | for (int i = 1; i <= n; i++) {
28 |
29 | int f = i;
30 | Set chain = new HashSet<>();
31 | while (!chain.contains(f)) {
32 | chain.add(f);
33 | f = bff[f];
34 | }
35 |
36 | // Special case where child has 2 best friends
37 | if (frequency(bff, i) > 1) {
38 | max = Math.max(max, chain.size() + 1);
39 | } else {
40 | max = Math.max(max, chain.size());
41 | }
42 | }
43 |
44 | System.out.printf("Case #%d: %d\n", k + 1, max);
45 | }
46 |
47 |
48 | }
49 |
50 | private static int frequency(int[] bff, int i) {
51 | int ctr = 0;
52 | for (int j = 0; j < bff.length; j++) {
53 | if (i == bff[j]) {
54 | ctr++;
55 | }
56 | }
57 | return ctr;
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/google/codejam/y2016/round1a/TheLastWord.java:
--------------------------------------------------------------------------------
1 | package google.codejam.y2016.round1a;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://code.google.com/codejam/contest/4304486/dashboard#s=p0
7 | */
8 | public class TheLastWord {
9 |
10 | public static void main(String[] args) {
11 |
12 | Scanner in = new Scanner(System.in);
13 | int t = in.nextInt();
14 | for (int i = 0; i < t; i++) {
15 | String s1 = in.next();
16 | String s2 = String.valueOf(s1.charAt(0));
17 | for (int j = 1; j < s1.length(); j++) {
18 | char c = s1.charAt(j);
19 | if (c >= s2.charAt(0)) {
20 | s2 = c + s2;
21 | } else {
22 | s2 = s2 + c;
23 | }
24 | }
25 | System.out.printf("Case #%d: %s\n", i + 1, s2);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/google/kickstart_2019/practice/interactive/Solution.java:
--------------------------------------------------------------------------------
1 | package google.kickstart_2019.practice.interactive;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.InputStreamReader;
5 | import java.util.Scanner;
6 |
7 | public class Solution {
8 | public static void main(String[] args) {
9 | Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
10 | int t = in.nextInt();
11 | for (int i = 1; i <= t; ++i) {
12 | int start = in.nextInt();
13 | int end = in.nextInt();
14 | int tries = in.nextInt();
15 |
16 | for (int j = 0; j < tries; j++) {
17 |
18 | int mid = start + (end - start) / 2;
19 | System.out.print(mid);
20 |
21 | String result = in.next();
22 | if (result.equals("CORRECT")) {
23 | break;
24 | } else if (result.equals("TOO_SMALL")) {
25 | start = mid;
26 | } else {
27 | end = mid;
28 | }
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/google/practice/MaxCountOfCharInString.java:
--------------------------------------------------------------------------------
1 | package google.practice;
2 |
3 | /**
4 | * Most common character in string - Classic interview question
5 | * So many assumptions and possible answers
6 | *
7 | * https://drive.google.com/file/d/0B6CeOmhX0PsWX0c2azQtYWFWTmc/view
8 | * https://www.youtube.com/watch?v=MyFxMpKn7yk&feature=youtu.be
9 | *
10 | * Assumptions - Only a-z or include special characters? Case-sensitive?
11 | */
12 | public class MaxCountOfCharInString {
13 |
14 | public static void main(String[] args) {
15 | String inputStr = "This is a small quick fox jumping over a log.";
16 |
17 | // System.out.println(caseInSensitive()); // array of size 26
18 | // System.out.println(caseSensitive()); // array of size 52
19 | // System.out.println(noWastedSpace()); // hashmap
20 | // System.out.println(multithreaded()); // accumulators (concurrency) / fork-join
21 | // System.out.println(distributed()); // split string and map-reduce
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/google/practice/SortArrayInPlaceOf012.java:
--------------------------------------------------------------------------------
1 | package google.practice;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Sort array in place, which consists of only 0, 1 and 2
7 | */
8 | public class SortArrayInPlaceOf012 {
9 | public static void main(String[] args) {
10 | System.out.println(Arrays.toString(sort(new int[]{0, 1, 2, 2, 1, 0})));
11 | System.out.println(Arrays.toString(sort2(new int[]{0, 1, 2, 2, 1, 0})));
12 | }
13 |
14 | private static int[] sort2(int[] ints) {
15 | int repIndex = 0;
16 | for (int i = 0; i < 3; i++) {
17 | int curIndex = 0;
18 | while (curIndex < ints.length) {
19 | if (ints[curIndex] == i) {
20 | swap(ints, curIndex, repIndex);
21 | repIndex++;
22 | }
23 | curIndex++;
24 | }
25 | }
26 | return ints;
27 | }
28 |
29 | private static void swap(int[] ints, int curIndex, int repIndex) {
30 | int tmp = ints[curIndex];
31 | ints[curIndex] = ints[repIndex];
32 | ints[repIndex] = tmp;
33 | }
34 |
35 | public static int[] sort(int[] a) {
36 | int[] counts = new int[3];
37 | for (int val : a) {
38 | counts[val]++;
39 | }
40 |
41 | int index = 0;
42 | for (int i = 0; i < 3; i++) {
43 | for (int j = 0; j < counts[i]; j++) {
44 | a[index++] = i;
45 | }
46 | }
47 | return a;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/main/java/hackerearth/challenge/lenskart/EndGame.java:
--------------------------------------------------------------------------------
1 | package hackerearth.challenge.lenskart;
2 |
3 |
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerearth.com/lenskart-hiring-challenge/algorithm/end-game/
8 | *
9 | * Cheated - https://www.hackerearth.com/submission/5006471/
10 | **/
11 | public class EndGame {
12 |
13 | public static void main(String[] args) {
14 | Scanner in = new Scanner(System.in);
15 |
16 | int T = in.nextInt();
17 | for (int i = 0; i < T; i++) {
18 | long n = in.nextLong();
19 | long a = in.nextLong();
20 | long b = in.nextLong();
21 | long c = in.nextLong();
22 | long d = in.nextLong();
23 | long Move = in.nextInt();
24 |
25 | // Crux = moves(black to reach n) < moves(white to catch up)
26 | // constraints = black/white to stay within board
27 | // constraints = black not be (1,n) , (2,n) , (1,n-1) , (2,n-1) , (a,b)
28 |
29 | if (Move == 0) {
30 | if (c >= a && Math.abs(d - b) <= (n - a)) {
31 | System.out.println("Draw");
32 | } else {
33 | System.out.println("White Wins");
34 | }
35 | } else {
36 | if (c >= a - 1 && Math.abs(d - b) <= (n - a + 1)) {
37 | System.out.println("Draw");
38 | } else {
39 | System.out.println("White Wins");
40 | }
41 | }
42 |
43 | }
44 | }
45 |
46 | }
47 |
48 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/ACMICPCTeam.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * https://www.hackerrank.com/challenges/acm-icpc-team
9 | */
10 | public class ACMICPCTeam {
11 |
12 | public static void main(String[] args) {
13 | Scanner in = new Scanner(System.in);
14 | int n = in.nextInt();
15 | int m = in.nextInt();
16 |
17 | List v = new ArrayList<>();
18 | for (int i = 0; i < n; i++) {
19 | v.add(in.next());
20 | }
21 |
22 | int max = 0;
23 | int tsize = 1;
24 | for (int i = 0; i < n; i++) {
25 | for (int j = i + 1; j < n; j++) {
26 | int count = or(v.get(i), v.get(j));
27 | if (count == max) {
28 | tsize++;
29 | } else if (count > max) {
30 | max = count;
31 | tsize = 1;
32 | }
33 | }
34 | }
35 | System.out.println(max);
36 | System.out.println(tsize);
37 | }
38 |
39 | private static int or(String s1, String s2) {
40 | int c = 0;
41 | for (int i = 0; i < s1.length(); i++) {
42 | if (s1.charAt(i) == '1' || s2.charAt(i) == '1') {
43 | c++;
44 | }
45 | }
46 | return c;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/AngryProfessor.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/angry-professor
7 | */
8 | public class AngryProfessor {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int cases = in.nextInt();
13 |
14 | for (int i = 0; i < cases; i++) {
15 | int n = in.nextInt();
16 | int k = in.nextInt();
17 | int pre = 0;
18 | for (int j = 0; j < n; j++) {
19 | if (in.nextInt() <= 0) {
20 | pre++;
21 | }
22 | }
23 | if (pre >= k) {
24 | System.out.println("NO");
25 | } else {
26 | System.out.println("YES");
27 | }
28 |
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/BeautifulTriplets.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * https://www.hackerrank.com/challenges/beautiful-triplets
9 | */
10 | public class BeautifulTriplets {
11 |
12 | public static void main(String[] args) {
13 | Scanner in = new Scanner(System.in);
14 | int n = in.nextInt();
15 | int d = in.nextInt();
16 | List a = new ArrayList<>();
17 | for (int i = 0; i < n; i++) {
18 | a.add(in.nextInt());
19 | }
20 |
21 | int tc = 0;
22 | for (int i = 0; i < n; i++) {
23 |
24 | int v = a.get(i);
25 | if (a.contains(v + d) && a.contains(v + d + d)) {
26 | tc++;
27 | }
28 | }
29 | System.out.println(tc);
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/ChocolateFeast.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/chocolate-feast
7 | */
8 | public class ChocolateFeast {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 |
14 | for (int i = 0; i < t; i++) {
15 | int n = in.nextInt();
16 | int c = in.nextInt();
17 | int m = in.nextInt();
18 |
19 | int ctr = n / c;
20 | int w = n / c;
21 | while (w >= m) {
22 | int ch = w / m;
23 | w = ch + (w % m);
24 | ctr += ch;
25 | }
26 | System.out.println(ctr);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/CutTheSticks.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.List;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * https://www.hackerrank.com/challenges/cut-the-sticks
10 | */
11 | public class CutTheSticks {
12 |
13 | public static void main(String[] args) {
14 | Scanner in = new Scanner(System.in);
15 | int n = in.nextInt();
16 |
17 | List sticks = new ArrayList<>();
18 | for (int i = 0; i < n; i++) {
19 | sticks.add(in.nextInt());
20 | }
21 | cut(sticks);
22 | }
23 |
24 | private static void cut(List sticks) {
25 | if (!sticks.isEmpty()) {
26 | Integer min = Collections.min(sticks);
27 | sticks.replaceAll(s -> s - min);
28 | System.out.println(sticks.size());
29 | sticks.removeIf(s -> s <= 0);
30 | cut(sticks);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/DivisibleSumPairs.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/divisible-sum-pairs
7 | */
8 | public class DivisibleSumPairs {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | int k = in.nextInt();
14 | int a[] = new int[n];
15 | for (int i = 0; i < n; i++) {
16 | a[i] = in.nextInt();
17 | }
18 |
19 | int ctr = 0;
20 | for (int i = 0; i < n - 1; i++) {
21 | for (int j = i + 1; j < n; j++) {
22 | if ((a[i] + a[j]) % k == 0) {
23 | ctr++;
24 | }
25 | }
26 | }
27 | System.out.println(ctr);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/FairRations.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/fair-rations
7 | */
8 | public class FairRations {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 | int b[] = new int[t];
14 | for (int i = 0; i < t; i++) {
15 | b[i] = in.nextInt();
16 | }
17 |
18 | int l = 0;
19 | for (int i = 0; i < t - 1; i++) {
20 | if (b[i] % 2 == 1) {
21 | b[i] = b[i] + 1;
22 | b[i + 1] = b[i + 1] + 1;
23 | l += 2;
24 | }
25 | }
26 |
27 | if (b[t - 1] % 2 == 1) {
28 | System.out.println("NO");
29 | } else {
30 | System.out.println(l);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/FindDigits.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/find-digits
7 | */
8 | public class FindDigits {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 | for (int i = 0; i < t; i++) {
14 | long v = in.nextLong();
15 |
16 | long n = v;
17 | int c = 0;
18 | while (n > 0) {
19 | long d = n % 10;
20 | if (d != 0 && v % d == 0) {
21 | c++;
22 | }
23 | n = n / 10;
24 | }
25 | System.out.println(c);
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/FlatlandSpaceStations.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/flatland-space-stations
8 | */
9 | public class FlatlandSpaceStations {
10 |
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 | int t = in.nextInt();
14 | int k = in.nextInt();
15 |
16 | int[] n = new int[k];
17 | for (int i = 0; i < k; i++) {
18 | n[i] = in.nextInt();
19 | }
20 | Arrays.sort(n);
21 |
22 | int gap = Math.max(t - n[n.length - 1] - 1, n[0]);
23 | for (int i = 0; i < k - 1; i++) {
24 | gap = Math.max((n[i + 1] - n[i]) / 2, gap);
25 | }
26 | System.out.println(gap);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/FlippingTheMatrix.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/flipping-the-matrix
7 | */
8 | public class FlippingTheMatrix {
9 |
10 | public static void main(String[] args) {
11 |
12 | Scanner in = new Scanner(System.in);
13 | int q = in.nextInt();
14 | for (int r = 1; r <= q; r++) {
15 | int n = in.nextInt();
16 | int[][] m = new int[2 * n][2 * n];
17 | for (int i = 0; i < 2 * n; i++) {
18 | for (int j = 0; j < 2 * n; j++) {
19 | m[i][j] = in.nextInt();
20 | }
21 | }
22 | System.out.println(findMaxSum(m, n));
23 | }
24 |
25 | }
26 |
27 | private static int findMaxSum(int[][] m, int n) {
28 |
29 | int sum = 0;
30 | for (int i = 0; i < n; i++) {
31 | for (int j = 0; j < n; j++) {
32 | int a = m[i][j];
33 | int b = m[i][2 * n - j - 1];
34 | int c = m[2 * n - i - 1][j];
35 | int d = m[2 * n - i - 1][2 * n - j - 1];
36 |
37 | int max = Math.max(Math.max(Math.max(a, b), c), d);
38 | sum += max;
39 | }
40 | }
41 | return sum;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/JumpingOnTheClouds.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/jumping-on-the-clouds
7 | */
8 | public class JumpingOnTheClouds {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | int c[] = new int[n];
14 | for (int i = 0; i < n; i++) {
15 | c[i] = in.nextInt();
16 | }
17 |
18 | int jumps = 0;
19 | int i = 0;
20 | while (i < n - 1) {
21 | if (i + 2 < n && (c[i + 2] == 1 || c[i + 2] > n)) {
22 | i++;
23 | } else {
24 | i += 2;
25 | }
26 | jumps++;
27 | }
28 |
29 | System.out.println(jumps);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/JumpingTheCloudsRevisited.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.io.IOException;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited
8 | */
9 | public class JumpingTheCloudsRevisited {
10 |
11 | public static void main(String[] args) throws IOException {
12 |
13 | Scanner in = new Scanner(System.in);
14 | int t = in.nextInt();
15 | int k = in.nextInt();
16 |
17 | int units = t / k;
18 | int n[] = new int[t];
19 | for (int i = 0; i < t; i++) {
20 | n[i] = in.nextInt();
21 | }
22 |
23 | for (int i = 0; i < t; i++) {
24 | final int v = n[i];
25 | if (v == 1 && i % k == 0) {
26 | units += 2;
27 | }
28 | }
29 | System.out.println(100 - units);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/Kangaroo.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/kangaroo
7 | */
8 | public class Kangaroo {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int x1 = in.nextInt();
13 | int v1 = in.nextInt();
14 | int x2 = in.nextInt();
15 | int v2 = in.nextInt();
16 |
17 | // Rates and Starting point both
18 | if (x2 > x1 && v2 > v1) {
19 | System.out.println("NO");
20 | return;
21 | }
22 |
23 | boolean gapDecreasing = true;
24 | while (gapDecreasing) {
25 | if (x2 == x1) {
26 | System.out.println("YES");
27 | return;
28 | }
29 | int gap = x2 - x1;
30 | x1 = x1 + v1;
31 | x2 = x2 + v2;
32 | int newGap = x2 - x1;
33 | gapDecreasing = newGap < gap;
34 | }
35 | System.out.println("NO");
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/LarrysArray.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/larrys-array
7 | */
8 | public class LarrysArray {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 |
14 | for (int i = 0; i < t; i++) {
15 | int n = in.nextInt();
16 | int a[] = new int[n + 1];
17 |
18 | for (int j = 1; j <= n; j++) {
19 | a[j] = in.nextInt();
20 | }
21 |
22 | solve(a);
23 | }
24 | }
25 |
26 | private static void solve(int[] a) {
27 |
28 | int n = a.length - 1;
29 |
30 | // Brute force
31 | for (int i = 1; i <= n; i++) {
32 | for (int j = 1; j <= n - 2; j++) {
33 | for (int k = 0; k < 3 && !inOrder(a, j); k++) {
34 | rotate(a, j);
35 | }
36 | }
37 | }
38 |
39 | if (isSorted(a)) {
40 | System.out.println("YES");
41 | } else {
42 | System.out.println("NO");
43 | }
44 | }
45 |
46 | private static boolean isSorted(int[] a) {
47 | for (int i = 1; i < a.length - 1; i++) {
48 | if (a[i] > a[i + 1]) {
49 | return false;
50 | }
51 | }
52 | return true;
53 | }
54 |
55 | private static boolean inOrder(int[] a, int j) {
56 | return a[j] < a[j + 1] && a[j] < a[j + 2];
57 | }
58 |
59 | private static void rotate(int[] a, int i) {
60 | int temp = a[i];
61 | a[i] = a[i + 1];
62 | a[i + 1] = a[i + 2];
63 | a[i + 2] = temp;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/LibraryFine.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.time.LocalDate;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/library-fine
8 | */
9 | public class LibraryFine {
10 |
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 |
14 | LocalDate act = getDate(in);
15 | LocalDate exp = getDate(in);
16 |
17 | if (act.isBefore(exp) || act.isEqual(exp)) {
18 | System.out.println(0);
19 | } else if (act.getYear() != exp.getYear()) {
20 | System.out.println("10000");
21 | } else if (act.getMonthValue() != exp.getMonthValue()) {
22 | System.out.println((act.getMonthValue() - exp.getMonthValue()) * 500);
23 | } else {
24 | System.out.println((act.getDayOfMonth() - exp.getDayOfMonth()) * 15);
25 | }
26 | }
27 |
28 | public static LocalDate getDate(Scanner in) {
29 | int d = in.nextInt();
30 | int m = in.nextInt();
31 | int y = in.nextInt();
32 | return LocalDate.of(y, m, d);
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/LisaWorkbook.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/lisa-workbook
7 | */
8 | public class LisaWorkbook {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | int k = in.nextInt();
14 |
15 | int p[] = new int[n];
16 | for (int i = 0; i < n; i++) {
17 | p[i] = in.nextInt();
18 | }
19 |
20 | int page = 0;
21 | int special = 0;
22 | for (int i = 0; i < n; i++) {
23 | int t1 = 1;
24 | int t2 = Math.min(p[i], k);
25 | while (t2 <= p[i]) {
26 | page++;
27 | if (page >= t1 && page <= t2) {
28 | special++;
29 | }
30 | t1 = t2 + 1;
31 | t2 = t2 + Math.min(p[i] - t2 == 0 ? k : p[i] - t2, k);
32 | }
33 | }
34 | System.out.println(special);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/ManasaAndStones.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 | import java.util.Set;
5 | import java.util.TreeSet;
6 | import java.util.stream.Collectors;
7 |
8 | /**
9 | * https://www.hackerrank.com/challenges/manasa-and-stones
10 | */
11 | public class ManasaAndStones {
12 |
13 | public static void main(String[] args) {
14 | Scanner in = new Scanner(System.in);
15 | int t = in.nextInt();
16 |
17 | for (int i = 0; i < t; i++) {
18 | int s = in.nextInt();
19 | int a = in.nextInt();
20 | int b = in.nextInt();
21 |
22 | Set sol = new TreeSet<>();
23 |
24 | // solve(sol, 0, s - 1, a, b);
25 | for (int j = 0; j < s; j++) {
26 | sol.add(j * a + (s - j - 1) * b);
27 | }
28 | System.out.println(sol.stream().map(Object::toString).collect(Collectors.joining(" ")));
29 | }
30 | }
31 |
32 | // Correct but times out
33 | private static void solve(Set sol, int c, int s, int a, int b) {
34 | if (s == 0) {
35 | sol.add(c);
36 | } else {
37 | solve(sol, c + a, s - 1, a, b);
38 | solve(sol, c + b, s - 1, a, b);
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/MinimumDistances.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.HashMap;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/minimum-distances
8 | */
9 | public class MinimumDistances {
10 |
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 | int n = in.nextInt();
14 | HashMap a = new HashMap<>(n);
15 | int min = Integer.MAX_VALUE;
16 |
17 | for (int i = 0; i < n; i++) {
18 | int v = in.nextInt();
19 | if (a.containsKey(v) && min > i - a.get(v)) {
20 | min = i - a.get(v);
21 | }
22 | a.put(v, i);
23 | }
24 |
25 | System.out.println(min == Integer.MAX_VALUE ? -1 : min);
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/NewYearChaos.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/new-year-chaos
7 | */
8 | public class NewYearChaos {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 |
14 | for (int i = 0; i < t; i++) {
15 | int n = in.nextInt();
16 | int[] p = new int[n + 1];
17 | for (int j = 1; j <= n; j++) {
18 | p[j] = in.nextInt();
19 | }
20 | solve(p);
21 | }
22 | }
23 |
24 | private static void solve(int[] p) {
25 | int c = 1;
26 | int bribes = 0;
27 | while (c < p.length - 1) {
28 | if (p[c] > c) {
29 | if (p[c] - c > 2) {
30 | System.out.println("Too chaotic");
31 | return;
32 | } else {
33 | bribes += (p[c] - c);
34 | }
35 | } else if (p[c] > p[c + 1]) {
36 | bribes++;
37 | }
38 | c++;
39 | }
40 | System.out.println(bribes);
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/NonDivisibleSubset.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/non-divisible-subset/
7 | *
8 | * Cheated - I feel bad
9 | * https://www.hackerrank.com/challenges/non-divisible-subset/forum/comments/150647
10 | * https://github.com/charles-wangkai/hackerrank/blob/master/non-divisible-subset/Solution.java
11 | */
12 | public class NonDivisibleSubset {
13 |
14 | public static void main(String[] args) {
15 | Scanner in = new Scanner(System.in);
16 | int n = in.nextInt();
17 | int k = in.nextInt();
18 | int a[] = new int[n];
19 | int[] remainders = new int[k];
20 | for (int i = 0; i < n; i++) {
21 | a[i] = in.nextInt();
22 | remainders[a[i] % k]++;
23 | }
24 |
25 | int count = remainders[0] > 0 ? 1 : 0;
26 | for (int i = 1; i <= k / 2; i++) {
27 | int opp = k - i;
28 | if (i == opp && remainders[i] > 0) {
29 | count++;
30 | } else {
31 | count += Math.max(remainders[i], remainders[opp]);
32 | }
33 | }
34 |
35 | System.out.println(count);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/ServiceLane.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/service-lane
7 | */
8 | public class ServiceLane {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | int t = in.nextInt();
14 | int w[] = new int[n];
15 | for (int i = 0; i < n; i++) {
16 | w[i] = in.nextInt();
17 | }
18 |
19 | for (int i = 0; i < t; i++) {
20 | int en = in.nextInt();
21 | int ex = in.nextInt();
22 |
23 | int min = Integer.MAX_VALUE;
24 | for (int k = en; k <= ex; k++) {
25 | if (w[k] < min) {
26 | min = w[k];
27 | }
28 | }
29 | System.out.println(min);
30 | }
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/SherlockAndSquares.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/sherlock-and-squares
7 | */
8 | public class SherlockAndSquares {
9 |
10 | public static void main(String[] args) {
11 |
12 | Scanner in = new Scanner(System.in);
13 | int t = in.nextInt();
14 | for (int i = 0; i < t; i++) {
15 | long n1 = in.nextLong();
16 | long n2 = in.nextLong();
17 |
18 | int ctr = 0;
19 |
20 | // Instead of finding roots or all numbers, find root of first
21 | // increment, find square, check if in range... repeat
22 | long c = (long) Math.sqrt(n1);
23 | long sq = c * c;
24 | while (sq <= n2) {
25 | if (sq >= n1 && sq <= n2) {
26 | ctr++;
27 | }
28 | c++;
29 | sq = c * c;
30 | }
31 | System.out.println(ctr);
32 | }
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/StrangeCode.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.io.IOException;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/strange-code
8 | */
9 | public class StrangeCode {
10 |
11 | public static void main(String[] args) throws IOException {
12 |
13 | Scanner in = new Scanner(System.in);
14 | long t = in.nextLong();
15 |
16 | long t1 = 1;
17 | long n = 3;
18 |
19 | // convert to division operation
20 | while (t1 < t) {
21 | t1 = t1 + n;
22 | n = n * 2;
23 | }
24 | if (t1 == t) {
25 | System.out.println(n);
26 | } else {
27 | n = n / 2;
28 | t1 = t1 - n;
29 | System.out.println(n - (t - t1));
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/TaumAndBdays.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/taum-and-bday
7 | */
8 | public class TaumAndBdays {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int t = in.nextInt();
13 |
14 | for (int i = 0; i < t; i++) {
15 | long b = in.nextLong();
16 | long w = in.nextLong();
17 | long bc = in.nextLong();
18 | long wc = in.nextLong();
19 | long cc = in.nextLong();
20 |
21 | long total = 0;
22 |
23 | if ((bc + cc) < wc) {
24 | total = bc * b + (bc + cc) * w;
25 | } else if ((wc + cc) < bc) {
26 | total = (wc + cc) * b + wc * w;
27 | } else {
28 | total = bc * b + wc * w;
29 | }
30 | System.out.println(total);
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/implementation/UtopianTree.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.implementation;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/utopian-tree
7 | *
8 | * No fancy memoization, or tricks since constraints are so small
9 | */
10 | public class UtopianTree {
11 |
12 | public static void main(String[] args) {
13 | Scanner in = new Scanner(System.in);
14 | int t = in.nextInt();
15 | for (int i = 0; i < t; i++) {
16 | int n = in.nextInt();
17 |
18 | int h = 1;
19 | for (int j = 1; j <= n; j++) {
20 | if (j % 2 == 0) {
21 | h += 1;
22 | } else {
23 | h = h * 2;
24 | }
25 | }
26 | System.out.println(h);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/sorting/Intro.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.sorting;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/tutorial-intro
7 | */
8 | public class Intro {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int val = in.nextInt();
13 | int n = in.nextInt();
14 |
15 | for (int i = 0; i < n; i++) {
16 | if (in.nextInt() == val) {
17 | System.out.println(i);
18 | }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/AVeryBigSum.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/a-very-big-sum
7 | */
8 | public class AVeryBigSum {
9 | public static void main(String[] args) {
10 | Scanner sc = new Scanner(System.in);
11 | int n = sc.nextInt();
12 | long sum = 0;
13 | for (int i = 0; i < n; i++) {
14 | sum += sc.nextInt();
15 | }
16 | System.out.println(sum);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/CircularArrayRotation.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://www.hackerrank.com/challenges/circular-array-rotation
8 | */
9 | public class CircularArrayRotation {
10 | public static void main(String[] args) {
11 | Scanner sc = new Scanner(System.in);
12 | int n = sc.nextInt();
13 | int k = sc.nextInt();
14 | int q = sc.nextInt();
15 |
16 | // create list
17 | LinkedList list = new LinkedList<>();
18 | for (int i = 0; i < n; i++) {
19 | list.add(sc.nextInt());
20 | }
21 |
22 | // shift by k
23 | for (int i = 0; i < k; i++) {
24 | list.addFirst(list.pollLast());
25 | }
26 |
27 | // get queries
28 | int queries[] = new int[q];
29 | for (int i = 0; i < q; i++) {
30 | queries[i] = sc.nextInt();
31 | }
32 |
33 | // answer queries
34 | for (int i = 0; i < q; i++) {
35 | System.out.println(list.get(queries[i]));
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/CompareTheTriplets.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/compare-the-triplets
7 | */
8 | public class CompareTheTriplets {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int a0 = in.nextInt();
12 | int a1 = in.nextInt();
13 | int a2 = in.nextInt();
14 | int b0 = in.nextInt();
15 | int b1 = in.nextInt();
16 | int b2 = in.nextInt();
17 |
18 | int alice = 0;
19 | int bob = 0;
20 |
21 | // Test 1
22 | if (a0 > b0) {
23 | alice++;
24 | } else if (b0 > a0) {
25 | bob++;
26 | }
27 |
28 | // Test 2
29 | if (a1 > b1) {
30 | alice++;
31 | } else if (b1 > a1) {
32 | bob++;
33 | }
34 |
35 | // Test 3
36 | if (a2 > b2) {
37 | alice++;
38 | } else if (b2 > a2) {
39 | bob++;
40 | }
41 |
42 | System.out.println(alice + " " + bob);
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/DiagonalDifference.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/diagonal-difference
7 | */
8 | public class DiagonalDifference {
9 |
10 | public static void main(String[] args) {
11 | Scanner sc = new Scanner(System.in);
12 | int n = sc.nextInt();
13 |
14 | int[][] m = new int[n][n];
15 | for (int i = 0; i < n; i++) {
16 | for (int j = 0; j < n; j++) {
17 | m[i][j] = sc.nextInt();
18 | }
19 | }
20 |
21 | // sum of primary diagonal
22 | int sum1 = 0;
23 | for (int i = 0, j = 0; i < n && j < n; i++, j++) {
24 | sum1 += m[i][j];
25 | }
26 |
27 | // sum of primary diagonal
28 | int sum2 = 0;
29 | for (int i = 0, j = n - 1; i < n && j >= 0; i++, j--) {
30 | sum2 += m[i][j];
31 | }
32 |
33 | System.out.println(Math.abs(sum1 - sum2));
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/PlusMinus.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.math.BigDecimal;
4 | import java.util.Scanner;
5 |
6 | import static java.math.BigDecimal.ROUND_HALF_UP;
7 |
8 | /**
9 | * https://www.hackerrank.com/challenges/plus-minus
10 | */
11 | public class PlusMinus {
12 |
13 | public static void main(String[] args) {
14 | Scanner sc = new Scanner(System.in);
15 | int n = sc.nextInt();
16 |
17 | int positive = 0, negative = 0, zeroes = 0;
18 | for (int i = 0; i < n; i++) {
19 | int num = sc.nextInt();
20 | if (num == 0) {
21 | zeroes++;
22 | } else if (num > 0) {
23 | positive++;
24 | } else {
25 | negative++;
26 | }
27 | }
28 |
29 | final BigDecimal count = new BigDecimal(n);
30 | BigDecimal pf = new BigDecimal(positive).divide(count, 6, ROUND_HALF_UP);
31 | BigDecimal nf = new BigDecimal(negative).divide(count, 6, ROUND_HALF_UP);
32 | BigDecimal zf = new BigDecimal(zeroes).divide(count, 6, ROUND_HALF_UP);
33 | System.out.println(pf);
34 | System.out.println(nf);
35 | System.out.println(zf);
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/SimpleArraySum.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/simple-array-sum
7 | */
8 | public class SimpleArraySum {
9 | public static void main(String[] args) {
10 | Scanner sc = new Scanner(System.in);
11 | int n = sc.nextInt();
12 | long sum = 0;
13 | for (int i = 0; i < n; i++) {
14 | sum += sc.nextInt();
15 | }
16 | System.out.println(sum);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/Staircase.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://www.hackerrank.com/challenges/staircase
7 | */
8 | public class Staircase {
9 |
10 | public static void main(String[] args) {
11 | Scanner sc = new Scanner(System.in);
12 | int n = sc.nextInt();
13 |
14 | for (int i = 1; i <= n; i++) {
15 | for (int j = 1; j <= n - i; j++) {
16 | System.out.print(" ");
17 | }
18 | for (int j = 1; j <= i; j++) {
19 | System.out.print("#");
20 | }
21 | System.out.println();
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/hackerrank/algorithms/warmup/TimeConversion.java:
--------------------------------------------------------------------------------
1 | package hackerrank.algorithms.warmup;
2 |
3 | import java.text.ParseException;
4 | import java.text.SimpleDateFormat;
5 | import java.util.Date;
6 | import java.util.Scanner;
7 |
8 | /**
9 | * https://www.hackerrank.com/challenges/time-conversion
10 | */
11 | public class TimeConversion {
12 |
13 | public static void main(String[] args) throws ParseException {
14 | Scanner sc = new Scanner(System.in);
15 | String dateStr = sc.next();
16 |
17 | SimpleDateFormat twelve = new SimpleDateFormat("hh:mm:ssa");
18 | SimpleDateFormat twentyFour = new SimpleDateFormat("HH:mm:ss");
19 |
20 | final Date dateTime = twelve.parse(dateStr);
21 | System.out.println(twentyFour.format(dateTime));
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/AddStringNumbers.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 |
4 | /**
5 | * https://leetcode.com/problems/add-strings/
6 | */
7 | public class AddStringNumbers {
8 | public static void main(String[] args) {
9 | System.out.println(addStrings("345", "92346"));
10 | }
11 |
12 | public static String addStrings(String num1, String num2) {
13 |
14 | String result = "";
15 |
16 | int carry = 0;
17 | for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) {
18 | int digit1 = getDigit(num1, i);
19 | int digit2 = getDigit(num2, j);
20 | int addition = digit1 + digit2 + carry;
21 | result = addition % 10 + result;
22 | carry = addition / 10;
23 | }
24 | if (carry > 0) {
25 | result = carry + result;
26 | }
27 | return result;
28 | }
29 |
30 | private static int getDigit(String string, int i) {
31 | return i < string.length() && i >= 0 ? Integer.parseInt(string.substring(i, i + 1)) : 0;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/AlienLanguageSorted.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 |
4 | /**
5 | * https://leetcode.com/problems/verifying-an-alien-dictionary
6 | */
7 | public class AlienLanguageSorted {
8 |
9 | public boolean isAlienSorted(String[] words, String order) {
10 |
11 | int[] idxOrder = convertToIdxArray(order);
12 | for (int i = 0; i < words.length - 1; i++) {
13 | if (!isLexicographicallyValid(words[i], words[i + 1], idxOrder)) {
14 | return false;
15 | }
16 | }
17 | return true;
18 | }
19 |
20 | public boolean isLexicographicallyValid(String leftWord, String rightWord, int[] idxOrder) {
21 |
22 | int i = 0, j = 0;
23 | for (; i < leftWord.length() && j < rightWord.length(); i++, j++) {
24 | char leftChar = leftWord.charAt(i);
25 | char rightChar = rightWord.charAt(j);
26 |
27 | if (idxOrder[leftChar - 'a'] > idxOrder[rightChar - 'a']) {
28 | return false;
29 | } else if (idxOrder[leftChar - 'a'] < idxOrder[rightChar - 'a']) {
30 | return true;
31 | }
32 | }
33 |
34 | if (i < leftWord.length()) {
35 | return false;
36 | }
37 | return true;
38 | }
39 |
40 | public int[] convertToIdxArray(String order) {
41 | int[] idxOrder = new int[26];
42 | for (int i = 0; i < 26; i++) {
43 | idxOrder[order.charAt(i) - 'a'] = i;
44 | }
45 | return idxOrder;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/ArithmeticSlices.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/arithmetic-slices/
7 | */
8 | public class ArithmeticSlices {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n = in.nextInt();
12 |
13 | int[] A = new int[n];
14 | for (int i = 0; i < n; i++) {
15 | A[i] = in.nextInt();
16 | }
17 | System.out.println(numberOfArithmeticSlices(A));
18 | }
19 |
20 | public static int numberOfArithmeticSlices(int[] A) {
21 | int count = 0;
22 | for (int i = 0; i + 2 < A.length; i++) {
23 | int diff = A[i + 1] - A[i];
24 | int j = i + 2;
25 | while (j < A.length && A[j] - A[j - 1] == diff) {
26 | count++;
27 | j++;
28 | }
29 | }
30 | return count;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/Battleships.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/battleships-in-a-board/
7 | */
8 | public class Battleships {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int rows = in.nextInt();
13 | int cols = in.nextInt();
14 |
15 | char[][] board = new char[rows][cols];
16 | for (int i = 0; i < rows; i++) {
17 | String string = in.next();
18 | for (int j = 0; j < string.length(); j++) {
19 | board[i][j] = string.charAt(j);
20 | }
21 | }
22 |
23 | System.out.println(countBattleships(board));
24 | }
25 |
26 | public static int countBattleships(char[][] board) {
27 | int count = 0;
28 | for (int i = 0; i < board.length; i++) {
29 | for (int j = 0; j < board[0].length; j++) {
30 | if (isX(board, i, j) && !isPreviousX(board, i, j)) {
31 | count++;
32 | }
33 | }
34 | }
35 | return count;
36 | }
37 |
38 | private static boolean isPreviousX(char[][] board, int i, int j) {
39 | return ((i - 1 >= 0 && isX(board, i - 1, j)) || (j - 1) >= 0 && isX(board, i, j - 1));
40 | }
41 |
42 | private static boolean isX(char[][] board, int i, int j) {
43 | return board[i][j] == 'X';
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/Candy.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 |
4 | import java.util.Arrays;
5 |
6 | /**
7 | * https://leetcode.com/problems/candy/
8 | */
9 | public class Candy {
10 | public static void main(String[] args) {
11 | // System.out.println(candy(new int[]{1, 5, 2, 10, 10, 3, 8, 9, 1, 1, 2}));
12 | // System.out.println(candy(new int[]{5, 3, 1}));
13 | // System.out.println(candy(new int[]{1, 2, 2}));
14 | System.out.println(candy(new int[]{1, 2, 4, 4, 3}));
15 | }
16 |
17 | public static int candy(int[] ratings) {
18 |
19 | if (ratings == null || ratings.length == 0) {
20 | return 0;
21 | }
22 |
23 | int n = ratings.length;
24 | int[] candies = new int[n];
25 | Arrays.fill(candies, 1);
26 |
27 | for (int i = 1; i < n; i++) {
28 | if (ratings[i] > ratings[i - 1]) {
29 | candies[i] = candies[i - 1] + 1;
30 | }
31 | }
32 |
33 | for (int i = n - 2; i >= 0; i--) {
34 | if (ratings[i] > ratings[i + 1]) {
35 | candies[i] = Math.max(candies[i], candies[i + 1] + 1);
36 | }
37 | }
38 |
39 | return Arrays.stream(candies).sum();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/DecodeString.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.regex.Pattern;
4 | import java.util.stream.IntStream;
5 |
6 | /**
7 | * https://leetcode.com/problems/decode-string/
8 | */
9 | public class DecodeString {
10 | public static void main(String[] args) {
11 | // System.out.println(decodeString("3[a]2[bc]"));
12 | // System.out.println(decodeString("3[a2[c]]"));
13 | // System.out.println(decodeString("2[abc]3[cd]ef"));
14 | System.out.println(decodeString("10[leetcode]"));
15 | }
16 |
17 | public static String decodeString(String str) {
18 | while (str.contains("]")) {
19 | int end = str.indexOf(']');
20 | int start = getStart(str, end);
21 | Integer count = getDigit(str, start);
22 | String pattern = str.substring(start + 1, end);
23 | String original = count.toString() + "[" + pattern + "]";
24 | String result = repeat(pattern, count);
25 | str = str.replaceAll(Pattern.quote(original), result);
26 | }
27 | return str;
28 | }
29 |
30 | private static int getDigit(String str, int end) {
31 | int start = end;
32 | while (start > 0 && Character.isDigit(str.charAt(start - 1))) {
33 | start--;
34 | }
35 | return Integer.parseInt(str.substring(start, end));
36 | }
37 |
38 | private static String repeat(String string, int count) {
39 | StringBuilder result = new StringBuilder();
40 | IntStream.rangeClosed(1, count).forEach(k -> result.append(string));
41 | return result.toString();
42 | }
43 |
44 | private static int getStart(String str, int end) {
45 | while (end > 0 && str.charAt(end) != '[') end--;
46 | return end;
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/DecodeWays.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class DecodeWays {
4 | public static void main(String[] args) {
5 | System.out.println(new DecodeWays().numDecodings("12"));
6 | }
7 |
8 | public int numDecodings(String input) {
9 | return decodeWays(input, 0);
10 | }
11 |
12 | private int decodeWays(String input, int index) {
13 |
14 | if (index == input.length() - 1) {
15 | return 1;
16 | }
17 |
18 | if (doubleDigitsPossible(input, index)) {
19 | return 1 + decodeWays(input, index + 1);
20 | } else {
21 | return decodeWays(input, index + 1);
22 | }
23 | }
24 |
25 | private boolean doubleDigitsPossible(String input, int index) {
26 | return input.charAt(index) == '1' || (index < input.length() && input.charAt(index) == '2' && input.charAt(index + 1) <= '6');
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/DegreeOfAnArray.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class DegreeOfAnArray {
4 |
5 | public static void main(String[] args) {
6 | int[] nums = new int[]{1, 2, 2, 3, 1, 4, 2};
7 | System.out.println(findShortestSubArray(nums));
8 | }
9 |
10 | public static int findShortestSubArray(int[] nums) {
11 |
12 | CustomChar[] chars = new CustomChar[50000];
13 |
14 | int maxCount = 0;
15 | for (int i = 0; i < nums.length; i++) {
16 | int num = nums[i];
17 | if (chars[num] == null) {
18 | chars[num] = new CustomChar();
19 | chars[num].start = i;
20 | }
21 | chars[num].count++;
22 | chars[num].end = i;
23 | maxCount = Math.max(maxCount, chars[num].count);
24 | }
25 |
26 | int shortestDist = Integer.MAX_VALUE;
27 | for (int i = 0; i < 50000; i++) {
28 | CustomChar num = chars[i];
29 | if (num != null && num.count == maxCount) {
30 | shortestDist = Math.min(shortestDist, num.end - num.start + 1);
31 | }
32 | }
33 | return shortestDist;
34 | }
35 |
36 | private static class CustomChar {
37 | int count = 0;
38 | int start;
39 | int end;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/DigitToHex.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/convert-a-number-to-hexadecimal/ -- without 2's complement
7 | */
8 | public class DigitToHex {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n = in.nextInt();
12 | System.out.println(convertToHex(n));
13 | }
14 |
15 | private static String convertToHex(int n) {
16 |
17 | String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
18 | if (n < 0) {
19 | return "";
20 | }
21 |
22 | String output = "";
23 | while (n > 0) {
24 | output = hex[n % 16] + output;
25 | n = n / 16;
26 | }
27 | return output;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/FindDifference.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/find-the-difference/
5 | */
6 | public class FindDifference {
7 | public static void main(String[] args) {
8 | System.out.println(findTheDifference("abcd", "abcde"));
9 | System.out.println(findTheDifference("abcdefd", "ladbcdef"));
10 | }
11 |
12 | public static char findTheDifference(String s, String t) {
13 | int[] counts = new int[26]; //alphabet counts
14 | for (int i = 0; i < t.length(); i++) {
15 | counts[t.charAt(i) - 'a']++;
16 | }
17 | for (int i = 0; i < s.length(); i++) {
18 | counts[s.charAt(i) - 'a']--;
19 | }
20 | for (int i = 0; i < 26; i++) {
21 | if (counts[i] > 0) {
22 | return (char) (i + 'a');
23 | }
24 | }
25 | return ' ';
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/FindDisappearedNumbers.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Scanner;
6 |
7 | /**
8 | * https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/
9 | */
10 | public class FindDisappearedNumbers {
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 | int n = in.nextInt();
14 | int[] arr = new int[n];
15 | for (int i = 0; i < n; i++) {
16 | arr[i] = in.nextInt();
17 | }
18 | System.out.println(findDisappearedNumbers(arr));
19 | }
20 |
21 | public static List findDisappearedNumbers(int[] nums) {
22 |
23 | for (int i = 0; i < nums.length; i++) {
24 | nums[i]--;
25 | }
26 |
27 | for (int i = 0; i < nums.length; i++) {
28 | int val = Math.abs(nums[i]);
29 | if (nums[val] > 0) {
30 | nums[val] = -nums[val];
31 | }
32 | }
33 |
34 | List list = new ArrayList<>();
35 | for (int i = 0; i < nums.length; i++) {
36 | if (nums[i] > 0) {
37 | list.add(i + 1);
38 | }
39 | }
40 |
41 | return list;
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/FindLeavesOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.stream.Collectors;
7 |
8 | /**
9 | * https://leetcode.com/problems/find-leaves-of-binary-tree
10 | */
11 | public class FindLeavesOfBinaryTree {
12 |
13 | public List> findLeaves(TreeNode root) {
14 | HashMap> leavesPerDepth = new HashMap<>();
15 | dfs(root, leavesPerDepth);
16 | return leavesPerDepth.values().stream().collect(Collectors.toList());
17 | }
18 |
19 | private int dfs(TreeNode node, HashMap> leavesMap) {
20 | if (node == null) return 0;
21 | int height = Math.max(dfs(node.left, leavesMap), dfs(node.right, leavesMap));
22 | leavesMap.computeIfAbsent(height, k -> new ArrayList<>()).add(node.data);
23 | return height + 1;
24 | }
25 |
26 | private class TreeNode {
27 | int data;
28 | TreeNode left, right;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/FirstUniqueChar.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.LinkedHashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * https://leetcode.com/problems/first-unique-character-in-a-string/
8 | */
9 | public class FirstUniqueChar {
10 | public static void main(String[] args) {
11 | System.out.println(firstUniqChar("leetcode"));
12 | System.out.println(firstUniqChar("loveleetcode"));
13 | }
14 |
15 | public static int firstUniqChar(String s) {
16 | int[] counts = new int[26]; // char counts
17 | LinkedHashMap firstIndex = new LinkedHashMap<>(26); // first indexes
18 |
19 | for (int i = 0; i < s.length(); i++) {
20 | if (counts[s.charAt(i) - 'a']++ == 0) {
21 | firstIndex.put(s.charAt(i), i);
22 | }
23 | }
24 |
25 | for (Map.Entry entry : firstIndex.entrySet()) {
26 | int i = entry.getKey() - 'a';
27 | if (counts[i] == 1) {
28 | return entry.getValue();
29 | }
30 | }
31 | return -1;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/GuessNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/guess-number-higher-or-lower/
5 | */
6 | public class GuessNumber {
7 |
8 | private int number;
9 |
10 | public GuessNumber(int num) {
11 | this.number = num;
12 | }
13 |
14 | public static void main(String[] args) {
15 | GuessNumber game = new GuessNumber(2);
16 | System.out.println(game.guessNumber(2));
17 | }
18 |
19 | public int guessNumber(int n) {
20 | int low = 1, high = n;
21 | while (low < high) {
22 | int mid = low + (high - low) / 2;
23 | int res = guess(mid);
24 | if (res == 0) {
25 | return mid;
26 | } else if (res == 1) {
27 | low = mid + 1;
28 | } else if (res == -1) {
29 | high = mid;
30 | }
31 | }
32 | return low;
33 | }
34 |
35 | private int guess(int i) {
36 | if (i == number) {
37 | return 0;
38 | } else if (i > number) {
39 | return -1;
40 | } else {
41 | return 1;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/IntegerBreak.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * https://leetcode.com/problems/integer-break/
7 | */
8 | public class IntegerBreak {
9 | public static void main(String[] args) {
10 | System.out.println(integerBreak(2));
11 | System.out.println(integerBreak(3));
12 | System.out.println(integerBreak(4));
13 | System.out.println(integerBreak(10));
14 | }
15 |
16 | public static int integerBreak(int n) {
17 | HashMap products = new HashMap<>();
18 | products.put(1, 1);
19 | products.put(2, 1);
20 | products.put(3, 2);
21 | if (n == 3 || n == 2) {
22 | return products.get(n);
23 | }
24 | return memoizedIntegerProduct(n, products);
25 | }
26 |
27 |
28 | private static int memoizedIntegerProduct(int n, HashMap products) {
29 |
30 | if (products.containsKey(n)) {
31 | return Math.max(products.get(n), n);
32 | }
33 |
34 | int maxProduct = 0;
35 | for (int i = 2; i < n; i++) {
36 | int product = i * memoizedIntegerProduct(n - i, products);
37 | maxProduct = product > maxProduct ? product : maxProduct;
38 | }
39 | products.put(n, maxProduct);
40 | return maxProduct;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/IntegerReplacement.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/integer-replacement/
5 | *
6 | * Cheated - https://discuss.leetcode.com/topic/58334/a-couple-of-java-solutions-with-explanations
7 | */
8 | public class IntegerReplacement {
9 |
10 | public static void main(String[] args) {
11 | // System.out.println(integerReplacement(8));
12 | // System.out.println(integerReplacement(7));
13 | System.out.println(integerReplacement(24));
14 | }
15 |
16 | public static int integerReplacement(int n) {
17 | int count = 0;
18 | while (n > 1) {
19 | if (n % 2 == 0) {
20 | n = n / 2;
21 | } else if (n == 3) {
22 | n--;
23 | } else if (Integer.bitCount(n - 1) < Integer.bitCount(n + 1)) {
24 | n--;
25 | } else {
26 | n++;
27 | }
28 | count++;
29 | }
30 | return count;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/KPairsWithSmallestSums.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 | import java.util.PriorityQueue;
6 | import java.util.Queue;
7 | import java.util.stream.Collectors;
8 |
9 | /**
10 | * https://leetcode.com/problems/find-k-pairs-with-smallest-sums/
11 | */
12 | public class KPairsWithSmallestSums {
13 |
14 | public static void main(String[] args) {
15 | kSmallestPairs(new int[]{1, 1, 2}, new int[]{1, 2, 3}, 2).forEach(k -> System.out.println(Arrays.toString(k) + ", "));
16 | }
17 |
18 | public static List kSmallestPairs(int[] nums1, int[] nums2, int k) {
19 |
20 | Queue sums = new PriorityQueue<>((o1, o2) -> Integer.compare(o2[0] + o2[1], o1[0] + o1[1]));
21 | for (int i = 0; i < nums1.length; i++) {
22 | for (int j = 0; j < nums2.length; j++) {
23 | sums.add(new int[]{nums1[i], nums2[j]});
24 | if (sums.size() > k) {
25 | sums.remove();
26 | }
27 | }
28 | }
29 | return sums.stream().collect(Collectors.toList());
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/KthSmallestFromMatrix.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
5 | *
6 | * Wrong solution.
7 | *
8 | * Can be fixed by using priority queue and adding indexes of neighbors
9 | */
10 | public class KthSmallestFromMatrix {
11 | public static void main(String[] args) {
12 | // int[][] matrix = {{1, 5, 9}, {10, 11, 13}, {12, 13, 15}};
13 | int[][] matrix = {{1, 3, 5}, {6, 7, 12}, {11, 14, 14}};
14 | System.out.println(kthSmallest(matrix, 5));
15 | }
16 |
17 | public static int kthSmallest(int[][] matrix, int k) {
18 | int n = matrix.length;
19 | int val = 0;
20 | for (int i = 0; i < n; i++) {
21 |
22 | k--;
23 | if (k == 0) return matrix[i][i];
24 |
25 | int hi = i + 1;
26 | int vi = i + 1;
27 | while (hi < n || vi < n) {
28 |
29 | if (hi == n) {
30 | val = matrix[vi][i];
31 | vi++;
32 | } else if (vi == n) {
33 | val = matrix[i][hi];
34 | hi++;
35 | } else if (matrix[i][hi] < matrix[vi][i]) {
36 | val = matrix[i][hi];
37 | hi++;
38 | } else {
39 | val = matrix[vi][i];
40 | vi++;
41 | }
42 |
43 | k--;
44 | if (k == 0) {
45 | return val;
46 | }
47 | }
48 | }
49 | return -1;
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LCM_BT_236.py:
--------------------------------------------------------------------------------
1 | def lowestCommonAncestor(self, root, p, q):
2 | # If looking for me, return myself
3 | if root == p or root == q:
4 | return root
5 |
6 | left = right = None
7 | # else look in left and right child
8 | if root.left:
9 | left = self.lowestCommonAncestor(root.left, p, q)
10 | if root.right:
11 | right = self.lowestCommonAncestor(root.right, p, q)
12 |
13 | if left and right:
14 | return root
15 | else:
16 | return left or right
17 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LargestDivisibleSubset.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Arrays;
5 | import java.util.List;
6 |
7 | public class LargestDivisibleSubset {
8 | public static void main(String[] args) {
9 | System.out.println(largestDivisibleSubset(new int[]{3}));
10 | System.out.println(largestDivisibleSubset(new int[]{1, 2, 3}));
11 | System.out.println(largestDivisibleSubset(new int[]{1, 2, 4, 8}));
12 | }
13 |
14 | public static List largestDivisibleSubset(int[] nums) {
15 | if (nums == null || nums.length == 0) {
16 | return new ArrayList<>();
17 | }
18 | Arrays.sort(nums);
19 | int max = 0;
20 | int maxInd = -1;
21 | int[] count = new int[nums.length];
22 | Arrays.fill(count, 1);
23 | int[] parent = new int[nums.length];
24 |
25 | for (int i = nums.length - 1; i >= 0; i--) {
26 | for (int j = i + 1; j < nums.length; j++) {
27 | if (nums[j] % nums[i] == 0
28 | && count[j] + 1 > count[i]) {
29 | count[i] = count[j] + 1;
30 | parent[i] = j;
31 | }
32 | }
33 | if (count[i] > max) {
34 | max = count[i];
35 | maxInd = i;
36 | }
37 | }
38 |
39 | List subset = new ArrayList<>();
40 | for (int i = 0; i < max; i++) {
41 | subset.add(nums[maxInd]);
42 | maxInd = parent[maxInd];
43 | }
44 |
45 | return subset;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LexographicalNumbers.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | /**
7 | * https://leetcode.com/problems/lexicographical-numbers/
8 | *
9 | * Cheated: https://discuss.leetcode.com/topic/55184/java-o-n-time-o-1-space-iterative-solution-130ms
10 | */
11 | public class LexographicalNumbers {
12 |
13 | public static void main(String[] args) {
14 | System.out.println(lexicalOrder(100));
15 | }
16 |
17 | public static List lexicalOrder(int n) {
18 |
19 | List result = new ArrayList<>(n);
20 | int val = 1;
21 | for (int i = 1; i <= n; i++) {
22 | result.add(val);
23 | if (val * 10 <= n) {
24 | val *= 10;
25 | } else if (val % 10 != 9 && val + 1 <= n) {
26 | val++;
27 | } else {
28 | while ((val / 10) % 10 == 9) {
29 | val /= 10;
30 | }
31 | val = val / 10 + 1;
32 | }
33 | }
34 | return result;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LinkedListRandomNote.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Random;
4 |
5 | /**
6 | * https://leetcode.com/problems/linked-list-random-node/
7 | */
8 | public class LinkedListRandomNote {
9 |
10 | private final ListNode head;
11 | private Random random = new Random();
12 |
13 | public LinkedListRandomNote(ListNode head) {
14 | this.head = head;
15 | }
16 |
17 | public int getRandom() {
18 | int count = 0;
19 | ListNode curr = head;
20 | ListNode random = head;
21 | while (curr.next != null) {
22 | curr = curr.next;
23 | count++;
24 | if (getRandom(count) == count) {
25 | random = curr;
26 | }
27 | }
28 | return random.val;
29 | }
30 |
31 | private int getRandom(int count) {
32 | return random.nextInt(count + 1);
33 | }
34 |
35 | public class ListNode {
36 | int val;
37 | ListNode next;
38 |
39 | ListNode(int x) {
40 | val = x;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LongestPalindrome.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/longest-palindrome/
7 | */
8 | public class LongestPalindrome {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | String str = in.next();
12 | System.out.println(longestPalindrome(str));
13 | }
14 |
15 | public static int longestPalindrome(String s) {
16 | int[] upper = new int[26];
17 | int[] lower = new int[26];
18 | for (int i = 0; i < s.length(); i++) {
19 | char ch = s.charAt(i);
20 | if (Character.isLowerCase(ch)) {
21 | lower[ch - 'a']++;
22 | } else {
23 | upper[ch - 'A']++;
24 | }
25 | }
26 |
27 | int count = 0;
28 | boolean extraChar = false;
29 | for (int i = 0; i < 26; i++) {
30 | count += upper[i];
31 | if (upper[i] % 2 != 0) {
32 | count--;
33 | extraChar = true;
34 | }
35 |
36 | count += lower[i];
37 | if (lower[i] % 2 != 0) {
38 | count--;
39 | extraChar = true;
40 | }
41 | }
42 | if (extraChar) count++;
43 | return count;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LongestRepeatingCharReplacement2.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://leetcode.com/problems/longest-repeating-character-replacement/
8 | *
9 | * Eg: ZDDDDKKPMPKKKPAXKKKKK
10 | *
11 | * k = 3
12 | *
13 | * Answer: 11
14 | *
15 | * Using Sliding Window.
16 | */
17 | public class LongestRepeatingCharReplacement2 {
18 |
19 | public static void main(String[] args) {
20 | Scanner in = new Scanner(System.in);
21 | String str = in.next();
22 | int k = in.nextInt();
23 | System.out.println(characterReplacement(str, k));
24 | }
25 |
26 | public static int characterReplacement(String str, int k) {
27 |
28 | if (str == null || str.length() == 0) {
29 | return 0;
30 | }
31 |
32 | int start = 0;
33 | int end = 0;
34 | int[] charCounts = new int[26];
35 | Arrays.fill(charCounts, 0);
36 | int maxRepChars = 0;
37 | int maxLength = 0;
38 |
39 | for (; end < str.length(); end++) {
40 | int ch = str.charAt(end) - 'A';
41 | charCounts[ch]++;
42 | maxRepChars = Math.max(maxRepChars, charCounts[ch]);
43 | if (end - start + 1 - maxRepChars > k) {
44 | charCounts[str.charAt(start) - 'A']--;
45 | start++;
46 | }
47 | maxLength = Math.max(maxLength, end - start + 1);
48 | }
49 |
50 | return maxLength;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LongestStringWithKRepeating.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/
5 | */
6 | public class LongestStringWithKRepeating {
7 | public static void main(String[] args) {
8 | System.out.println(longestSubstring("aaabb", 3));
9 | System.out.println(longestSubstring("ababbc", 2));
10 | }
11 |
12 | public static int longestSubstring(String s, int k) {
13 | return getMax(s, 0, s.length() - 1, k);
14 | }
15 |
16 | public static int getMax(String s, int start, int end, int k) {
17 |
18 | if (start > end || (end - start + 1) < k) {
19 | return 0;
20 | }
21 |
22 | int charCount[] = charCount(s, start, end);
23 | for (int i = start; i <= end; i++) {
24 | int cc = charCount[s.charAt(i) - 'a'];
25 | if (cc > 0 && cc < k) {
26 | return Math.max(getMax(s, start, i - 1, k), getMax(s, i + 1, end, k));
27 | }
28 | }
29 | return end - start + 1;
30 | }
31 |
32 | private static int[] charCount(String s, int start, int end) {
33 | int[] charCount = new int[26];
34 | for (int i = start; i <= end; i++) {
35 | charCount[s.charAt(i) - 'a']++;
36 | }
37 | return charCount;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/LongestSubstringNonRepeated.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * https://leetcode.com/problems/longest-substring-without-repeating-characters
8 | *
9 | * https://leetcode.com/problems/longest-repeating-character-replacement/discuss/91271/Java-12-lines-O(n)-sliding-window-solution-with-explanation
10 | *
11 | */
12 | public class LongestSubstringNonRepeated {
13 |
14 | public static void main(String[] args) {
15 | System.out.println(new LongestSubstringNonRepeated().lengthOfLongestSubstring("bbbbb"));
16 | System.out.println(new LongestSubstringNonRepeated().lengthOfLongestSubstring("abcdbefc"));
17 | System.out.println(new LongestSubstringNonRepeated().lengthOfLongestSubstring("abcde"));
18 | }
19 |
20 | public int lengthOfLongestSubstring(String input) {
21 |
22 | Set window = new HashSet<>();
23 | int start = 0;
24 | int end = 0;
25 | int maxCount = 0;
26 |
27 | while (end < input.length()) {
28 |
29 | Character currentChar = input.charAt(end++);
30 | if (window.contains(currentChar)) {
31 | while (input.charAt(start) != currentChar) {
32 | window.remove(input.charAt(start));
33 | start++;
34 | }
35 | start++;
36 | }
37 | window.add(currentChar);
38 | if (window.size() > maxCount) {
39 | maxCount = window.size();
40 | }
41 | }
42 | return maxCount;
43 |
44 | }
45 | }
46 |
47 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/MatrixPathTo9.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class MatrixPathTo9 {
4 |
5 | public static void main(String[] args) {
6 | MatrixPathTo9 obj = new MatrixPathTo9();
7 | boolean ans = obj.pathToNine(
8 | new int[][]{{1, 1, 0, 1, 0},
9 | {1, 0, 0, 1, 1},
10 | {1, 0, 1, 9, 1},
11 | {1, 1, 1, 0, 0},
12 | {1, 0, 1, 1, 1}});
13 | System.out.println(ans);
14 | }
15 |
16 | public boolean pathToNine(int[][] A) {
17 |
18 | if (A == null || A.length == 0 || A[0].length == 0) {
19 | return false;
20 | }
21 |
22 | boolean[][] visited = new boolean[A.length][A[0].length];
23 | return pathToNine(A, 0, 0, visited);
24 | }
25 |
26 | public boolean pathToNine(int[][] A, int row, int col, boolean[][] visited) {
27 |
28 | if (!isValidBound(A, row, col) || visited[row][col] == true || A[row][col] == 0) {
29 | return false;
30 | }
31 |
32 | visited[row][col] = true;
33 | if (A[row][col] == 9) {
34 | return true;
35 | }
36 |
37 | return pathToNine(A, row + 1, col, visited)
38 | || pathToNine(A, row, col + 1, visited)
39 | || pathToNine(A, row - 1, col, visited)
40 | || pathToNine(A, row, col - 1, visited);
41 | }
42 |
43 | public boolean isValidBound(int[][] A, int row, int col) {
44 | return !(row < 0 || row >= A.length || col < 0 || col >= A[0].length);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/MergeIntervals.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 |
4 | import java.util.Comparator;
5 | import java.util.LinkedList;
6 | import java.util.List;
7 |
8 | public class MergeIntervals {
9 |
10 | public static void main(String[] args) {
11 |
12 |
13 | }
14 |
15 | public List merge(List intervals) {
16 |
17 | intervals.sort(Comparator.comparingInt(i -> i.start));
18 | LinkedList merged = new LinkedList<>();
19 | for (Interval current : intervals) {
20 |
21 | if (merged.isEmpty() || current.start > merged.getLast().end) {
22 | merged.add(current);
23 | } else {
24 | merged.getLast().end = Math.max(merged.getLast().end, current.end);
25 | }
26 | }
27 | return merged;
28 | }
29 |
30 | private class Interval {
31 | int start;
32 | int end;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/MinKElementsInBST.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Deque;
4 | import java.util.LinkedList;
5 |
6 | public class MinKElementsInBST {
7 |
8 | public static void main(String[] args) {
9 |
10 | }
11 |
12 | public int KthSmallest(TreeNode root, int k) {
13 |
14 | TreeNode node = root;
15 | Deque stack = new LinkedList<>();
16 |
17 | while (node != null || !stack.isEmpty()) {
18 |
19 | while (node != null) {
20 | stack.offerFirst(node);
21 | node = node.left;
22 | }
23 |
24 | node = stack.pollFirst();
25 | if (--k == 0) {
26 | return node.val;
27 | }
28 | node = node.right;
29 | }
30 | return -1;
31 | }
32 |
33 | public class TreeNode {
34 | int val;
35 | TreeNode left;
36 | TreeNode right;
37 |
38 | TreeNode(int x) {
39 | val = x;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/NestedListWeightSum.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.List;
4 |
5 | /**
6 | * https://leetcode.com/problems/nested-list-weight-sum
7 | */
8 | public class NestedListWeightSum {
9 |
10 | public int depthSumInverse(List nestedList) {
11 | return weightedSum(nestedList, 1);
12 | }
13 |
14 | private int weightedSum(List nestedList, int level) {
15 | int weightedSum = 0;
16 | for (NestedInteger ni : nestedList) {
17 | if (ni.isInteger()) {
18 | weightedSum += ni.getData() * level;
19 | } else {
20 | weightedSum += weightedSum(ni.getList(), level + 1);
21 | }
22 | }
23 | return weightedSum;
24 | }
25 |
26 | private class NestedInteger {
27 |
28 | int data;
29 | List list;
30 | boolean isInteger;
31 |
32 | public boolean isInteger() {
33 | return isInteger;
34 | }
35 |
36 | public int getData() {
37 | return data;
38 | }
39 |
40 | public List getList() {
41 | return list;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/NthDigit.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/nth-digit/
7 | */
8 | public class NthDigit {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | System.out.println(findNthDigit(n));
14 | }
15 |
16 | public static int findNthDigit(int m) {
17 |
18 | if (m < 10) {
19 | return m;
20 | }
21 |
22 | long n = m;
23 | long i = 1;
24 | long mul = 9;
25 | long start = 1;
26 | while (n > i * mul) {
27 | n = n - i * mul;
28 | mul = mul * 10;
29 | start = start * 10;
30 | i++;
31 | }
32 |
33 | start = start + (n - 1) / i;
34 | return Long.toString(start).charAt((int) ((n - 1) % i)) - '0';
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/NumberOfMeetingRooms.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Comparator;
4 | import java.util.List;
5 | import java.util.PriorityQueue;
6 |
7 | public class NumberOfMeetingRooms {
8 |
9 | public static void main(String[] args) {
10 |
11 | }
12 |
13 | public int minMeetingRooms(List intervals) {
14 | intervals.sort(Comparator.comparingInt(i -> i.start));
15 |
16 | PriorityQueue minEndTimes = new PriorityQueue<>();
17 | minEndTimes.offer(intervals.get(0).end);
18 | for (Interval interval : intervals) {
19 |
20 | if (interval.start >= minEndTimes.peek()) {
21 | minEndTimes.poll();
22 | minEndTimes.offer(interval.end);
23 | } else {
24 | minEndTimes.offer(interval.end);
25 | }
26 | }
27 |
28 | return minEndTimes.size();
29 | }
30 |
31 | private class Interval {
32 | int start;
33 | int end;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/Palindrome.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class Palindrome {
4 |
5 | public static void main(String[] args) {
6 | Palindrome obj = new Palindrome();
7 | // obj.isPalindrome("A man, a plan, a canal: Panama");
8 | obj.isPalindrome("1b1");
9 | }
10 |
11 | public boolean isPalindrome(String s) {
12 |
13 | if (s == null || s.length() == 0) {
14 | return false;
15 | }
16 |
17 | if (s.length() == 1) {
18 | return true;
19 | }
20 |
21 | s = s.toLowerCase();
22 |
23 | int start = incrementToValidChar(s, 0);
24 | int end = decrementToValidChar(s, s.length() - 1);
25 |
26 | while (start < end) {
27 |
28 | if (s.charAt(start) != s.charAt(end)) {
29 | return false;
30 | }
31 |
32 |
33 | start = incrementToValidChar(s, start + 1);
34 | end = decrementToValidChar(s, end - 1);
35 | }
36 |
37 | return true;
38 | }
39 |
40 | public int incrementToValidChar(String s, int index) {
41 | while (index < s.length() && !isValidLetter(s.charAt(index))) {
42 | index++;
43 | }
44 | return index;
45 | }
46 |
47 | public int decrementToValidChar(String s, int index) {
48 | while (index >= 0 && !isValidLetter(s.charAt(index))) {
49 | index--;
50 | }
51 | return index;
52 | }
53 |
54 | public boolean isValidLetter(Character c) {
55 | return Character.isDigit(c) || Character.isLetter(c);
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/PartitionEqualSum.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.Scanner;
5 |
6 | /**
7 | * https://leetcode.com/problems/partition-equal-subset-sum/
8 | *
9 | * Works but time exceeds in LeetCode env.
10 | */
11 | public class PartitionEqualSum {
12 |
13 | public static void main(String[] args) {
14 | Scanner in = new Scanner(System.in);
15 | int n = in.nextInt();
16 | int nums[] = new int[n];
17 |
18 | for (int i = 0; i < n; i++) {
19 | nums[i] = in.nextInt();
20 | }
21 |
22 | System.out.println(canPartition(nums));
23 | }
24 |
25 | public static boolean canPartition(int[] nums) {
26 | int sum = sumOf(nums);
27 | if (sum % 2 != 0) {
28 | return false;
29 | }
30 |
31 | int[] used = new int[nums.length];
32 | return findset(nums, 0, used, 0, sum / 2);
33 | }
34 |
35 |
36 | private static boolean findset(int[] nums, int index, int[] used, int currSum, int sum) {
37 |
38 | if (currSum == sum) {
39 | return true;
40 | }
41 |
42 | if (currSum > sum) {
43 | return false;
44 | }
45 |
46 | if (index == nums.length) {
47 | return false;
48 | }
49 |
50 | used[index] = 1;
51 | currSum = currSum + nums[index];
52 | boolean with = findset(nums, index + 1, used, currSum, sum);
53 |
54 | used[index] = 0;
55 | currSum = currSum - nums[index];
56 | boolean without = findset(nums, index + 1, used, currSum, sum);
57 |
58 | return with || without;
59 | }
60 |
61 | private static int sumOf(int[] nums) {
62 | return Arrays.stream(nums).sum();
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/PathSum_118.java:
--------------------------------------------------------------------------------
1 | class PathSum_118 {
2 |
3 | public List> pathSum(TreeNode root, int sum){
4 |
5 | List> result = new ArrayList<>();
6 | List currentPath = new ArrayList<>();
7 |
8 | pathToSumRecurse(root, sum, 0, currentPath, result);
9 |
10 | return result;
11 | }
12 |
13 | private void pathToSumRecurse(TreeNode node,
14 | int sum,
15 | int currentSum,
16 | List currentPath,
17 | List> result){
18 |
19 | if(node == null){
20 | return;
21 | }
22 |
23 | currentPath.add(node.val);
24 | currentSum += node.val;
25 |
26 | if(currentSum == sum && isLeaf(node)){
27 | result.add(List.copyOf(currentPath));
28 | }
29 |
30 | pathToSumRecurse(node.left, sum, currentSum, currentPath, result);
31 | pathToSumRecurse(node.right, sum, currentSum, currentPath, result);
32 |
33 | currentSum -= node.val;
34 | currentPath.remove(currentPath.size()-1);
35 | }
36 |
37 | private boolean isLeaf(TreeNode node) {
38 | return node != null && node.left == null && node.right == null;
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/PathSum_124:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private int maxSum = Integer.MIN_VALUE;
3 |
4 | public int maxPathSum(TreeNode root){
5 | maxPathSumDown(root);
6 | return maxSum;
7 | }
8 |
9 | private int maxPathSumDown(TreeNode node){
10 | if(node == null){
11 | return 0;
12 | }
13 | int leftVal = Math.max(0, maxPathSumDown(node.left));
14 | int rightVal = Math.max(0, maxPathSumDown(node.right));
15 | maxSum = Math.max(maxSum, rightVal + leftVal + node.val);
16 | return Math.max(leftVal, rightVal) + node.val;
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RangeAddition.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * https://leetcode.com/problems/range-addition
7 | */
8 | public class RangeAddition {
9 |
10 | public static void main(String[] args) {
11 | System.out.println(Arrays.toString(getModifiedArray(5, new int[][]{
12 | {1, 3, 2},
13 | {2, 4, 3},
14 | {0, 2, -2},
15 | })));
16 | }
17 |
18 | public static int[] getModifiedArray(int length, int[][] updates) {
19 |
20 | if (length <= 0) {
21 | return null;
22 | }
23 |
24 | int res[] = new int[length];
25 | for (int i = 0; i < updates.length; i++) {
26 | res[updates[i][0]] += updates[i][2];
27 | if (updates[i][1] + 1 < length) {
28 | res[updates[i][1] + 1] -= updates[i][2];
29 | }
30 | }
31 |
32 | for (int i = 1; i < length; i++) {
33 | res[i] += res[i - 1];
34 | }
35 |
36 | return res;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RangeQuerySum.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class RangeQuerySum {
4 |
5 | public static void main(String[] args) {
6 |
7 | RangeQuerySum obj = new RangeQuerySum(new int[]{-2, 0, 3, -5, 2, -1});
8 | System.out.println(obj.sumRange(0, 2));
9 | System.out.println(obj.sumRange(2, 5));
10 | System.out.println(obj.sumRange(0, 5));
11 | }
12 |
13 | int[] sum = new int[0];
14 |
15 | public RangeQuerySum(int[] nums) {
16 | if (nums != null) {
17 | sum = createSumArray(nums);
18 | }
19 | }
20 |
21 | private int[] createSumArray(int[] nums) {
22 | int[] sum = new int[nums.length];
23 | int count = 0;
24 | for (int i = 0; i < nums.length; i++) {
25 | count += nums[i];
26 | sum[i] = count;
27 | }
28 | return sum;
29 | }
30 |
31 | public int sumRange(int i, int j) {
32 |
33 | if (i < 0) {
34 | i = 0;
35 | }
36 |
37 | if (j >= sum.length) {
38 | j = sum.length - 1;
39 | }
40 |
41 | return i == 0 ? sum[j] : sum[j] - sum[i - 1];
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RansomNote.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/ransom-note/
5 | */
6 | public class RansomNote {
7 | public static void main(String[] args) {
8 | System.out.println(canConstruct("aa", "aab"));
9 | }
10 |
11 | public static boolean canConstruct(String ransomNote, String magazine) {
12 | int[] counts = new int[26];
13 | for (int i = 0; i < magazine.length(); i++) {
14 | counts[magazine.charAt(i) - 'a']++;
15 | }
16 | for (int i = 0; i < ransomNote.length(); i++) {
17 | counts[ransomNote.charAt(i) - 'a']--;
18 | }
19 | for (int i = 0; i < 26; i++) {
20 | if (counts[i] < 0) {
21 | return false;
22 | }
23 | }
24 | return true;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RepeatedAlphabets.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | public class RepeatedAlphabets {
4 |
5 | public static void main(String[] args) {
6 |
7 | System.out.println(new RepeatedAlphabets().strWithout3a3b(4, 6));
8 | }
9 |
10 | public static final int THRESHOLD = 3;
11 |
12 | public String strWithout3a3b(int A, int B) {
13 |
14 | int num1 = 0;
15 | char startChar;
16 | int num2 = 0;
17 | char secondChar;
18 | if (A > B) {
19 | num1 = A;
20 | startChar = 'a';
21 | secondChar = 'b';
22 | } else {
23 | num1 = B;
24 | startChar = 'b';
25 | secondChar = 'a';
26 | }
27 |
28 | StringBuilder result = new StringBuilder();
29 | while (num1 > 0 && num2 > 0) {
30 | num1 = appendRepeated(result, num1, startChar);
31 | num2 = appendRepeated(result, num2, secondChar);
32 | }
33 |
34 | appendRepeated(result, num1, ('a'));
35 | appendRepeated(result, num2, ('b'));
36 |
37 | return result.toString();
38 | }
39 |
40 | public int appendRepeated(StringBuilder result, int num1, char alphabet) {
41 |
42 | if (num1 >= THRESHOLD) {
43 | appendAlphabet(result, alphabet, THRESHOLD - 1);
44 | num1 -= THRESHOLD;
45 | } else {
46 | appendAlphabet(result, alphabet, num1);
47 | num1 = 0;
48 | }
49 | return num1;
50 | }
51 |
52 | private void appendAlphabet(StringBuilder result, char alphabet, int times) {
53 | for (int i = 0; i < times; i++) {
54 | result.append(alphabet);
55 | }
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RepeatedNumInArray.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | /**
7 | * https://leetcode.com/problems/n-repeated-element-in-size-2n-array
8 | */
9 | public class RepeatedNumInArray {
10 |
11 | public static void main(String[] args) {
12 |
13 | }
14 |
15 | public int repeatedNTimes(int[] A) {
16 |
17 | if (A == null || A.length == 0) {
18 | return -1;
19 | }
20 |
21 | Set uniqueNumbers = new HashSet<>();
22 | for (int num : A) {
23 | if (uniqueNumbers.contains(num)) {
24 | return num;
25 | }
26 | uniqueNumbers.add(num);
27 | }
28 | return -1;
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/ReverseVowelsInString.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.List;
5 |
6 | /**
7 | * https://leetcode.com/problems/reverse-vowels-of-a-string/
8 | */
9 | public class ReverseVowelsInString {
10 | public static void main(String[] args) {
11 | // System.out.println(reverseVowels("hello"));
12 | // System.out.println(reverseVowels("leetcode"));
13 | System.out.println(reverseVowels("Unglad, I tar a tidal gnu."));
14 | }
15 |
16 | public static final List VOWELS
17 | = Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
18 |
19 | // In place
20 | public static String reverseVowels(String str) {
21 |
22 | char[] chars = str.toCharArray();
23 | int i = 0, j = chars.length - 1;
24 | while (true) {
25 | while (i < chars.length && !isVowel(chars[i])) i++;
26 | while (j >= 0 && !isVowel(chars[j])) j--;
27 |
28 | if (j < 0 || i >= chars.length || i >= j) {
29 | break;
30 | } else {
31 | swap(chars, i++, j--);
32 | }
33 | }
34 | return new String(chars);
35 | }
36 |
37 | private static void swap(char[] str, int i, int j) {
38 | char temp = str[i];
39 | str[i] = str[j];
40 | str[j] = temp;
41 | }
42 |
43 | private static boolean isVowel(char c) {
44 | return VOWELS.contains(c);
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/RotateFunction.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/rotate-function/
5 | */
6 | public class RotateFunction {
7 | public static void main(String[] args) {
8 | System.out.println(maxRotateFunction(new int[]{4, 3, 2, 6}));
9 | }
10 |
11 | public static int maxRotateFunction(int[] A) {
12 |
13 | int n = A.length;
14 | int max = 0;
15 | for (int i = 0; i < n; i++) {
16 | int currMax = 0;
17 | for (int j = 0; j < n; j++) {
18 | currMax += A[(j + i) % n] * j;
19 | }
20 | max = Math.max(max, currMax);
21 | }
22 | return max;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/SentenceScreenFitting.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/sentence-screen-fitting
7 | *
8 | * Unoptimized
9 | */
10 | public class SentenceScreenFitting {
11 | public static void main(String[] args) {
12 | Scanner in = new Scanner(System.in);
13 | String sentence = in.nextLine();
14 | int rows = in.nextInt();
15 | int cols = in.nextInt();
16 | System.out.println(fitOnScreen(sentence, rows, cols));
17 | }
18 |
19 | private static int fitOnScreen(String sentence, int rows, int cols) {
20 | String[] words = sentence.split(" ");
21 | int i = 0, j = 0, wi = 0, count = 0;
22 | while (i < rows) {
23 | if (j == cols - 1 || j + words[wi].length() - 1 >= cols) {
24 | i++;
25 | j = 0;
26 | } else {
27 | j += words[wi].length();
28 | j++; // for space
29 |
30 | if (wi == words.length - 1) {
31 | count++;
32 | wi = 0;
33 | } else {
34 | wi++;
35 | }
36 | }
37 | }
38 | return count;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/Serialize_BT_297.java:
--------------------------------------------------------------------------------
1 | public class Codec {
2 |
3 | public String serialize(TreeNode root) {
4 | StringBuilder sb = new StringBuilder();
5 | marshall(root, sb);
6 | return sb.toString();
7 | }
8 |
9 | private void marshall(TreeNode node, StringBuilder sb){
10 | if(node == null){
11 | sb.append("X,");
12 | } else {
13 | sb.append(node.val).append(",");
14 | marshall(node.left, sb);
15 | marshall(node.right, sb);
16 | }
17 | }
18 |
19 | public TreeNode deserialize(String data) {
20 | String[] values = data.split(",");
21 | Deque queue = new ArrayDeque<>();
22 | queue.addAll(Arrays.asList(values));
23 | TreeNode root = unmarshall(queue);
24 | return root;
25 | }
26 |
27 | private TreeNode unmarshall(Deque values){
28 | String val = values.pop();
29 | if (val.equals("X")){
30 | return null;
31 | }
32 | TreeNode node = new TreeNode(Integer.valueOf(val));
33 | node.left = unmarshall(values);
34 | node.right = unmarshall(values);
35 | return node;
36 | }
37 |
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/ShuffleArray.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 | import java.util.Random;
5 |
6 | /**
7 | * https://leetcode.com/problems/shuffle-an-array/
8 | */
9 | public class ShuffleArray {
10 |
11 | private final int[] nums;
12 |
13 | public static void main(String[] args) {
14 | ShuffleArray shuffleArray = new ShuffleArray(new int[]{2, 4, 6, 8, 10});
15 | System.out.println(Arrays.toString(shuffleArray.reset()));
16 | System.out.println(Arrays.toString(shuffleArray.shuffle()));
17 | System.out.println(Arrays.toString(shuffleArray.reset()));
18 | System.out.println(Arrays.toString(shuffleArray.shuffle()));
19 | }
20 |
21 | public ShuffleArray(int[] nums) {
22 | this.nums = nums;
23 | }
24 |
25 | public int[] reset() {
26 | return nums;
27 | }
28 |
29 | /**
30 | * Returns a random shuffling of the array.
31 | */
32 | public int[] shuffle() {
33 |
34 | int n = nums.length;
35 | Random random = new Random();
36 |
37 | int[] shuffled = Arrays.copyOf(nums, n);
38 | for (int i = 0; i < shuffled.length - 1; i++) {
39 | int j = randomBetween(random, i + 1, n - 1);
40 | int temp = shuffled[i];
41 | shuffled[i] = shuffled[j];
42 | shuffled[j] = temp;
43 | }
44 | return shuffled;
45 | }
46 |
47 | private int randomBetween(Random random, int min, int max) {
48 | return random.nextInt(max - min + 1) + min;
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/SqauresOfSortedArray.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Arrays;
4 |
5 | public class SqauresOfSortedArray {
6 |
7 | public static void main(String[] args) {
8 | int[] result = new SqauresOfSortedArray().sortedSquares(new int[]{-7, -3, 0, 3, 5});
9 | // int[] result = new SqauresOfSortedArray().sortedSquares(new int[]{-7, -3, -1});
10 | System.out.println(Arrays.toString(result));
11 | }
12 |
13 | public int[] sortedSquares(int[] A) {
14 |
15 | int midIdx = indexOfSmallestNegative(A);
16 | int[] result = new int[A.length];
17 |
18 | int leftIdx = midIdx;
19 | int rightIdx = midIdx + 1;
20 |
21 | int rstIdx = 0;
22 | while (leftIdx >= 0 || rightIdx < A.length) {
23 | if (leftIdx < 0) {
24 | result[rstIdx++] = A[rightIdx] * A[rightIdx];
25 | rightIdx++;
26 | } else if (rightIdx >= A.length) {
27 | result[rstIdx++] = A[leftIdx] * A[leftIdx];
28 | leftIdx--;
29 | } else {
30 | if (Math.abs(A[leftIdx]) > A[rightIdx]) {
31 | result[rstIdx++] = A[rightIdx] * A[rightIdx];
32 | rightIdx++;
33 | } else {
34 | result[rstIdx++] = A[leftIdx] * A[leftIdx];
35 | leftIdx--;
36 | }
37 | }
38 | }
39 |
40 | return result;
41 | }
42 |
43 | private int indexOfSmallestNegative(int[] sortedArray) {
44 | int idx = 0;
45 | while (idx < sortedArray.length && sortedArray[idx] < 0) {
46 | idx++;
47 | }
48 | return idx - 1;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/SumOfLeftLeaves.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/sum-of-left-leaves/
5 | */
6 | public class SumOfLeftLeaves {
7 |
8 | public int sumOfLeftLeaves(TreeNode root) {
9 | return visit(root);
10 | }
11 |
12 | private int visit(TreeNode node) {
13 | if (node == null) {
14 | return 0;
15 | } else {
16 | int temp = 0;
17 | if (hasLeftLeaf(node)) {
18 | temp = node.left.val;
19 | }
20 | int left = visit(node.left);
21 | int right = visit(node.right);
22 | return left + right + temp;
23 | }
24 | }
25 |
26 | private boolean hasLeftLeaf(TreeNode node) {
27 | return node != null
28 | && node.left != null
29 | && node.left.left == null
30 | && node.left.right == null;
31 | }
32 |
33 | public class TreeNode {
34 | int val;
35 | TreeNode left;
36 | TreeNode right;
37 |
38 | TreeNode(int x) {
39 | val = x;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/ThirdMax.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * https://leetcode.com/problems/third-maximum-number/
7 | */
8 | public class ThirdMax {
9 | public static void main(String[] args) {
10 | Scanner in = new Scanner(System.in);
11 | int n = in.nextInt();
12 | int[] arr = new int[n];
13 | for (int i = 0; i < n; i++) {
14 | arr[i] = in.nextInt();
15 | }
16 | System.out.println(thirdMax(arr));
17 | }
18 |
19 | public static int thirdMax(int[] nums) {
20 | Integer m1 = Integer.MIN_VALUE, m2 = Integer.MIN_VALUE, m3 = Integer.MIN_VALUE;
21 | for (int i = 0; i < nums.length; i++) {
22 | int val = nums[i];
23 | if (val > m1) {
24 | m3 = m2;
25 | m2 = m1;
26 | m1 = val;
27 | } else if (val > m2 && val != m1) {
28 | m3 = m2;
29 | m2 = val;
30 | } else if (val > m3 && val != m1 && val != m2) {
31 | m3 = val;
32 | }
33 | }
34 |
35 | if (m3 != Integer.MIN_VALUE) {
36 | return m3;
37 | }
38 | return m1;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/TopKFrequent.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 | import java.util.Map;
7 |
8 | /**
9 | * https://leetcode.com/problems/top-k-frequent-elements/
10 | */
11 | public class TopKFrequent {
12 |
13 | public static void main(String[] args) {
14 | System.out.println(topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2));
15 | }
16 |
17 | public static List topKFrequent(int[] nums, int k) {
18 |
19 | Map freq = new HashMap<>();
20 | for (int i = 0; i < nums.length; i++) {
21 | freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1);
22 | }
23 |
24 | // frequency can be max nums.length
25 | // wastes lot of space (many slots will be blank),
26 | // but this avoid having to sort the map by value
27 | List[] buckets = new List[nums.length + 1];
28 | for (Map.Entry entry : freq.entrySet()) {
29 | if (buckets[entry.getValue()] == null) {
30 | buckets[entry.getValue()] = new ArrayList<>();
31 | }
32 | buckets[entry.getValue()].add(entry.getKey());
33 | }
34 |
35 | List result = new ArrayList<>();
36 | for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) {
37 | if (buckets[i] != null) {
38 | result.addAll(buckets[i]);
39 | }
40 | }
41 | return result.subList(0, k); // In case buckets[pos] has more elements than k
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/Trie_208.java:
--------------------------------------------------------------------------------
1 | // only allows chars 'a' through 'z'
2 | class Trie {
3 |
4 |
5 | private TrieNode root;
6 |
7 | public Trie(){
8 | root = new TrieNode();
9 | }
10 |
11 | public void insert(String word){
12 |
13 | TrieNode current = root;
14 | for(int i=0; i A[i - 1]) {
31 | return false;
32 | }
33 | }
34 | }
35 |
36 | return increasing == false;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/ValidWordSquare.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | import java.util.Scanner;
4 |
5 | /**
6 | * Unoptimized solution
7 | */
8 | public class ValidWordSquare {
9 |
10 | public static void main(String[] args) {
11 | Scanner in = new Scanner(System.in);
12 | int n = in.nextInt();
13 | String[] words = new String[n];
14 | for (int i = 0; i < n; i++) {
15 | words[i] = in.next();
16 | }
17 | System.out.println(isValidWordSquare(words));
18 | }
19 |
20 | private static boolean isValidWordSquare(String[] words) {
21 | int n = words.length;
22 | for (int i = 0; i < n; i++) {
23 | for (int j = 0; j < words[i].length(); j++) {
24 | if (words[i].charAt(j) != words[j].charAt(i)) {
25 | return false;
26 | }
27 | }
28 | }
29 | return true;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/leetcode/WiggleSequence.java:
--------------------------------------------------------------------------------
1 | package leetcode;
2 |
3 | /**
4 | * https://leetcode.com/problems/wiggle-subsequence/
5 | */
6 | public class WiggleSequence {
7 | public static void main(String[] args) {
8 | // System.out.println(wiggleMaxLength(new int[]{1,7,4,9,2,5}));
9 | // System.out.println(wiggleMaxLength(new int[]{1,17,5,10,13,15,10,5,16,8}));
10 | // System.out.println(wiggleMaxLength(new int[]{1,2,3,4,5,6,7,8,9}));
11 | System.out.println(wiggleMaxLength(new int[]{0, 0}));
12 | }
13 |
14 | public static int wiggleMaxLength(int[] arr) {
15 | int n = arr.length;
16 | if (n == 0 || n == 1) {
17 | return n;
18 | }
19 |
20 | int k = 0;
21 | while (k + 1 < n && arr[k] == arr[k + 1]) k++;
22 | if (k + 1 == n) return 1;
23 |
24 | boolean findSmall = arr[k] < arr[k + 1];
25 | k++;
26 | int count = 2;
27 | while (k + 1 < n) {
28 | if (findSmall && arr[k + 1] < arr[k]) {
29 | findSmall = false;
30 | count++;
31 | } else if (!findSmall && arr[k + 1] > arr[k]) {
32 | findSmall = true;
33 | count++;
34 | }
35 | k++;
36 | }
37 |
38 | return count;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/adder/AdderExample.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.adder;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.atomic.AtomicLong;
6 |
7 | public class AdderExample {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | AtomicLong counter = new AtomicLong(0);
12 |
13 | ExecutorService service = Executors.newFixedThreadPool(16);
14 | for (int i = 0; i < 100; i++) {
15 | service.submit(new Task(counter));
16 | }
17 |
18 | Thread.sleep(2000); // don't do this
19 |
20 | System.out.println(counter.get());
21 | }
22 |
23 | private static class Task implements Runnable {
24 |
25 | private final AtomicLong counter;
26 |
27 | public Task(AtomicLong counter) {
28 | this.counter = counter;
29 | }
30 |
31 | @Override
32 | public void run() {
33 | // some processing
34 | counter.incrementAndGet();
35 | }
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/adder/AdderExample_2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.adder;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.atomic.LongAdder;
6 |
7 | public class AdderExample_2 {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | LongAdder counter = new LongAdder();
12 |
13 | ExecutorService service = Executors.newFixedThreadPool(16);
14 | for (int i = 0; i < 100; i++) {
15 | service.submit(new Task(counter));
16 | }
17 |
18 | Thread.sleep(2000); // don't do this
19 |
20 | System.out.println(counter.sum());
21 | }
22 |
23 | private static class Task implements Runnable {
24 |
25 | private final LongAdder counter;
26 |
27 | public Task(LongAdder counter) {
28 | this.counter = counter;
29 | }
30 |
31 | @Override
32 | public void run() {
33 | // some processing
34 | counter.increment();
35 | }
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/adder/AdderExample_3.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.adder;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.atomic.LongAccumulator;
6 |
7 | public class AdderExample_3 {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | LongAccumulator counter = new LongAccumulator((x, y) -> x + y, 0);
12 |
13 | ExecutorService service = Executors.newFixedThreadPool(16);
14 | for (int i = 0; i < 100; i++) {
15 | service.submit(new Task(counter));
16 | }
17 |
18 | Thread.sleep(2000); // don't do this
19 |
20 | System.out.println(counter.get());
21 | }
22 |
23 | private static class Task implements Runnable {
24 |
25 | private final LongAccumulator counter;
26 |
27 | public Task(LongAccumulator counter) {
28 | this.counter = counter;
29 | }
30 |
31 | @Override
32 | public void run() {
33 | // some processing
34 | counter.accumulate(1);
35 | }
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/adder/AdderExample_4.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.adder;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.atomic.LongAccumulator;
6 |
7 | public class AdderExample_4 {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | LongAccumulator counter = new LongAccumulator((x, y) -> x + y, 0);
12 | LongAccumulator result = new LongAccumulator((x, y) -> x * y, 0);
13 | LongAccumulator min = new LongAccumulator((x, y) -> Math.min(x, y), Integer.MAX_VALUE);
14 | LongAccumulator max = new LongAccumulator((x, y) -> Math.max(x, y), Integer.MIN_VALUE);
15 |
16 | ExecutorService service = Executors.newFixedThreadPool(16);
17 | for (int i = 0; i < 100; i++) {
18 | service.submit(new Task(counter));
19 | }
20 |
21 | Thread.sleep(2000); // don't do this
22 |
23 | System.out.println(counter.get());
24 | }
25 |
26 | private static class Task implements Runnable {
27 |
28 | private final LongAccumulator counter;
29 |
30 | public Task(LongAccumulator counter) {
31 | this.counter = counter;
32 | }
33 |
34 | @Override
35 | public void run() {
36 | // some processing
37 | counter.accumulate(1);
38 | }
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/async/FileIO.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.async;
2 |
3 | import java.io.IOException;
4 | import java.nio.ByteBuffer;
5 | import java.nio.channels.AsynchronousFileChannel;
6 | import java.nio.channels.CompletionHandler;
7 | import java.nio.file.Path;
8 | import java.nio.file.Paths;
9 | import java.nio.file.StandardOpenOption;
10 |
11 | public class FileIO {
12 |
13 | public static void main(String[] args) throws IOException {
14 |
15 | ByteBuffer buffer = ByteBuffer.allocate(1024);
16 |
17 | Path path = Paths.get("/home/file2");
18 | AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
19 |
20 | fileChannel.read(buffer, 0, buffer, new CompletionHandler() {
21 |
22 | @Override
23 | public void completed(Integer result, ByteBuffer data) {
24 | // process data
25 | }
26 |
27 | @Override
28 | public void failed(Throwable exc, ByteBuffer attachment) {
29 |
30 | }
31 | });
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/async/UserAsyncServlet.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.async;
2 |
3 | import javax.servlet.AsyncContext;
4 | import javax.servlet.ServletResponse;
5 | import javax.servlet.annotation.WebServlet;
6 | import javax.servlet.http.HttpServlet;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | @WebServlet(urlPatterns = {"/user"}, asyncSupported = true)
11 | public class UserAsyncServlet extends HttpServlet {
12 |
13 | @Override
14 | public void doGet(HttpServletRequest request,
15 | HttpServletResponse response) {
16 |
17 | final AsyncContext context = request.startAsync();
18 | context.start(new Runnable() {
19 | public void run() {
20 | // make the network call
21 | ServletResponse response = context.getResponse();
22 | // print to the response
23 | context.complete();
24 | }
25 | });
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/async/UserAsyncServlet_2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.async;
2 |
3 | import javax.servlet.AsyncContext;
4 | import javax.servlet.ServletInputStream;
5 | import javax.servlet.annotation.WebServlet;
6 | import javax.servlet.http.HttpServlet;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 | import java.io.IOException;
10 |
11 | @WebServlet(urlPatterns = {"/user"}, asyncSupported = true)
12 | public class UserAsyncServlet_2 extends HttpServlet {
13 |
14 | @Override
15 | public void doGet(HttpServletRequest request,
16 | HttpServletResponse response) throws IOException {
17 |
18 | final AsyncContext context = request.startAsync();
19 | ServletInputStream input = request.getInputStream();
20 | // input.setReadListener(new MyReadListener(input, context));
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/condition/Temp.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.condition;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.atomic.AtomicInteger;
6 |
7 | public class Temp {
8 | public static void main(String[] args) throws InterruptedException {
9 |
10 | AtomicInteger counter = new AtomicInteger(0);
11 | ExecutorService service = Executors.newFixedThreadPool(4);
12 | service.execute(new Task(counter));
13 | service.execute(new Task(counter));
14 | service.execute(new Task(counter));
15 | service.execute(new Task(counter));
16 | service.execute(new Task(counter));
17 | service.execute(new Task(counter));
18 | service.execute(new Task(counter));
19 |
20 | Thread.sleep(1000);
21 | System.out.println(counter.get());
22 | }
23 |
24 | private static class Task implements Runnable {
25 |
26 |
27 | private final AtomicInteger counter;
28 |
29 | public Task(AtomicInteger counter) {
30 | this.counter = counter;
31 | }
32 |
33 | @Override
34 | public void run() {
35 | counter.incrementAndGet();
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/AccountTransfer.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class AccountTransfer {
6 |
7 | private void transfer(Account acc1, Account acc2, BigDecimal amount) {
8 |
9 | synchronized (acc1) {
10 | synchronized (acc2) {
11 | acc1.deduct(amount);
12 | acc2.add(amount);
13 | }
14 | }
15 | }
16 |
17 | private class Account {
18 | public void add(BigDecimal amount) {
19 |
20 | }
21 |
22 | public void deduct(BigDecimal amount) {
23 |
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/AccountTransfer2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.math.BigDecimal;
4 |
5 | public class AccountTransfer2 {
6 |
7 | private void transfer(Account from, Account to, BigDecimal amount) {
8 |
9 | Account acc1 = getLarger(from, to);
10 | Account acc2 = getSmaller(from, to);
11 |
12 | synchronized (acc1) {
13 | synchronized (acc2) {
14 | from.deduct(amount);
15 | to.add(amount);
16 | }
17 | }
18 | }
19 |
20 | private Account getLarger(Account from, Account to) {
21 | return null;
22 | }
23 |
24 | private Account getSmaller(Account from, Account to) {
25 | return null;
26 | }
27 |
28 | private class Account {
29 | public int number;
30 |
31 | public void add(BigDecimal amount) {
32 |
33 | }
34 |
35 | public void deduct(BigDecimal amount) {
36 |
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/DeadLockBasics.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | public class DeadLockBasics {
7 |
8 | public static void main(String[] args) throws InterruptedException {
9 |
10 | DeadLockBasics basics = new DeadLockBasics();
11 | basics.execute();
12 |
13 | Thread.sleep(100000);
14 | }
15 |
16 | private Lock lockA = new ReentrantLock();
17 | private Lock lockB = new ReentrantLock();
18 |
19 | private void execute() {
20 | Thread t1 = new Thread(this::processThis);
21 | Thread t2 = new Thread(this::processThat);
22 |
23 | t1.start();
24 | t2.start();
25 | }
26 |
27 | public void processThis() {
28 | lockA.lock();
29 | // process resource A
30 |
31 | try {
32 | Thread.sleep(100);
33 | } catch (InterruptedException e) {
34 | e.printStackTrace();
35 | }
36 |
37 | lockB.lock();
38 | // process resource A and B
39 |
40 | lockA.unlock();
41 | lockB.unlock();
42 | }
43 |
44 | public void processThat() {
45 | lockB.lock();
46 | // process resource B
47 |
48 | try {
49 | Thread.sleep(100);
50 | } catch (InterruptedException e) {
51 | e.printStackTrace();
52 | }
53 |
54 | lockA.lock();
55 | // process resource A and B
56 |
57 | lockA.unlock();
58 | lockB.unlock();
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/DeadLockBasicsSolved.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | public class DeadLockBasicsSolved {
7 |
8 | public static void main(String[] args) throws InterruptedException {
9 |
10 | DeadLockBasicsSolved basics = new DeadLockBasicsSolved();
11 | basics.execute();
12 |
13 | Thread.sleep(10000);
14 | }
15 |
16 | private Lock lockA = new ReentrantLock();
17 | private Lock lockB = new ReentrantLock();
18 |
19 | private void execute() {
20 | Thread t1 = new Thread(this::processThis);
21 | Thread t2 = new Thread(this::processThat);
22 |
23 | t1.start();
24 | t2.start();
25 | }
26 |
27 | public void processThis() {
28 | lockA.lock();
29 | // process resource A
30 |
31 | lockB.lock();
32 | // process resource A and B
33 |
34 | lockA.unlock();
35 | lockB.unlock();
36 | }
37 |
38 | public void processThat() {
39 |
40 | lockA.lock();
41 | lockB.lock();
42 | // process resource B
43 | // process resource A and B
44 |
45 | lockA.unlock();
46 | lockB.unlock();
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/TypesOfLocks.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.util.concurrent.ArrayBlockingQueue;
4 | import java.util.concurrent.BlockingQueue;
5 | import java.util.concurrent.Semaphore;
6 | import java.util.concurrent.locks.Lock;
7 | import java.util.concurrent.locks.ReentrantLock;
8 |
9 | public class TypesOfLocks {
10 |
11 | private void execute() throws InterruptedException {
12 |
13 | Lock lock = new ReentrantLock();
14 | lock.lock();
15 |
16 | BlockingQueue queue = new ArrayBlockingQueue(16);
17 | queue.take();
18 |
19 | Semaphore sem = new Semaphore(1);
20 | sem.acquire();
21 | }
22 |
23 | public synchronized void process() {
24 |
25 | }
26 |
27 | public static synchronized void count() {
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/TypesOfLocks2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import java.util.concurrent.ArrayBlockingQueue;
4 | import java.util.concurrent.BlockingQueue;
5 | import java.util.concurrent.Semaphore;
6 | import java.util.concurrent.TimeUnit;
7 | import java.util.concurrent.locks.Lock;
8 | import java.util.concurrent.locks.ReentrantLock;
9 |
10 | public class TypesOfLocks2 {
11 |
12 | private void execute() throws InterruptedException {
13 |
14 | Lock lock = new ReentrantLock();
15 | boolean acquired = lock.tryLock(2, TimeUnit.SECONDS);
16 |
17 | BlockingQueue queue = new ArrayBlockingQueue(16);
18 | queue.poll(2, TimeUnit.SECONDS);
19 |
20 | Semaphore sem = new Semaphore(1);
21 | sem.tryAcquire(2, TimeUnit.SECONDS);
22 | }
23 |
24 | public synchronized void process() {
25 |
26 | }
27 |
28 | public static synchronized void count() {
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/deadlocks/TypesOfThreads.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.deadlocks;
2 |
3 | import org.springframework.web.bind.annotation.RequestMapping;
4 |
5 | import java.util.concurrent.ExecutorService;
6 | import java.util.concurrent.Executors;
7 | import java.util.concurrent.ScheduledExecutorService;
8 | import java.util.concurrent.TimeUnit;
9 |
10 | public class TypesOfThreads {
11 |
12 | private void execute() {
13 |
14 | Thread t1 = new Thread();
15 | t1.start();
16 |
17 | ExecutorService pool = Executors.newFixedThreadPool(10);
18 | pool.submit(() -> { /** task **/});
19 |
20 | ScheduledExecutorService schedulers = Executors.newScheduledThreadPool(1);
21 | schedulers.schedule(() -> { /** task **/}, 10, TimeUnit.SECONDS);
22 | }
23 |
24 | @RequestMapping("/user/32")
25 | public void userDetails() {
26 |
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/BasicLock.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks;
2 |
3 | import java.util.concurrent.locks.ReentrantLock;
4 |
5 | @SuppressWarnings("all")
6 | public class BasicLock {
7 |
8 | private static ReentrantLock lock = new ReentrantLock();
9 |
10 | private static void accessResource() {
11 |
12 | lock.lock();
13 |
14 | // access the resource
15 |
16 | lock.unlock();
17 | }
18 |
19 | public static void main(String[] args) {
20 |
21 | Thread t1 = new Thread(() -> accessResource());
22 | t1.start();
23 | Thread t2 = new Thread(() -> accessResource());
24 | t2.start();
25 | Thread t3 = new Thread(() -> accessResource());
26 | t3.start();
27 | Thread t4 = new Thread(() -> accessResource());
28 | t4.start();
29 | }
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/HoldCount.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks;
2 |
3 | import java.util.concurrent.locks.ReentrantLock;
4 |
5 | @SuppressWarnings("all")
6 | public class HoldCount {
7 |
8 | private static ReentrantLock lock = new ReentrantLock();
9 |
10 | private static void accessResource() {
11 |
12 | lock.lock();
13 |
14 | // update shared resource
15 |
16 | if (someCondition()) {
17 | accessResource();
18 | }
19 |
20 | lock.unlock();
21 | }
22 |
23 | private static boolean someCondition() {
24 | return false;
25 | }
26 |
27 | public static void main(String[] args) {
28 |
29 | // Thread t1 = new Thread(() -> accessResource());
30 | // t1.start();
31 | // Thread t2 = new Thread(() -> accessResource());
32 | // t2.start();
33 | // Thread t3 = new Thread(() -> accessResource());
34 | // t3.start();
35 | // Thread t4 = new Thread(() -> accessResource());
36 | // t4.start();
37 | }
38 | }
39 |
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/TryLock.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks;
2 |
3 | import java.util.concurrent.locks.ReentrantLock;
4 |
5 | @SuppressWarnings("all")
6 | public class TryLock {
7 |
8 | private static ReentrantLock lock = new ReentrantLock(true);
9 |
10 | private static void accessResource() {
11 |
12 | boolean lockAcquired = lock.tryLock();
13 |
14 | if (lockAcquired) {
15 | try {
16 | // access resource
17 | } finally {
18 | lock.unlock();
19 | }
20 | } else {
21 | // do alternate thing
22 | }
23 | }
24 |
25 | public static void main(String[] args) {
26 |
27 | Thread t1 = new Thread(() -> accessResource());
28 | t1.start();
29 | Thread t2 = new Thread(() -> accessResource());
30 | t2.start();
31 | Thread t3 = new Thread(() -> accessResource());
32 | t3.start();
33 | Thread t4 = new Thread(() -> accessResource());
34 | t4.start();
35 | }
36 | }
37 |
38 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/TryLockDuration.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks;
2 |
3 | import java.util.concurrent.TimeUnit;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | @SuppressWarnings("all")
7 | public class TryLockDuration {
8 |
9 | private static ReentrantLock lock = new ReentrantLock();
10 |
11 | private static void accessResource() throws InterruptedException {
12 |
13 | boolean lockAcquired = lock.tryLock(0, TimeUnit.SECONDS);
14 |
15 | if (lockAcquired) {
16 | try {
17 | // access resource
18 | } finally {
19 | lock.unlock();
20 | }
21 | } else {
22 | // do alternate thing
23 | }
24 | }
25 |
26 | public static void main(String[] args) {
27 |
28 | // Thread t1 = new Thread(() -> accessResource());
29 | // t1.start();
30 | // Thread t2 = new Thread(() -> accessResource());
31 | // t2.start();
32 | // Thread t3 = new Thread(() -> accessResource());
33 | // t3.start();
34 | // Thread t4 = new Thread(() -> accessResource());
35 | // t4.start();
36 | }
37 | }
38 |
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/striped/Bag.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks.striped;
2 |
3 | public class Bag {
4 |
5 | public boolean hasBlueCandy() {
6 | return false;
7 | }
8 |
9 | public void add(Candy blue) {
10 |
11 | }
12 |
13 | public String getId() {
14 | return "";
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/striped/Candy.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks.striped;
2 |
3 | public class Candy {
4 | public Candy(String color) {
5 |
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/locks/striped/ConcurrencyProblem.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.locks.striped;
2 |
3 | import com.google.common.util.concurrent.Striped;
4 |
5 | import java.util.concurrent.locks.Lock;
6 | import java.util.concurrent.locks.ReentrantLock;
7 |
8 | public class ConcurrencyProblem {
9 |
10 | public static void main(String[] args) {
11 |
12 | Bag bag = new Bag();
13 |
14 | Lock lock = new ReentrantLock();
15 |
16 | lock.lock();
17 | if (!bag.hasBlueCandy()) {
18 | bag.add(new Candy("blue"));
19 | }
20 | lock.unlock();
21 |
22 |
23 | }
24 |
25 | private Striped stripedLocks = Striped.lock(10);
26 |
27 | public void update(Bag bag) {
28 |
29 | Lock lock = stripedLocks.get(bag);
30 |
31 | lock.lock();
32 | if (!bag.hasBlueCandy()) {
33 | bag.add(new Candy("blue"));
34 | }
35 | lock.unlock();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/CountDownLatchExample.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.CountDownLatch;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 |
7 | public class CountDownLatchExample {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | ExecutorService executor = Executors.newFixedThreadPool(4);
12 |
13 | CountDownLatch latch = new CountDownLatch(3);
14 | executor.submit(new DependentService(latch));
15 | executor.submit(new DependentService(latch));
16 | executor.submit(new DependentService(latch));
17 |
18 | latch.await();
19 |
20 | System.out.println("All dependant services initialized");
21 | // program initialized, perform other operations
22 | }
23 |
24 | public static class DependentService implements Runnable {
25 |
26 | private CountDownLatch latch;
27 |
28 | public DependentService(CountDownLatch latch) {
29 | this.latch = latch;
30 | }
31 |
32 | @Override
33 | public void run() {
34 | // startup task
35 | latch.countDown();
36 | // continue w/ other operations
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/CyclicBarrierExample.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.*;
4 |
5 | public class CyclicBarrierExample {
6 |
7 | public static void main(String[] args) throws InterruptedException {
8 |
9 | ExecutorService executor = Executors.newFixedThreadPool(4);
10 |
11 | CyclicBarrier barrier = new CyclicBarrier(3);
12 | executor.submit(new Task(barrier));
13 | executor.submit(new Task(barrier));
14 | executor.submit(new Task(barrier));
15 |
16 | Thread.sleep(5000);
17 | }
18 |
19 | public static class Task implements Runnable {
20 |
21 | private CyclicBarrier barrier;
22 |
23 | public Task(CyclicBarrier barrier) {
24 | this.barrier = barrier;
25 | }
26 |
27 | @Override
28 | public void run() {
29 |
30 | while (true) {
31 | try {
32 | Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
33 | System.out.println("Waiting for barrier" + Thread.currentThread().getName());
34 | Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
35 | barrier.await();
36 | } catch (InterruptedException | BrokenBarrierException e) {
37 | e.printStackTrace();
38 | }
39 | System.out.println("Sent message" + Thread.currentThread().getName());
40 |
41 | // send message to corresponding system
42 | }
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/CyclicBarrierExample_2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.BrokenBarrierException;
4 | import java.util.concurrent.CyclicBarrier;
5 | import java.util.concurrent.ExecutorService;
6 | import java.util.concurrent.Executors;
7 |
8 | public class CyclicBarrierExample_2 {
9 |
10 | public static void main(String[] args) throws InterruptedException {
11 |
12 | ExecutorService executor = Executors.newFixedThreadPool(4);
13 |
14 | CyclicBarrier barrier = new CyclicBarrier(3);
15 | executor.submit(new Task(barrier));
16 | executor.submit(new Task(barrier));
17 | executor.submit(new Task(barrier));
18 |
19 | Thread.sleep(2000);
20 | }
21 |
22 | public static class Task implements Runnable {
23 |
24 | private CyclicBarrier barrier;
25 |
26 | public Task(CyclicBarrier barrier) {
27 | this.barrier = barrier;
28 | }
29 |
30 | @Override
31 | public void run() {
32 |
33 | while (true) {
34 | try {
35 | barrier.await();
36 | } catch (InterruptedException | BrokenBarrierException e) {
37 | e.printStackTrace();
38 | }
39 | // send message to corresponding system
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/PhaserAsCountDownLatch.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Phaser;
6 |
7 | public class PhaserAsCountDownLatch {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | ExecutorService executor = Executors.newFixedThreadPool(4);
12 |
13 | Phaser phaser = new Phaser(3);
14 | executor.submit(new DependentService(phaser));
15 | executor.submit(new DependentService(phaser));
16 | executor.submit(new DependentService(phaser));
17 |
18 | phaser.awaitAdvance(1);
19 |
20 | System.out.println("All dependant services initialized");
21 | // program initialized, perform other operations
22 | }
23 |
24 | public static class DependentService implements Runnable {
25 |
26 | private Phaser phaser;
27 |
28 | public DependentService(Phaser phaser) {
29 | this.phaser = phaser;
30 | }
31 |
32 | @Override
33 | public void run() {
34 | // startup task
35 | phaser.arrive();
36 | // continue w/ other operations
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/PhaserAsCyclicBarrier.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Phaser;
6 |
7 | public class PhaserAsCyclicBarrier {
8 |
9 | public static void main(String[] args) throws InterruptedException {
10 |
11 | ExecutorService executor = Executors.newFixedThreadPool(4);
12 |
13 | Phaser phaser = new Phaser(3);
14 | executor.submit(new Task(phaser));
15 | executor.submit(new Task(phaser));
16 | executor.submit(new Task(phaser));
17 |
18 | Thread.sleep(3000);
19 | }
20 |
21 | public static class Task implements Runnable {
22 |
23 | private Phaser phaser;
24 |
25 | public Task(Phaser phaser) {
26 | this.phaser = phaser;
27 | }
28 |
29 | @Override
30 | public void run() {
31 |
32 | while (true) {
33 | phaser.arriveAndAwaitAdvance();
34 | // send message to corresponding system
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/PhaserAsCyclicBarrier_2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Phaser;
6 | import java.util.concurrent.ThreadLocalRandom;
7 |
8 | public class PhaserAsCyclicBarrier_2 {
9 |
10 | public static void main(String[] args) throws InterruptedException {
11 |
12 | ExecutorService executor = Executors.newFixedThreadPool(4);
13 |
14 | Phaser phaser = new Phaser(3);
15 | executor.submit(new Task(phaser));
16 | executor.submit(new Task(phaser));
17 | executor.submit(new Task(phaser));
18 |
19 | Thread.sleep(2000);
20 | }
21 |
22 | public static class Task implements Runnable {
23 |
24 | private Phaser phaser;
25 |
26 | public Task(Phaser phaser) {
27 | this.phaser = phaser;
28 | }
29 |
30 | @Override
31 | public void run() {
32 |
33 | while (true) {
34 | try {
35 | Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
36 | System.out.println("Waiting for phaser" + Thread.currentThread().getName());
37 | Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
38 | } catch (InterruptedException e) {
39 | e.printStackTrace();
40 | }
41 | phaser.arriveAndAwaitAdvance();
42 | System.out.println("Sent message" + Thread.currentThread().getName());
43 | // send message to corresponding system
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/phaser/PhaserRegistration.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.phaser;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Phaser;
6 |
7 | public class PhaserRegistration {
8 |
9 | public static void main(String[] args) {
10 |
11 | ExecutorService executor = Executors.newFixedThreadPool(4);
12 |
13 | Phaser phaser = new Phaser(1);
14 |
15 | executor.submit(new Service(phaser));
16 | executor.submit(new Service(phaser));
17 |
18 | phaser.arriveAndAwaitAdvance();
19 |
20 | phaser.bulkRegister(4);
21 | }
22 |
23 | public static class Service implements Runnable {
24 |
25 | private Phaser phaser;
26 |
27 | public Service(Phaser phaser) {
28 | this.phaser = phaser;
29 | }
30 |
31 | @Override
32 | public void run() {
33 | phaser.register();
34 | // some operations
35 | phaser.arriveAndDeregister();
36 | // other operations
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/questions/producer_consumer/MyBlockingQueue.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.questions.producer_consumer;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 | import java.util.concurrent.locks.Condition;
6 | import java.util.concurrent.locks.ReentrantLock;
7 |
8 | public class MyBlockingQueue {
9 |
10 | private Queue queue;
11 | private int max;
12 | private ReentrantLock lock = new ReentrantLock(true);
13 | private Condition notEmpty = lock.newCondition();
14 | private Condition notFull = lock.newCondition();
15 |
16 | public MyBlockingQueue(int size) {
17 | queue = new LinkedList<>();
18 | this.max = size;
19 | }
20 |
21 | public void put(E e) {
22 | lock.lock();
23 | try {
24 | if (queue.size() == max) {
25 | try {
26 | notFull.await();
27 | } catch (InterruptedException e1) {
28 | e1.printStackTrace();
29 | }
30 | }
31 | queue.add(e);
32 | notEmpty.signalAll();
33 | } finally {
34 | lock.unlock();
35 | }
36 | }
37 |
38 | public E take() {
39 | lock.lock();
40 | try {
41 | if (queue.size() == 0) {
42 | try {
43 | notEmpty.await();
44 | } catch (InterruptedException e) {
45 | e.printStackTrace();
46 | }
47 | }
48 | E item = queue.remove();
49 | notFull.signalAll();
50 | return item;
51 | } finally {
52 | lock.unlock();
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/questions/scatter_gather/ScatterGather.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.questions.scatter_gather;
2 |
3 | import java.util.Collections;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 | import java.util.concurrent.ExecutorService;
7 | import java.util.concurrent.Executors;
8 |
9 | public class ScatterGather {
10 |
11 | String url1, url2, url3;
12 | ExecutorService threadPool = Executors.newFixedThreadPool(4);
13 |
14 | private Set getPrices(int productId) throws InterruptedException {
15 |
16 | Set prices = Collections.synchronizedSet(new HashSet<>());
17 |
18 | threadPool.submit(new Task(url1, productId, prices));
19 | threadPool.submit(new Task(url2, productId, prices));
20 | threadPool.submit(new Task(url3, productId, prices));
21 |
22 | Thread.sleep(3 * 1000);
23 |
24 | return prices;
25 | }
26 |
27 | private class Task implements Runnable {
28 |
29 | private String url;
30 | private int productId;
31 | private Set prices;
32 |
33 | public Task(String url, int productId, Set prices) {
34 | this.url = url;
35 | this.productId = productId;
36 | this.prices = prices;
37 | }
38 |
39 | @Override
40 | public void run() {
41 | int price = 0;
42 | // make http call
43 | prices.add(price);
44 | }
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/questions/scatter_gather/ScatterGather5.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.questions.scatter_gather;
2 |
3 | import java.util.Collections;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 | import java.util.concurrent.CompletableFuture;
7 | import java.util.concurrent.ExecutionException;
8 | import java.util.concurrent.TimeUnit;
9 | import java.util.concurrent.TimeoutException;
10 |
11 | public class ScatterGather5 {
12 |
13 | String url1, url2, url3;
14 |
15 | private Set getPrices(int productId) throws InterruptedException, TimeoutException, ExecutionException {
16 |
17 | Set prices = Collections.synchronizedSet(new HashSet<>());
18 |
19 | CompletableFuture task1 = CompletableFuture.runAsync(new Task(url1, productId, prices));
20 | CompletableFuture task2 = CompletableFuture.runAsync(new Task(url2, productId, prices));
21 | CompletableFuture task3 = CompletableFuture.runAsync(new Task(url3, productId, prices));
22 |
23 | CompletableFuture allTasks = CompletableFuture.allOf(task1, task2, task3);
24 | allTasks.get(3, TimeUnit.SECONDS);
25 |
26 | return prices;
27 | }
28 |
29 | private class Task implements Runnable {
30 |
31 | private String url;
32 | private int productId;
33 | private Set prices;
34 |
35 | public Task(String url1, int productId, Set prices) {
36 | this.url = url;
37 | this.productId = productId;
38 | this.prices = prices;
39 | }
40 |
41 | @Override
42 | public void run() {
43 | int price = 0;
44 | // make http call
45 | prices.add(price);
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/semaphore/SemaphoreAsLock.java:
--------------------------------------------------------------------------------
1 | //package teaching.concurrency.semaphore;
2 | //
3 | //import java.util.concurrent.Semaphore;
4 | //
5 | //public class SemaphoreAsLock {
6 | //
7 | // public static void main(String[] args) throws InterruptedException {
8 | //
9 | // Semaphore semaphore = new Semaphore(1);
10 | // }
11 | //
12 | // static class TaskByThread1 implements Runnable {
13 | //
14 | // @Override
15 | // public void run() {
16 | //
17 | // semaphore.acquireUninterruptibly();
18 | // // IO call to the slow service
19 | // semaphore.release();
20 | //
21 | // // rest of processing
22 | // }
23 | //
24 | // private final Semaphore semaphore;
25 | //
26 | // public Task(Semaphore semaphore) {
27 | // this.semaphore = semaphore;
28 | // }
29 | //
30 | // }
31 | //}
32 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/semaphore/SemaphoreSample.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.semaphore;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.TimeUnit;
6 | import java.util.stream.IntStream;
7 |
8 | public class SemaphoreSample {
9 |
10 | public static void main(String[] args) throws InterruptedException {
11 |
12 | ExecutorService service = Executors.newFixedThreadPool(50);
13 | IntStream.of(1000).forEach(i -> service.execute(new Task()));
14 |
15 | service.shutdown();
16 | service.awaitTermination(1, TimeUnit.MINUTES);
17 | }
18 |
19 | static class Task implements Runnable {
20 |
21 | @Override
22 | public void run() {
23 | // some processing
24 | // IO call to the slow service
25 | // rest of processing
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/main/java/teaching/concurrency/semaphore/SemaphoreSample2.java:
--------------------------------------------------------------------------------
1 | package teaching.concurrency.semaphore;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 | import java.util.concurrent.Semaphore;
6 | import java.util.concurrent.TimeUnit;
7 | import java.util.stream.IntStream;
8 |
9 | public class SemaphoreSample2 {
10 |
11 | public static void main(String[] args) throws InterruptedException {
12 |
13 | Semaphore semaphore = new Semaphore(3);
14 |
15 | ExecutorService service = Executors.newFixedThreadPool(50);
16 | IntStream.of(1000).forEach(i -> service.execute(new Task(semaphore)));
17 |
18 | service.shutdown();
19 | service.awaitTermination(1, TimeUnit.MINUTES);
20 | }
21 |
22 | static class Task implements Runnable {
23 |
24 | @Override
25 | public void run() {
26 | // some processing
27 |
28 | semaphore.acquireUninterruptibly();
29 | // IO call to the slow service
30 | semaphore.release();
31 |
32 | // rest of processing
33 | }
34 |
35 | private final Semaphore semaphore;
36 |
37 | public Task(Semaphore semaphore) {
38 | this.semaphore = semaphore;
39 | }
40 |
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_1.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | public class _1 {
4 |
5 | public static void main(String[] args) {
6 |
7 | Thread thread1 = new Thread(new Task());
8 | thread1.start();
9 | System.out.println("Thread Name: " + Thread.currentThread().getName());
10 | }
11 |
12 | static class Task implements Runnable {
13 | public void run() {
14 | System.out.println("Thread Name: " + Thread.currentThread().getName());
15 | }
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_10.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.List;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 | import java.util.concurrent.TimeUnit;
7 |
8 | public class _10 {
9 |
10 | public static void main(String[] args) throws InterruptedException {
11 |
12 | ExecutorService service = Executors.newFixedThreadPool(10);
13 | for (int i = 0; i < 100; i++) {
14 | service.execute(new Task());
15 | }
16 |
17 | // initiate shutdown
18 | service.shutdown();
19 |
20 | // will throw RejectionExecutionException
21 | // service.execute(new Task());
22 |
23 | // will return true, since shutdown has begun
24 | service.isShutdown();
25 |
26 | // will return true if all tasks are completed
27 | // including queued ones
28 | service.isTerminated();
29 |
30 | // block until all tasks are completed or if timeout occurs
31 | service.awaitTermination(10, TimeUnit.SECONDS);
32 |
33 | // will initiate shutdown and return all queued tasks
34 | List runnables = service.shutdownNow();
35 |
36 | }
37 |
38 | static class Task implements Runnable {
39 | public void run() {
40 | System.out.println("Thread Name: " + Thread.currentThread().getName());
41 | }
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_11.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.Random;
4 | import java.util.concurrent.*;
5 |
6 | public class _11 {
7 |
8 | public static void main(String[] args) {
9 |
10 | ExecutorService service = Executors.newFixedThreadPool(10);
11 |
12 | // submit task and accept the placeholder object for return value
13 | Future future = service.submit(new Task());
14 |
15 | // some optional unrelated operations
16 |
17 | // get the task return value (this may block until task is completed)
18 | try {
19 | Integer result = future.get();
20 | System.out.println("Result from the task is " + result);
21 | } catch (InterruptedException e) {
22 | e.printStackTrace();
23 | } catch (ExecutionException e) {
24 | e.printStackTrace();
25 | }
26 | }
27 |
28 | static class Task implements Callable {
29 | @Override
30 | public Integer call() throws Exception {
31 | return new Random().nextInt();
32 | }
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_12.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 | import java.util.Random;
6 | import java.util.concurrent.*;
7 |
8 | public class _12 {
9 |
10 | public static void main(String[] args) {
11 |
12 | // create the pool
13 | ExecutorService service = Executors.newFixedThreadPool(10);
14 |
15 | // submit the tasks for execution
16 | List allFutures = new ArrayList<>();
17 | for (int i = 0; i < 100; i++) {
18 | Future future = service.submit(new Task());
19 | allFutures.add(future);
20 | }
21 |
22 | // 100 futures, with 100 placeholders.
23 |
24 | // perform some unrelated operations
25 |
26 | // 100 seconds
27 | for (int i = 0; i < 100; i++) {
28 | Future future = allFutures.get(i);
29 | try {
30 | Integer result = future.get(); // blocking
31 | System.out.println("Result of future #" + i + "=" + result);
32 | } catch (InterruptedException e) {
33 | e.printStackTrace();
34 | } catch (ExecutionException e) {
35 | e.printStackTrace();
36 | }
37 | }
38 |
39 |
40 | System.out.println("Thread Name: " + Thread.currentThread().getName());
41 | }
42 |
43 | static class Task implements Callable {
44 | @Override
45 | public Integer call() throws Exception {
46 | Thread.sleep(3000);
47 | return new Random().nextInt();
48 | }
49 | }
50 |
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_13.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.Random;
4 | import java.util.concurrent.*;
5 |
6 | public class _13 {
7 |
8 | public static void main(String[] args) {
9 |
10 | ExecutorService service = Executors.newFixedThreadPool(10);
11 |
12 | // submit task and accept the placeholder object for return value
13 | Future future = service.submit(new Task());
14 |
15 | // some optional unrelated operations
16 |
17 | // get the task return value (this may block until task is completed)
18 |
19 | // Cancel the task
20 | future.cancel(false);
21 |
22 | // Returns true if task was cancelled
23 | future.isCancelled();
24 |
25 | // Returns true is task is completed (successfully or otherwise)
26 | future.isDone();
27 |
28 | try {
29 | Integer result = future.get(1, TimeUnit.SECONDS);
30 | System.out.println("Result from the task is " + result);
31 | } catch (InterruptedException e) {
32 | e.printStackTrace();
33 | } catch (ExecutionException e) {
34 | e.printStackTrace();
35 | } catch (TimeoutException e) {
36 | System.out.println("Couldn't complete task before timeout");
37 | }
38 | }
39 |
40 | static class Task implements Callable {
41 | @Override
42 | public Integer call() throws Exception {
43 | return new Random().nextInt();
44 | }
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_2.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | public class _2 {
4 |
5 | public static void main(String[] args) {
6 |
7 | for (int i = 0; i < 10; i++) {
8 | Thread thread = new Thread(new Task());
9 | thread.start();
10 | }
11 | System.out.println("Thread Name: " + Thread.currentThread().getName());
12 | }
13 |
14 | static class Task implements Runnable {
15 | public void run() {
16 | System.out.println("Thread Name: " + Thread.currentThread().getName());
17 | }
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_3.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _3 {
7 |
8 | public static void main(String[] args) {
9 |
10 | // create the pool
11 | ExecutorService service = Executors.newFixedThreadPool(10);
12 |
13 | // submit the tasks for execution
14 | for (int i = 0; i < 100; i++) {
15 | service.execute(new Task());
16 | }
17 | System.out.println("Thread Name: " + Thread.currentThread().getName());
18 | }
19 |
20 | static class Task implements Runnable {
21 | public void run() {
22 | System.out.println("Thread Name: " + Thread.currentThread().getName());
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_4.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _4 {
7 |
8 | public static void main(String[] args) {
9 |
10 | // get count of available cores
11 | int coreCount = Runtime.getRuntime().availableProcessors();
12 | ExecutorService service = Executors.newFixedThreadPool(coreCount);
13 |
14 | // submit the tasks for execution
15 | for (int i = 0; i < 100; i++) {
16 | service.execute(new CpuIntensiveTask());
17 | }
18 | }
19 |
20 | static class CpuIntensiveTask implements Runnable {
21 | public void run() {
22 | // some CPU intensive operations
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_5.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _5 {
7 |
8 | public static void main(String[] args) {
9 |
10 | // much higher count for IO tasks
11 | ExecutorService service = Executors.newFixedThreadPool(100);
12 |
13 | // submit the tasks for execution
14 | for (int i = 0; i < 100; i++) {
15 | service.execute(new IOTask());
16 | }
17 | }
18 |
19 | static class IOTask implements Runnable {
20 | public void run() {
21 | // some IO operations which will cause thread to block/wait
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_6.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _6 {
7 |
8 | public static void main(String[] args) {
9 |
10 | // for lot of short lived tasks
11 | ExecutorService service = Executors.newCachedThreadPool();
12 |
13 | // submit the tasks for execution
14 | for (int i = 0; i < 100; i++) {
15 | service.execute(new Task());
16 | }
17 | }
18 |
19 | static class Task implements Runnable {
20 | public void run() {
21 | // short lived task
22 | }
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_7.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.Executors;
4 | import java.util.concurrent.ScheduledExecutorService;
5 | import java.util.concurrent.TimeUnit;
6 |
7 | import static java.util.concurrent.TimeUnit.SECONDS;
8 |
9 | public class _7 {
10 |
11 | public static void main(String[] args) {
12 |
13 | // for scheduling of tasks
14 | ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
15 |
16 | // task to run after 10 second delay
17 | service.schedule(new Task(), 10, SECONDS);
18 |
19 | // task to run repeatedly every 10 seconds
20 | service.scheduleAtFixedRate(new Task(), 15, 10, SECONDS);
21 |
22 | // task to run repeatedly 10 seconds after previous task completes
23 | service.scheduleWithFixedDelay(new Task(), 15, 10, TimeUnit.SECONDS);
24 | }
25 |
26 | static class Task implements Runnable {
27 | public void run() {
28 | // task that needs to run
29 | // based on schedule
30 | }
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_8.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _8 {
7 |
8 | public static void main(String[] args) {
9 |
10 | // create the single-thread-pool
11 | ExecutorService service = Executors.newSingleThreadExecutor();
12 |
13 | // submit the tasks for execution
14 | for (int i = 0; i < 100; i++) {
15 | service.execute(new Task());
16 | }
17 | System.out.println("Thread Name: " + Thread.currentThread().getName());
18 | }
19 |
20 | static class Task implements Runnable {
21 | public void run() {
22 | System.out.println("Thread Name: " + Thread.currentThread().getName());
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/main/java/teaching/executorservice/_9.java:
--------------------------------------------------------------------------------
1 | package teaching.executorservice;
2 |
3 | import java.util.concurrent.*;
4 |
5 | public class _9 {
6 |
7 | public static void main(String[] args) {
8 |
9 | // create the single-thread-pool
10 | ExecutorService service
11 | = new ThreadPoolExecutor(
12 | 10,
13 | 100,
14 | 120, TimeUnit.SECONDS,
15 | new ArrayBlockingQueue<>(300));
16 |
17 | try {
18 | service.execute(new Task());
19 | } catch (RejectedExecutionException e) {
20 | System.err.println("task rejected " + e.getMessage());
21 | }
22 | }
23 |
24 | private static class CustomRejectionHandler implements RejectedExecutionHandler {
25 | @Override
26 | public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
27 | // logging / operations to perform on rejection
28 | }
29 | }
30 |
31 | static class Task implements Runnable {
32 | public void run() {
33 | System.out.println("Thread Name: " + Thread.currentThread().getName());
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/Product.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | public class Product {
4 | public int price;
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/Task.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | import java.util.concurrent.locks.ReentrantLock;
4 |
5 | public class Task {
6 |
7 | private ReentrantLock lock;
8 |
9 | public void task() {
10 |
11 | Fibers.execute(() -> {
12 | calculations();
13 | lock.lock();
14 | updateSharedResource();
15 | lock.unlock();
16 | });
17 | }
18 |
19 | private void updateSharedResource() {
20 |
21 | }
22 |
23 | private void calculations() {
24 |
25 | }
26 |
27 | private static class Fibers {
28 |
29 | public static void execute(Runnable r) {
30 |
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/WithCachedThreadPool.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | @SuppressWarnings("all")
7 | public class WithCachedThreadPool {
8 |
9 | public void updateAllPrices(int discount) {
10 |
11 | ExecutorService threadPool = Executors.newCachedThreadPool();
12 |
13 | for (int i = 0; i < 100_000; i++) {
14 |
15 | int productId = i;
16 | Runnable task = () -> {
17 | Product p = retrieveProduct(productId);
18 | updatePrice(p);
19 | saveInDB(p);
20 | };
21 | threadPool.submit(task);
22 | }
23 | }
24 |
25 | private void updatePrice(Product p) {
26 | }
27 |
28 |
29 | private void saveInDB(Product p) {
30 |
31 | }
32 |
33 | public Product retrieveProduct(int productId) {
34 | return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/WithExecutorService.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class WithExecutorService {
7 |
8 | public void updateAllPrices(int discount) {
9 |
10 | ExecutorService threadPool = Executors.newFixedThreadPool(10);
11 |
12 | for (int i = 0; i < 100_000; i++) {
13 |
14 | int productId = i;
15 | Runnable task = new Runnable() {
16 |
17 | @Override
18 | public void run() {
19 | Product p = retrieveProduct(productId);
20 | updatePrice(p);
21 | saveInDB(p);
22 | }
23 | };
24 | threadPool.submit(task);
25 | }
26 | }
27 |
28 | private void updatePrice(Product p) {
29 |
30 | }
31 |
32 | private void saveInDB(Product p) {
33 |
34 | }
35 |
36 | public Product retrieveProduct(int productId) {
37 | return null;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/WithExecutorServiceLambda.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | @SuppressWarnings("all")
7 | public class WithExecutorServiceLambda {
8 |
9 | public void updateAllPrices(int discount) {
10 |
11 | ExecutorService threadPool = Executors.newFixedThreadPool(10);
12 |
13 | for (int i = 0; i < 100_000; i++) {
14 |
15 | int productId = i;
16 | Runnable task = () -> {
17 | Product p = retrieveProduct(productId);
18 | updatePrice(p);
19 | saveInDB(p);
20 | };
21 | threadPool.submit(task);
22 | }
23 | }
24 |
25 | private void updatePrice(Product p) {
26 |
27 | }
28 |
29 | private void saveInDB(Product p) {
30 |
31 | }
32 |
33 | public Product retrieveProduct(int productId) {
34 | return null;
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/teaching/fiber/WithReactive.java:
--------------------------------------------------------------------------------
1 | package teaching.fiber;
2 |
3 | import reactor.core.publisher.Flux;
4 | import reactor.core.publisher.Mono;
5 | import reactor.core.scheduler.Scheduler;
6 | import reactor.core.scheduler.Schedulers;
7 |
8 |
9 | @SuppressWarnings("all")
10 | public class WithReactive {
11 |
12 | public void updateAllPrices(int discount) {
13 |
14 |
15 | Scheduler scheduler = Schedulers.newParallel("", 10);
16 |
17 | Flux.range(1, 100_1000)
18 | .map(productId -> retrieveProduct(productId))
19 | .map(product -> updatePrice(product))
20 | .flatMap(p -> {
21 | return saveInDB(p);
22 | })
23 | .then();
24 | }
25 |
26 | private Product updatePrice(Product product) {
27 | return null;
28 | }
29 |
30 | private Mono saveInDB(Product p) {
31 | return null;
32 | }
33 |
34 | public Product retrieveProduct(int productId) {
35 | return null;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/main/java/teaching/mm/FieldVisibility.java:
--------------------------------------------------------------------------------
1 | package teaching.mm;
2 |
3 | public class FieldVisibility {
4 |
5 | int x = 0;
6 |
7 | public void writerThread() {
8 | x = 1;
9 | }
10 |
11 | public void readerThread() {
12 | int r2 = x;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/teaching/mm/LockVisibility.java:
--------------------------------------------------------------------------------
1 | package teaching.mm;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | public class LockVisibility {
7 |
8 | int a = 0, b = 0, c = 0, x = 0;
9 | Lock lock = new ReentrantLock();
10 |
11 | public void writerThread() {
12 |
13 | lock.lock();
14 | a = 1;
15 | b = 1;
16 | c = 1;
17 | x = 1;
18 | lock.unlock();
19 | }
20 |
21 | public void readerThread() {
22 |
23 | lock.lock();
24 | int r2 = x;
25 | int d1 = a;
26 | int d2 = b;
27 | int d3 = c;
28 | lock.unlock();
29 | }
30 | }
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/src/main/java/teaching/mm/SynchronizedFieldsVisibility.java:
--------------------------------------------------------------------------------
1 | package teaching.mm;
2 |
3 | public class SynchronizedFieldsVisibility {
4 |
5 | int a = 0, b = 0, c = 0;
6 | volatile int x = 0;
7 |
8 | public void writerThread() {
9 |
10 | synchronized (this) {
11 | a = 1;
12 | b = 1;
13 | c = 1;
14 | x = 1;
15 | }
16 | }
17 |
18 | public void readerThread() {
19 |
20 | synchronized (this) {
21 | int r2 = x;
22 | int d1 = a;
23 | int d2 = b;
24 | int d3 = c;
25 | }
26 | }
27 | }
28 |
29 |
30 |
--------------------------------------------------------------------------------
/src/main/java/teaching/mm/VolatileFieldsVisibility.java:
--------------------------------------------------------------------------------
1 | package teaching.mm;
2 |
3 | public class VolatileFieldsVisibility {
4 |
5 | int a = 0, b = 0, c = 0;
6 | volatile int x = 0;
7 |
8 | public void writerThread() {
9 |
10 | a = 1;
11 | b = 1;
12 | c = 1;
13 |
14 | x = 1; // write of x
15 | }
16 |
17 | public void readerThread() {
18 |
19 | int r2 = x; // read of x
20 |
21 | int d1 = a;
22 | int d2 = b;
23 | int d3 = c;
24 | }
25 | }
26 |
27 |
28 |
--------------------------------------------------------------------------------
/src/main/java/teaching/mm/VolatileVisibility.java:
--------------------------------------------------------------------------------
1 | package teaching.mm;
2 |
3 | public class VolatileVisibility {
4 |
5 | volatile boolean flag = true;
6 |
7 | public void writerThread() {
8 | flag = false;
9 | }
10 |
11 | public void readerThread() {
12 | while (flag) {
13 | // do some operations
14 | }
15 | }
16 | }
17 |
18 |
19 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ConcurrencyComposition.java:
--------------------------------------------------------------------------------
1 | //package teaching.parallelism;
2 | //
3 | //import teaching.lambda.Tax;
4 | //import teaching.lambda.User;
5 | //
6 | //import java.math.BigDecimal;
7 | //
8 | //@SuppressWarnings("all")
9 | //public class ConcurrencyComposition {
10 | //
11 | // private static int ticketsAvailable = 2;
12 | //
13 | // public static void main(String[] args) throws InterruptedException {
14 | //
15 | // User user = fetchUserFromDB();
16 | //
17 | // Tax taxRate = fetchGovtTaxRate();
18 | //
19 | // BigDecimal tax = calculateTax();
20 | //
21 | // saveTaxInDB(user, tax);
22 | // }
23 | //
24 | // private static void saveTaxInDB(User user, BigDecimal tax) {
25 | //
26 | // }
27 | //
28 | // private static BigDecimal calculateTax() {
29 | // return null;
30 | // }
31 | //
32 | // private static Tax fetchGovtTaxRate() {
33 | // return null;
34 | // }
35 | //
36 | // private static User fetchUserFromDB() {
37 | // return null;
38 | // }
39 | //
40 | // private static void bookTicket() {
41 | //
42 | // }
43 | //}
44 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ConcurrencyExample.java:
--------------------------------------------------------------------------------
1 | package teaching.parallelism;
2 |
3 | public class ConcurrencyExample {
4 |
5 | private static int ticketsAvailable = 2;
6 |
7 | public static void main(String[] args) throws InterruptedException {
8 |
9 | new Thread(() -> {
10 | if (ticketsAvailable > 0) {
11 | bookTicket();
12 | ticketsAvailable--;
13 | }
14 | }).start();
15 |
16 | new Thread(() -> {
17 | if (ticketsAvailable > 0) {
18 | bookTicket();
19 | ticketsAvailable--;
20 | }
21 | }).start();
22 |
23 | Thread.sleep(5000);
24 | }
25 |
26 | private static void bookTicket() {
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ConcurrencyExample2.java:
--------------------------------------------------------------------------------
1 | package teaching.parallelism;
2 |
3 | import java.util.concurrent.locks.Lock;
4 | import java.util.concurrent.locks.ReentrantLock;
5 |
6 | @SuppressWarnings("all")
7 | public class ConcurrencyExample2 {
8 |
9 | private static int ticketsAvailable = 2;
10 | private static Lock lock = new ReentrantLock();
11 |
12 | public static void main(String[] args) throws InterruptedException {
13 |
14 | new Thread(() -> {
15 | lock.lock();
16 | if (ticketsAvailable > 0) {
17 | bookTicket();
18 | ticketsAvailable--;
19 | }
20 | lock.unlock();
21 | }).start();
22 |
23 | new Thread(() -> {
24 | lock.lock();
25 | if (ticketsAvailable > 0) {
26 | bookTicket();
27 | ticketsAvailable--;
28 | }
29 | lock.unlock();
30 | }).start();
31 |
32 | Thread.sleep(5000);
33 | }
34 |
35 | private static void bookTicket() {
36 |
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ParallismExample.java:
--------------------------------------------------------------------------------
1 | //package teaching.parallelism;
2 | //
3 | //import teaching.lambda.User;
4 | //
5 | //public class ParallismExample {
6 | //
7 | // private static User user2;
8 | // private static User user1;
9 | //
10 | // public static void main(String[] args) {
11 | //
12 | // new Thread(() -> {
13 | // processTax(user1);
14 | // }).start();
15 | //
16 | // new Thread(() -> {
17 | // processTax(user2);
18 | // }).start();
19 | //
20 | // heavyCalculations();
21 | // }
22 | //
23 | // private static void processTax(User user1) {
24 | //
25 | // }
26 | //
27 | // private static void heavyCalculations() {
28 | //
29 | // }
30 | //}
31 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ParallismExample2.java:
--------------------------------------------------------------------------------
1 | //package teaching.parallelism;
2 | //
3 | //import teaching.lambda.User;
4 | //
5 | //public class ParallismExample2 {
6 | //
7 | // private static User user2;
8 | // private static User user1;
9 | //
10 | // public static void main(String[] args) {
11 | //
12 | // new Thread(() -> {
13 | // processTax(user1);
14 | // }).start();
15 | //
16 | // new Thread(() -> {
17 | // processTax(user2);
18 | // }).start();
19 | //
20 | // heavyCalculations();
21 | // }
22 | //
23 | // private static void processTax(User user1) {
24 | //
25 | // }
26 | //
27 | // private static void heavyCalculations() {
28 | //
29 | // }
30 | //}
31 |
--------------------------------------------------------------------------------
/src/main/java/teaching/parallelism/ParallismExample3.java:
--------------------------------------------------------------------------------
1 | //package teaching.parallelism;
2 | //
3 | //import teaching.lambda.User;
4 | //
5 | //import java.util.concurrent.ExecutorService;
6 | //import java.util.concurrent.Executors;
7 | //
8 | //public class ParallismExample3 {
9 | //
10 | // private static User user2;
11 | // private static User user1;
12 | //
13 | // public static void main(String[] args) {
14 | //
15 | // ExecutorService es = Executors.newFixedThreadPool(4);
16 | // es.submit(() -> processTax(user1));
17 | // es.submit(() -> processTax(user2));
18 | //
19 | // heavyCalculations();
20 | // }
21 | //
22 | // private static void processTax(User user1) {
23 | //
24 | // }
25 | //
26 | // private static void heavyCalculations() {
27 | //
28 | // }
29 | //}
30 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_1.java:
--------------------------------------------------------------------------------
1 | package teaching.reactive;
2 |
3 | import java.util.concurrent.Callable;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 |
7 | public class _1 {
8 |
9 | public static void main(String[] args) {
10 |
11 | _1 object = new _1();
12 | object.printDBValue();
13 | }
14 |
15 | private void printDBValue() {
16 |
17 | ExecutorService service = Executors.newFixedThreadPool(5);
18 |
19 | Task task = new Task();
20 | service.submit(task);
21 | }
22 |
23 | private class Task implements Callable {
24 |
25 | @Override
26 | public String call() {
27 |
28 | // fetch from DB
29 | return "fetched-value";
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_2.java:
--------------------------------------------------------------------------------
1 | package teaching.reactive;
2 |
3 | import java.util.concurrent.ExecutorService;
4 | import java.util.concurrent.Executors;
5 |
6 | public class _2 {
7 |
8 | public static void main(String[] args) {
9 |
10 |
11 | }
12 |
13 | private void printDBValue() {
14 |
15 | ExecutorService service = Executors.newFixedThreadPool(5);
16 | service.submit(() -> {
17 | // fetch from DB
18 | return "fetched-value";
19 | });
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_3.java:
--------------------------------------------------------------------------------
1 | package teaching.reactive;
2 |
3 | import java.util.concurrent.ExecutionException;
4 | import java.util.concurrent.ExecutorService;
5 | import java.util.concurrent.Executors;
6 | import java.util.concurrent.Future;
7 |
8 | public class _3 {
9 |
10 | public static void main(String[] args) throws ExecutionException, InterruptedException {
11 |
12 | }
13 |
14 | private void printDBValue() throws Exception {
15 |
16 | ExecutorService service = Executors.newFixedThreadPool(5);
17 | Future future = service.submit(() -> {
18 | // fetch from DB
19 | return "fetched-value";
20 | });
21 |
22 | String futureValue = future.get(); // blocking
23 | System.out.println(futureValue);
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_4.java:
--------------------------------------------------------------------------------
1 | package teaching.reactive;
2 |
3 | import java.util.concurrent.CompletableFuture;
4 |
5 | public class _4 {
6 |
7 | public static void main(String[] args) {
8 |
9 | CompletableFuture.supplyAsync(() -> {
10 | // fetch from DB
11 | return "fetched-value";
12 | }).thenRunAsync(System.out::println);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_5.java:
--------------------------------------------------------------------------------
1 | package teaching.reactive;
2 |
3 | import java.util.concurrent.CompletableFuture;
4 |
5 | public class _5 {
6 |
7 | public static void main(String[] args) {
8 |
9 | }
10 |
11 | private void printDBValue() {
12 |
13 | CompletableFuture.supplyAsync(() -> {
14 | // fetch from DB
15 | return "fetched-value";
16 | }).thenRunAsync(System.out::println);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/teaching/reactive/_6.java:
--------------------------------------------------------------------------------
1 | //package teaching.reactive;
2 | //
3 | //import io.reactivex.Observable;
4 | //
5 | //public class _6 {
6 | //
7 | // public static void main(String[] args) {
8 | //
9 | // }
10 | //
11 | // private void printAllDBChanges() {
12 | //
13 | // Observable observable = Observable.create(emitter -> {
14 | // while (true) {
15 | // // fetch new value from DB
16 | // emitter.onNext("fetched-value");
17 | // }
18 | // });
19 | // observable.subscribe(System.out::println);
20 | // }
21 | //}
22 |
--------------------------------------------------------------------------------
/src/main/java/teaching/streams/BeforeStreams.java:
--------------------------------------------------------------------------------
1 | package teaching.streams;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | //@SuppressWarnings("All")
6 | public class BeforeStreams {
7 |
8 | public static void main(String[] args) {
9 |
10 | int[] numbers = {4, 1, 13, 90, 16, 2, 0};
11 |
12 | // int min = numbers[0];
13 | // for (int i = 1; i < numbers.length; i++) {
14 | // if (min < numbers[i]) {
15 | // min = numbers[i];
16 | // }
17 | // }
18 | // System.out.println("Minimum is " + min);
19 |
20 | IntStream.of(numbers)
21 | .min()
22 | .ifPresent(System.out::println);
23 |
24 | int min = IntStream.of(numbers)
25 | .min()
26 | .getAsInt();
27 |
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/teaching/streams/BeforeStreams2.java:
--------------------------------------------------------------------------------
1 | package teaching.streams;
2 |
3 | //@SuppressWarnings("All")
4 | public class BeforeStreams2 {
5 |
6 | public static void main(String[] args) {
7 |
8 | int[] numbers = {4, 1, 13, 90, 16, 2, 0};
9 |
10 | for (int i = 0; i < numbers.length; i++) {
11 |
12 | // distinct
13 |
14 |
15 | }
16 |
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/teaching/streams/IntSortStream.java:
--------------------------------------------------------------------------------
1 | package teaching.streams;
2 |
3 | import java.util.Arrays;
4 |
5 | public class IntSortStream {
6 |
7 |
8 | public static void main(String[] args) {
9 |
10 | int[] numbers = {4, 1, 13, 90, 16, 2, 0};
11 |
12 | // clone
13 | int[] copy = Arrays.copyOf(numbers, numbers.length);
14 |
15 | // sort
16 | Arrays.sort(copy);
17 |
18 | // pick first 3
19 | for (int i = 0; i < 3; i++) {
20 | System.out.println(copy[i]);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/teaching/streams/IntSortStream2.java:
--------------------------------------------------------------------------------
1 | package teaching.streams;
2 |
3 | import java.util.stream.IntStream;
4 |
5 | @SuppressWarnings("all")
6 | public class IntSortStream2 {
7 |
8 |
9 | public static void main(String[] args) {
10 |
11 | int[] numbers = {4, 1, 13, 90, 16, 2, 0};
12 |
13 | IntStream.of(numbers)
14 | .sorted()
15 | .limit(3)
16 | .forEach(System.out::println);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/teaching/streams/IntStreams.java:
--------------------------------------------------------------------------------
1 | package teaching.streams;
2 |
3 | import java.util.IntSummaryStatistics;
4 | import java.util.stream.IntStream;
5 |
6 | @SuppressWarnings("ALL")
7 | public class IntStreams {
8 |
9 |
10 | public static void main(String[] args) {
11 |
12 | // int[] numbers = {4, 1, 13, 90, 16, 2, 0};
13 | //
14 | // IntStream.of(numbers).min();
15 | // IntStream.of(numbers).max();
16 | // IntStream.of(numbers).average();
17 | // IntStream.of(numbers).count();
18 | // IntStream.of(numbers).sum();
19 |
20 | int[] numbers = {4, 1, 13, 90, 16, 2, 0};
21 |
22 | IntSummaryStatistics stats
23 | = IntStream.of(numbers).summaryStatistics();
24 |
25 | stats.getMin();
26 | stats.getMax();
27 | stats.getAverage();
28 | stats.getCount();
29 | stats.getSum();
30 | }
31 | }
32 |
--------------------------------------------------------------------------------