Date: Tue, 29 Oct 2019 12:40:39 +0800
Subject: [PATCH 0039/2014] FibonacciNumber
---
Maths/FactorialRecursion.java | 26 ++++++++++++++++++
Maths/FibonacciNumber.java | 37 ++++++++++++++++++++++++++
Others/CountChar.java | 16 ++++-------
Others/Factorial.java | 50 -----------------------------------
4 files changed, 68 insertions(+), 61 deletions(-)
create mode 100644 Maths/FactorialRecursion.java
create mode 100644 Maths/FibonacciNumber.java
delete mode 100644 Others/Factorial.java
diff --git a/Maths/FactorialRecursion.java b/Maths/FactorialRecursion.java
new file mode 100644
index 000000000000..6e12d0babbcd
--- /dev/null
+++ b/Maths/FactorialRecursion.java
@@ -0,0 +1,26 @@
+package Maths;
+
+public class FactorialRecursion {
+
+ /* Driver Code */
+ public static void main(String[] args) {
+ assert factorial(0) == 1;
+ assert factorial(1) == 1;
+ assert factorial(2) == 2;
+ assert factorial(3) == 6;
+ assert factorial(5) == 120;
+ }
+
+ /**
+ * Recursive FactorialRecursion Method
+ *
+ * @param n The number to factorial
+ * @return The factorial of the number
+ */
+ public static long factorial(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("number is negative");
+ }
+ return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
+ }
+}
diff --git a/Maths/FibonacciNumber.java b/Maths/FibonacciNumber.java
new file mode 100644
index 000000000000..89796b337135
--- /dev/null
+++ b/Maths/FibonacciNumber.java
@@ -0,0 +1,37 @@
+package Maths;
+
+/**
+ * Fibonacci: 0 1 1 2 3 5 8 13 21 ...
+ */
+public class FibonacciNumber {
+ public static void main(String[] args) {
+ assert isFibonacciNumber(1);
+ assert isFibonacciNumber(2);
+ assert isFibonacciNumber(21);
+ assert !isFibonacciNumber(9);
+ assert !isFibonacciNumber(10);
+ }
+
+ /**
+ * Check if a number is perfect square number
+ *
+ * @param number the number to be checked
+ * @return true if {@code number} is perfect square, otherwise false
+ */
+ public static boolean isPerfectSquare(int number) {
+ int sqrt = (int) Math.sqrt(number);
+ return sqrt * sqrt == number;
+ }
+
+ /**
+ * Check if a number is fibonacci number
+ * This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square
+ *
+ * @param number the number
+ * @return true if {@code number} is fibonacci number, otherwise false
+ * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
+ */
+ public static boolean isFibonacciNumber(int number) {
+ return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
+ }
+}
diff --git a/Others/CountChar.java b/Others/CountChar.java
index ee83bce06a51..8f37217ed5f9 100644
--- a/Others/CountChar.java
+++ b/Others/CountChar.java
@@ -2,13 +2,6 @@
import java.util.Scanner;
-
-/**
- * @author blast314
- *
- * Counts the number of characters in the text.
- */
-
public class CountChar {
public static void main(String[] args) {
@@ -20,11 +13,12 @@ public static void main(String[] args) {
}
/**
- * @param str: String to count the characters
- * @return int: Number of characters in the passed string
+ * Count non space character in string
+ *
+ * @param str String to count the characters
+ * @return number of character in the specified string
*/
private static int CountCharacters(String str) {
- str = str.replaceAll("\\s","");
- return str.length();
+ return str.replaceAll("\\s", "").length();
}
}
diff --git a/Others/Factorial.java b/Others/Factorial.java
deleted file mode 100644
index 652607e5107b..000000000000
--- a/Others/Factorial.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package Others;
-
-import java.util.Scanner;
-
-/**
- * This program will print out the factorial of any non-negative
- * number that you input into it.
- *
- * @author Marcus
- */
-public class Factorial {
-
- /**
- * The main method
- *
- * @param args Command line arguments
- */
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.print("Enter a non-negative integer: ");
-
- //If user does not enter an Integer, we want program to fail gracefully, letting the user know why it terminated
- try {
- int number = input.nextInt();
-
- //We keep prompting the user until they enter a positive number
- while (number < 0) {
- System.out.println("Your input must be non-negative. Please enter a positive number: ");
- number = input.nextInt();
- }
- //Display the result
- System.out.println("The factorial of " + number + " will yield: " + factorial(number));
-
- } catch (Exception e) {
- System.out.println("Error: You did not enter an integer. Program has terminated.");
- }
- input.close();
- }
-
- /**
- * Recursive Factorial Method
- *
- * @param n The number to factorial
- * @return The factorial of the number
- */
- public static long factorial(int n) {
- if (n == 0 || n == 1) return 1;
- return n * factorial(n - 1);
- }
-}
From d1a3ff1aa1d217a9b94640219876fd85e13ab122 Mon Sep 17 00:00:00 2001
From: Hemant Kumar
Date: Thu, 31 Oct 2019 19:58:21 +0530
Subject: [PATCH 0040/2014] Create CONTRIBUTING.md
to avoid 404 for community guidelines.
---
CONTRIBUTING.md | 2 ++
1 file changed, 2 insertions(+)
create mode 100644 CONTRIBUTING.md
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 000000000000..d502de24281c
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,2 @@
+## Contribution Guidelines
+Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
From e08408ca11148af5da53ef5015391a2a139af69f Mon Sep 17 00:00:00 2001
From: Yang Libin
Date: Tue, 19 Nov 2019 16:40:29 +0800
Subject: [PATCH 0041/2014] fix: update FindMin and fix #1170
---
Maths/FindMin.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/Maths/FindMin.java b/Maths/FindMin.java
index 9097c0179f39..90b7ea10926d 100644
--- a/Maths/FindMin.java
+++ b/Maths/FindMin.java
@@ -5,7 +5,7 @@ public class FindMin {
//Driver
public static void main(String[] args) {
int[] array = {2, 4, 9, 7, 19, 94, 5};
- System.out.println("min = " + findMax(array));
+ System.out.println("min = " + findMin(array));
}
/**
@@ -14,7 +14,7 @@ public static void main(String[] args) {
* @param array the array contains element
* @return min value
*/
- public static int findMax(int[] array) {
+ public static int findMin(int[] array) {
int min = array[0];
for (int i = 1; i < array.length; ++i) {
if (array[i] < min) {
From 3259944dbc19380b2741d536a4c059e5d489d7b8 Mon Sep 17 00:00:00 2001
From: Chase Ganey <11964615+cganey@users.noreply.github.com>
Date: Sat, 23 Nov 2019 12:22:27 -0500
Subject: [PATCH 0042/2014] Update BubbleSort.java
Output from print(integers) returns [78, 231, 54, 23, 12, 9, 6, 4, 1]
Correct output should be: [231, 78, 54, 23, 12, 9, 6, 4, 1]
---
Sorts/BubbleSort.java | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index 29d588932c8f..e7b7fdde2440 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -21,7 +21,10 @@ public > T[] sort(T array[]) {
for (int i = 0, size = array.length; i < size - 1; ++i) {
boolean swapped = false;
for (int j = 0; j < size - 1 - i; ++j) {
- swapped = less(array[j], array[j + 1]) && swap(array, j, j + 1);
+ if (less(array[j], array[j + 1])) {
+ swap(array, j, j + 1);
+ swapped = true;
+ }
}
if (!swapped) {
break;
From 9f76ad52b801f251f97115da996b48403574c44b Mon Sep 17 00:00:00 2001
From: BryanChan777 <43082778+BryanChan777@users.noreply.github.com>
Date: Sat, 23 Nov 2019 14:44:55 -0800
Subject: [PATCH 0043/2014] Update README.md
---
README.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/README.md b/README.md
index d0dd123e4d4e..80b5888a5165 100644
--- a/README.md
+++ b/README.md
@@ -2,15 +2,15 @@
[](https://www.paypal.me/TheAlgorithms/100)
-NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we are trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info.
+NOTE: A [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch is made for this repo where we're trying to migrate the existing project to a Java project structure. You can switch to [Development](https://github.com/TheAlgorithms/Java/tree/Development) branch for contributions. Please refer [this issue](https://github.com/TheAlgorithms/Java/issues/474) for more info.
-You can play around (run and edit) the Algorithms or contribute to them using Gitpod.io a free online dev environment with a single click. No need to worry about the Dev enviroment.
+You can run and edit the algorithms or contribute to them using Gitpod.io, a free online development environment, with a single click.
[](https://gitpod.io/#https://github.com/TheAlgorithms/Java)
-### All algorithms implemented in Java (for education)
-These implementations are for learning purposes. They may be less efficient than the implementations in the Java standard library.
+### All algorithms are implemented in Java (for education purposes)
+These implementations are for learning purposes. The implementations may be less efficient than the Java standard library.
## Contribution Guidelines
Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
From 79d29c0bd3ec0f45f157d29c760ae92adead480c Mon Sep 17 00:00:00 2001
From: Arogon1 <40372809+Arogon1@users.noreply.github.com>
Date: Tue, 10 Dec 2019 23:35:54 -0500
Subject: [PATCH 0044/2014] Comment revisions
---
Conversions/DecimalToBinary.java | 2 +-
Conversions/DecimalToHexaDecimal.java | 1 +
Conversions/DecimalToOctal.java | 4 +++-
Conversions/HexaDecimalToBinary.java | 4 +++-
Conversions/IntegerToRoman.java | 20 ++++++++++++++++++++
Conversions/RomanToInteger.java | 1 +
Maths/AbsoluteMax.java | 2 +-
Maths/AbsoluteMin.java | 2 +-
Maths/Factorial.java | 9 ++++++---
Maths/Pow.java | 9 +++++----
10 files changed, 42 insertions(+), 12 deletions(-)
diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java
index 2c8d3218fdfe..c709d0d16cff 100644
--- a/Conversions/DecimalToBinary.java
+++ b/Conversions/DecimalToBinary.java
@@ -5,7 +5,7 @@
/**
* This class converts a Decimal number to a Binary number
*
- * @author Unknown
+ *
*/
class DecimalToBinary {
diff --git a/Conversions/DecimalToHexaDecimal.java b/Conversions/DecimalToHexaDecimal.java
index c9c4e434417c..3d0351dd0122 100644
--- a/Conversions/DecimalToHexaDecimal.java
+++ b/Conversions/DecimalToHexaDecimal.java
@@ -1,5 +1,6 @@
package Conversions;
+//hex = [0 - 9] -> [A - F]
class DecimalToHexaDecimal {
private static final int sizeOfIntInHalfBytes = 8;
private static final int numberOfBitsInAHalfByte = 4;
diff --git a/Conversions/DecimalToOctal.java b/Conversions/DecimalToOctal.java
index 017ab33321b5..98c9f1bb0c48 100644
--- a/Conversions/DecimalToOctal.java
+++ b/Conversions/DecimalToOctal.java
@@ -5,7 +5,7 @@
/**
* This class converts Decimal numbers to Octal Numbers
*
- * @author Unknown
+ *
*/
public class DecimalToOctal {
/**
@@ -13,6 +13,8 @@ public class DecimalToOctal {
*
* @param args Command line Arguments
*/
+
+ //enter in a decimal value to get Octal output
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k, d, s = 0, c = 0;
diff --git a/Conversions/HexaDecimalToBinary.java b/Conversions/HexaDecimalToBinary.java
index 8a79e9b4f00c..091822ce0cb4 100644
--- a/Conversions/HexaDecimalToBinary.java
+++ b/Conversions/HexaDecimalToBinary.java
@@ -1,5 +1,7 @@
package Conversions;
+//Hex [0-9],[A-F] -> Binary [0,1]
+
public class HexaDecimalToBinary {
private final int LONG_BITS = 8;
@@ -9,7 +11,7 @@ public void convert(String numHex) {
int conHex = Integer.parseInt(numHex, 16);
// Hex a Binary:
String binary = Integer.toBinaryString(conHex);
- // Presentation:
+ // Output:
System.out.println(numHex + " = " + completeDigits(binary));
}
diff --git a/Conversions/IntegerToRoman.java b/Conversions/IntegerToRoman.java
index e979eb536336..8886ef4ad016 100644
--- a/Conversions/IntegerToRoman.java
+++ b/Conversions/IntegerToRoman.java
@@ -1,9 +1,29 @@
package Conversions;
+/**
+ * Converting Integers into Roman Numerals
+ *
+ *('I', 1);
+ *('IV',4);
+ *('V', 5);
+ *('IV',9);
+ *('X', 10);
+ *('XL',40;
+ *('L', 50);
+ *('XC',90);
+ *('C', 100);
+ *('D', 500);
+ *('M', 1000);
+ *
+ */
+
+
public class IntegerToRoman {
private static int[] allArabianRomanNumbers = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
private static String[] allRomanNumbers = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
+ //Value must be > 0
+
public static String integerToRoman(int num) {
if (num <= 0) {
return "";
diff --git a/Conversions/RomanToInteger.java b/Conversions/RomanToInteger.java
index 7d6e0650ab46..4563ce4a4a72 100644
--- a/Conversions/RomanToInteger.java
+++ b/Conversions/RomanToInteger.java
@@ -13,6 +13,7 @@ public class RomanToInteger {
put('D', 500);
put('M', 1000);
}};
+ //Roman Number = Roman Numerals
/**
* This function convert Roman number into Integer
diff --git a/Maths/AbsoluteMax.java b/Maths/AbsoluteMax.java
index 18634bc3582f..f454f8ae003d 100644
--- a/Maths/AbsoluteMax.java
+++ b/Maths/AbsoluteMax.java
@@ -15,7 +15,7 @@ public static void main(String[] args) {
}
/**
- * get the value, it's absolute value is max
+ * get the value, return the absolute max value
*
* @param numbers contains elements
* @return the absolute max value
diff --git a/Maths/AbsoluteMin.java b/Maths/AbsoluteMin.java
index 4af43c5c08ac..576019581f9c 100644
--- a/Maths/AbsoluteMin.java
+++ b/Maths/AbsoluteMin.java
@@ -15,7 +15,7 @@ public static void main(String[] args) {
}
/**
- * get the value, it's absolute value is min
+ * get the value, returns the absolute min value min
*
* @param numbers contains elements
* @return the absolute min value
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 1734e93fb83d..3feb43356129 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -1,25 +1,28 @@
package Maths;
+//change around 'n' for different factorial results
public class Factorial {
public static void main(String[] args) {
int n = 5;
System.out.println(n + "! = " + factorial(n));
}
+ //Factorial = n! = n1 * (n-1) * (n-2)*...1
+
/**
- * Calculate factorial
+ * Calculate factorial N
*
* @param n the number
* @return the factorial of {@code n}
*/
public static long factorial(int n) {
if (n < 0) {
- throw new ArithmeticException("n < 0");
+ throw new ArithmeticException("n < 0"); //Dont work with less than 0
}
long fac = 1;
for (int i = 1; i <= n; ++i) {
fac *= i;
}
- return fac;
+ return fac; //Return factorial
}
}
diff --git a/Maths/Pow.java b/Maths/Pow.java
index 605e01d98234..7c0cad1afc9e 100644
--- a/Maths/Pow.java
+++ b/Maths/Pow.java
@@ -1,11 +1,12 @@
package maths;
+//POWER (exponentials) Examples (a^b)
public class Pow {
public static void main(String[] args) {
- assert pow(2, 0) == Math.pow(2, 0);
- assert pow(0, 2) == Math.pow(0, 2);
- assert pow(2, 10) == Math.pow(2, 10);
- assert pow(10, 2) == Math.pow(10, 2);
+ assert pow(2, 0) == Math.pow(2, 0); // == 1
+ assert pow(0, 2) == Math.pow(0, 2); // == 0
+ assert pow(2, 10) == Math.pow(2, 10); // == 1024
+ assert pow(10, 2) == Math.pow(10, 2); // == 100
}
/**
From a6ae9515805c585545762879ff9f2221d757923a Mon Sep 17 00:00:00 2001
From: valery noname
Date: Mon, 30 Dec 2019 13:03:14 +0700
Subject: [PATCH 0045/2014] fix: removed warning for Sorts 'C-style array
declaration of parameter 'array''
---
Sorts/BogoSort.java | 6 +++---
Sorts/BubbleSort.java | 2 +-
Sorts/CombSort.java | 6 +++---
Sorts/RadixSort.java | 14 +++++++-------
4 files changed, 14 insertions(+), 14 deletions(-)
diff --git a/Sorts/BogoSort.java b/Sorts/BogoSort.java
index 299c6b90ec5d..439d51ec6935 100644
--- a/Sorts/BogoSort.java
+++ b/Sorts/BogoSort.java
@@ -12,7 +12,7 @@ public class BogoSort implements SortAlgorithm {
private static final Random random = new Random();
- private static > boolean isSorted(T array[]) {
+ private static > boolean isSorted(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (SortUtils.less(array[i + 1], array[i])) return false;
}
@@ -20,7 +20,7 @@ private static > boolean isSorted(T array[]) {
}
// Randomly shuffles the array
- private static void nextPermutation(T array[]) {
+ private static void nextPermutation(T[] array) {
int length = array.length;
for (int i = 0; i < array.length; i++) {
@@ -29,7 +29,7 @@ private static void nextPermutation(T array[]) {
}
}
- public > T[] sort(T array[]) {
+ public > T[] sort(T[] array) {
while (!isSorted(array)) {
nextPermutation(array);
}
diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java
index e7b7fdde2440..9d2f371786d8 100644
--- a/Sorts/BubbleSort.java
+++ b/Sorts/BubbleSort.java
@@ -17,7 +17,7 @@ class BubbleSort implements SortAlgorithm {
**/
@Override
- public > T[] sort(T array[]) {
+ public > T[] sort(T[] array) {
for (int i = 0, size = array.length; i < size - 1; ++i) {
boolean swapped = false;
for (int j = 0; j < size - 1 - i; ++j) {
diff --git a/Sorts/CombSort.java b/Sorts/CombSort.java
index 23e38323ef36..652fc9f945a6 100644
--- a/Sorts/CombSort.java
+++ b/Sorts/CombSort.java
@@ -33,7 +33,7 @@ private int nextGap(int gap) {
* @return sorted array
*/
@Override
- public > T[] sort(T arr[]) {
+ public > T[] sort(T[] arr) {
int size = arr.length;
// initialize gap
@@ -62,9 +62,9 @@ public > T[] sort(T arr[]) {
}
// Driver method
- public static void main(String args[]) {
+ public static void main(String[] args) {
CombSort ob = new CombSort();
- Integer arr[] = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0};
+ Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0};
ob.sort(arr);
System.out.println("sorted array");
diff --git a/Sorts/RadixSort.java b/Sorts/RadixSort.java
index a207f6bbdda3..ca9ed767eaa0 100644
--- a/Sorts/RadixSort.java
+++ b/Sorts/RadixSort.java
@@ -4,7 +4,7 @@
class RadixSort {
- private static int getMax(int arr[], int n) {
+ private static int getMax(int[] arr, int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
@@ -12,10 +12,10 @@ private static int getMax(int arr[], int n) {
return mx;
}
- private static void countSort(int arr[], int n, int exp) {
- int output[] = new int[n];
+ private static void countSort(int[] arr, int n, int exp) {
+ int[] output = new int[n];
int i;
- int count[] = new int[10];
+ int[] count = new int[10];
Arrays.fill(count, 0);
for (i = 0; i < n; i++)
@@ -33,7 +33,7 @@ private static void countSort(int arr[], int n, int exp) {
arr[i] = output[i];
}
- private static void radixsort(int arr[], int n) {
+ private static void radixsort(int[] arr, int n) {
int m = getMax(arr, n);
@@ -43,14 +43,14 @@ private static void radixsort(int arr[], int n) {
}
- static void print(int arr[], int n) {
+ static void print(int[] arr, int n) {
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
public static void main(String[] args) {
- int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
+ int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
int n = arr.length;
radixsort(arr, n);
print(arr, n);
From dc6f830d072e7077d15b6c22a6ad05072d7de662 Mon Sep 17 00:00:00 2001
From: shellhub
Date: Thu, 9 Jan 2020 18:28:56 +0800
Subject: [PATCH 0046/2014] optimization
---
Sorts/MergeSort.java | 34 ++++++++++++++++------------------
1 file changed, 16 insertions(+), 18 deletions(-)
diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java
index 90392293b58f..2b15a9ce09b4 100644
--- a/Sorts/MergeSort.java
+++ b/Sorts/MergeSort.java
@@ -22,24 +22,22 @@ class MergeSort implements SortAlgorithm {
@Override
@SuppressWarnings("unchecked")
public > T[] sort(T[] unsorted) {
- T[] tmp = (T[]) new Comparable[unsorted.length];
- doSort(unsorted, tmp, 0, unsorted.length - 1);
+ doSort(unsorted, 0, unsorted.length - 1);
return unsorted;
}
/**
* @param arr The array to be sorted
- * @param temp The copy of the actual array
* @param left The first index of the array
* @param right The last index of the array
* Recursively sorts the array in increasing order
**/
- private static > void doSort(T[] arr, T[] temp, int left, int right) {
+ private static > void doSort(T[] arr, int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
- doSort(arr, temp, left, mid);
- doSort(arr, temp, mid + 1, right);
- merge(arr, temp, left, mid, right);
+ doSort(arr, left, mid);
+ doSort(arr, mid + 1, right);
+ merge(arr, left, mid, right);
}
}
@@ -48,36 +46,36 @@ private static > void doSort(T[] arr, T[] temp, int left
* This method implements the merge step of the merge sort
*
* @param arr The array to be sorted
- * @param temp The copy of the actual array
* @param left The first index of the array
* @param mid The middle index of the array
* @param right The last index of the array
* merges two parts of an array in increasing order
**/
- private static > void merge(T[] arr, T[] temp, int left, int mid, int right) {
- System.arraycopy(arr, left, temp, left, right - left + 1);
-
-
+ private static > void merge(T[] arr, int left, int mid, int right) {
+ int length = right - left + 1;
+ T[] temp = (T[]) new Comparable[length];
int i = left;
int j = mid + 1;
- int k = left;
+ int k = 0;
while (i <= mid && j <= right) {
- if (temp[i].compareTo(temp[j]) <= 0) {
- arr[k++] = temp[i++];
+ if (arr[i].compareTo(arr[j]) <= 0) {
+ temp[k++] = arr[i++];
} else {
- arr[k++] = temp[j++];
+ temp[k++] = arr[j++];
}
}
while (i <= mid) {
- arr[k++] = temp[i++];
+ temp[k++] = arr[i++];
}
while (j <= right) {
- arr[k++] = temp[j++];
+ temp[k++] = arr[j++];
}
+
+ System.arraycopy(temp, 0, arr, left, length);
}
// Driver program
From 6f06de18d2301e117e0a27705cbbfe294a184abd Mon Sep 17 00:00:00 2001
From: Christian Clauss
Date: Thu, 9 Jan 2020 21:15:37 +0100
Subject: [PATCH 0047/2014] Create update_directory_md.yml
---
.github/workflows/update_directory_md.yml | 69 +++++++++++++++++++++++
1 file changed, 69 insertions(+)
create mode 100644 .github/workflows/update_directory_md.yml
diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml
new file mode 100644
index 000000000000..a37bf23bd0f0
--- /dev/null
+++ b/.github/workflows/update_directory_md.yml
@@ -0,0 +1,69 @@
+# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push
+name: update_directory_md
+on: [push]
+jobs:
+ update_directory_md:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v1
+ - shell: python # Legacy Python 2.7.15 :-(
+ run: import sys ; print("Python {}.{}.{}".format(*sys.version_info))
+ - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}"
+ run: import sys ; print("Python {}.{}.{}".format(*sys.version_info))
+ - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}"
+ run: |
+ import os
+ from typing import Iterator
+
+ URL_BASE = "https://github.com/TheAlgorithms/Java/blob/master"
+ g_output = []
+
+
+ def good_filepaths(top_dir: str = ".") -> Iterator[str]:
+ for dirpath, dirnames, filenames in os.walk(top_dir):
+ dirnames[:] = [d for d in dirnames if d[0] not in "._"]
+ for filename in filenames:
+ if os.path.splitext(filename)[1].lower() == ".java":
+ yield os.path.join(dirpath, filename).lstrip("./")
+
+
+ def md_prefix(i):
+ return f"{i * ' '}*" if i else "\n##"
+
+
+ def print_path(old_path: str, new_path: str) -> str:
+ global g_output
+ old_parts = old_path.split(os.sep)
+ for i, new_part in enumerate(new_path.split(os.sep)):
+ if i + 1 > len(old_parts) or old_parts[i] != new_part:
+ if new_part:
+ g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ')}")
+ return new_path
+
+
+ def build_directory_md(top_dir: str = ".") -> str:
+ global g_output
+ old_path = ""
+ for filepath in sorted(good_filepaths(), key=str.lower):
+ filepath, filename = os.path.split(filepath)
+ if filepath != old_path:
+ old_path = print_path(old_path, filepath)
+ indent = (filepath.count(os.sep) + 1) if filepath else 0
+ url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
+ filename = os.path.splitext(filename.replace("_", " "))[0]
+ g_output.append(f"{md_prefix(indent)} [{filename}]({url})")
+ return "\n".join(g_output)
+
+
+ with open("DIRECTORY.md", "w") as out_file:
+ out_file.write(build_directory_md(".") + "\n")
+
+ - name: Update DIRECTORY.md
+ run: |
+ cat DIRECTORY.md
+ git config --global user.name github-actions
+ git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com'
+ git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
+ git add DIRECTORY.md
+ git commit -am "updating DIRECTORY.md" || true
+ git push --force origin HEAD:$GITHUB_REF || true
From 23874ffd002bf6401034b2e152ec6fe9728c6fdd Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Thu, 9 Jan 2020 20:16:21 +0000
Subject: [PATCH 0048/2014] updating DIRECTORY.md
---
DIRECTORY.md | 199 +++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 199 insertions(+)
create mode 100644 DIRECTORY.md
diff --git a/DIRECTORY.md b/DIRECTORY.md
new file mode 100644
index 000000000000..17faca9a0fac
--- /dev/null
+++ b/DIRECTORY.md
@@ -0,0 +1,199 @@
+
+## ciphers
+ * [AES](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AES.java)
+ * [AESEncryption](https://github.com/TheAlgorithms/Java/blob/master/ciphers/AESEncryption.java)
+ * [Caesar](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Caesar.java)
+ * [ColumnarTranspositionCipher](https://github.com/TheAlgorithms/Java/blob/master/ciphers/ColumnarTranspositionCipher.java)
+ * [RSA](https://github.com/TheAlgorithms/Java/blob/master/ciphers/RSA.java)
+ * [Vigenere](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Vigenere.java)
+
+## Conversions
+ * [AnyBaseToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnyBaseToAnyBase.java)
+ * [AnyBaseToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnyBaseToDecimal.java)
+ * [AnytoAny](https://github.com/TheAlgorithms/Java/blob/master/Conversions/AnytoAny.java)
+ * [BinaryToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToDecimal.java)
+ * [BinaryToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToHexadecimal.java)
+ * [BinaryToOctal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/BinaryToOctal.java)
+ * [DecimalToAnyBase](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToAnyBase.java)
+ * [DecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToBinary.java)
+ * [DecimalToHexaDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToHexaDecimal.java)
+ * [DecimalToOctal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/DecimalToOctal.java)
+ * [HexaDecimalToBinary](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexaDecimalToBinary.java)
+ * [HexaDecimalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexaDecimalToDecimal.java)
+ * [HexToOct](https://github.com/TheAlgorithms/Java/blob/master/Conversions/HexToOct.java)
+ * [IntegerToRoman](https://github.com/TheAlgorithms/Java/blob/master/Conversions/IntegerToRoman.java)
+ * [OctalToDecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/OctalToDecimal.java)
+ * [OctalToHexadecimal](https://github.com/TheAlgorithms/Java/blob/master/Conversions/OctalToHexadecimal.java)
+ * [RomanToInteger](https://github.com/TheAlgorithms/Java/blob/master/Conversions/RomanToInteger.java)
+
+## DataStructures
+ * Bags
+ * [Bag](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Bags/Bag.java)
+ * Buffers
+ * [CircularBuffer](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Buffers/CircularBuffer.java)
+ * Graphs
+ * [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/BellmanFord.java)
+ * [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/ConnectedComponent.java)
+ * [Cycles](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Cycles.java)
+ * [FloydWarshall](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/FloydWarshall.java)
+ * [Graphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/Graphs.java)
+ * [MatrixGraphs](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/MatrixGraphs.java)
+ * [PrimMST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/PrimMST.java)
+ * HashMap
+ * Hashing
+ * [HashMap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/HashMap.java)
+ * [LinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/LinkedList.java)
+ * [Main](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Main.java)
+ * [Node](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Node.java)
+ * Heaps
+ * [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/EmptyHeapException.java)
+ * [Heap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/Heap.java)
+ * [HeapElement](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/HeapElement.java)
+ * [MaxHeap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MaxHeap.java)
+ * [MinHeap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MinHeap.java)
+ * [MinPriorityQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/MinPriorityQueue.java)
+ * Lists
+ * [CircleLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/CircleLinkedList.java)
+ * [CursorLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/CursorLinkedList.java)
+ * [DoublyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/DoublyLinkedList.java)
+ * [Merge K SortedLinkedlist](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/Merge_K_SortedLinkedlist.java)
+ * [MergeSortedArrayList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/MergeSortedArrayList.java)
+ * [SinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Lists/SinglyLinkedList.java)
+ * Queues
+ * [GenericArrayListQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/GenericArrayListQueue.java)
+ * [LinkedQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/LinkedQueue.java)
+ * [PriorityQueues](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/PriorityQueues.java)
+ * [Queues](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Queues/Queues.java)
+ * Stacks
+ * [BalancedBrackets](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/BalancedBrackets.java)
+ * [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/DecimalToAnyUsingStack.java)
+ * [NodeStack](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/NodeStack.java)
+ * [StackArray](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackArray.java)
+ * [StackArrayList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackArrayList.java)
+ * [StackOfLinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Stacks/StackOfLinkedList.java)
+ * Trees
+ * [AVLTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/AVLTree.java)
+ * [BinaryTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/BinaryTree.java)
+ * [GenericTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/GenericTree.java)
+ * [LevelOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/LevelOrderTraversal.java)
+ * [LevelOrderTraversalQueue](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/LevelOrderTraversalQueue.java)
+ * [PrintTopViewofTree](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/PrintTopViewofTree.java)
+ * [RedBlackBST](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/RedBlackBST.java)
+ * [TreeTraversal](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/TreeTraversal.java)
+ * [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/TrieImp.java)
+ * [ValidBSTOrNot](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Trees/ValidBSTOrNot.java)
+
+## divideconquer
+ * [ClosestPair](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/ClosestPair.java)
+ * [SkylineAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/divideconquer/SkylineAlgorithm.java)
+
+## DynamicProgramming
+ * [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/CoinChange.java)
+ * [EditDistance](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/EditDistance.java)
+ * [EggDropping](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/EggDropping.java)
+ * [Fibonacci](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/Fibonacci.java)
+ * [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/FordFulkerson.java)
+ * [KadaneAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/KadaneAlgorithm.java)
+ * [Knapsack](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/Knapsack.java)
+ * [LevenshteinDistance](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LevenshteinDistance.java)
+ * [LongestCommonSubsequence](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestCommonSubsequence.java)
+ * [LongestIncreasingSubsequence](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestIncreasingSubsequence.java)
+ * [LongestValidParentheses](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/LongestValidParentheses.java)
+ * [MatrixChainMultiplication](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/MatrixChainMultiplication.java)
+ * [RodCutting](https://github.com/TheAlgorithms/Java/blob/master/DynamicProgramming/RodCutting.java)
+
+## Maths
+ * [AbsoluteMax](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMax.java)
+ * [AbsoluteMin](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMin.java)
+ * [AbsoluteValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteValue.java)
+ * [Factorial](https://github.com/TheAlgorithms/Java/blob/master/Maths/Factorial.java)
+ * [FactorialRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FactorialRecursion.java)
+ * [FibonacciNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/FibonacciNumber.java)
+ * [FindMax](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMax.java)
+ * [FindMaxRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMaxRecursion.java)
+ * [FindMin](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMin.java)
+ * [FindMinRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FindMinRecursion.java)
+ * [GCD](https://github.com/TheAlgorithms/Java/blob/master/Maths/GCD.java)
+ * [GCDRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/GCDRecursion.java)
+ * [MaxValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/MaxValue.java)
+ * [MinValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/MinValue.java)
+ * [PalindromeNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/PalindromeNumber.java)
+ * [ParseInteger](https://github.com/TheAlgorithms/Java/blob/master/Maths/ParseInteger.java)
+ * [PerfectNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/PerfectNumber.java)
+ * [Pow](https://github.com/TheAlgorithms/Java/blob/master/Maths/Pow.java)
+ * [PowRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/PowRecursion.java)
+ * [PrimeCheck](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeCheck.java)
+
+## MinimizingLateness
+ * [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/MinimizingLateness/MinimizingLateness.java)
+
+## Misc
+ * [heap sort](https://github.com/TheAlgorithms/Java/blob/master/Misc/heap_sort.java)
+ * [MedianOfRunningArray](https://github.com/TheAlgorithms/Java/blob/master/Misc/MedianOfRunningArray.java)
+ * [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/Misc/PalindromePrime.java)
+
+## Others
+ * [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java)
+ * [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java)
+ * [BrianKernighanAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/BrianKernighanAlgorithm.java)
+ * [CountChar](https://github.com/TheAlgorithms/Java/blob/master/Others/CountChar.java)
+ * [CountWords](https://github.com/TheAlgorithms/Java/blob/master/Others/CountWords.java)
+ * [CRC32](https://github.com/TheAlgorithms/Java/blob/master/Others/CRC32.java)
+ * [CRCAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/CRCAlgorithm.java)
+ * [Dijkshtra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkshtra.java)
+ * [Dijkstra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkstra.java)
+ * [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/Others/EulersFunction.java)
+ * [FibToN](https://github.com/TheAlgorithms/Java/blob/master/Others/FibToN.java)
+ * [FloydTriangle](https://github.com/TheAlgorithms/Java/blob/master/Others/FloydTriangle.java)
+ * [GuassLegendre](https://github.com/TheAlgorithms/Java/blob/master/Others/GuassLegendre.java)
+ * [InsertDeleteInArray](https://github.com/TheAlgorithms/Java/blob/master/Others/InsertDeleteInArray.java)
+ * [KMP](https://github.com/TheAlgorithms/Java/blob/master/Others/KMP.java)
+ * [Krishnamurthy](https://github.com/TheAlgorithms/Java/blob/master/Others/Krishnamurthy.java)
+ * [LinearCongruentialGenerator](https://github.com/TheAlgorithms/Java/blob/master/Others/LinearCongruentialGenerator.java)
+ * [LowestBasePalindrome](https://github.com/TheAlgorithms/Java/blob/master/Others/LowestBasePalindrome.java)
+ * [Palindrome](https://github.com/TheAlgorithms/Java/blob/master/Others/Palindrome.java)
+ * [PasswordGen](https://github.com/TheAlgorithms/Java/blob/master/Others/PasswordGen.java)
+ * [PerlinNoise](https://github.com/TheAlgorithms/Java/blob/master/Others/PerlinNoise.java)
+ * [PowerOfTwoOrNot](https://github.com/TheAlgorithms/Java/blob/master/Others/PowerOfTwoOrNot.java)
+ * [QueueUsingTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/Others/QueueUsingTwoStacks.java)
+ * [RemoveDuplicateFromString](https://github.com/TheAlgorithms/Java/blob/master/Others/RemoveDuplicateFromString.java)
+ * [ReturnSubsequence](https://github.com/TheAlgorithms/Java/blob/master/Others/ReturnSubsequence.java)
+ * [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java)
+ * [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseString.java)
+ * [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/Others/RootPrecision.java)
+ * [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/Others/SieveOfEratosthenes.java)
+ * [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java)
+ * [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java)
+ * [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/Others/StackPostfixNotation.java)
+ * [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/Others/TopKWords.java)
+ * [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/Others/TowerOfHanoi.java)
+
+## Searches
+ * [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java)
+ * [InterpolationSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/InterpolationSearch.java)
+ * [IterativeBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/IterativeBinarySearch.java)
+ * [IterativeTernarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/IterativeTernarySearch.java)
+ * [JumpSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/JumpSearch.java)
+ * [LinearSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/LinearSearch.java)
+ * [SaddlebackSearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/SaddlebackSearch.java)
+ * [SearchAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Searches/SearchAlgorithm.java)
+ * [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/TernarySearch.java)
+
+## Sorts
+ * [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java)
+ * [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java)
+ * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java)
+ * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java)
+ * [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CountingSort.java)
+ * [CycleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CycleSort.java)
+ * [GnomeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/GnomeSort.java)
+ * [HeapSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/HeapSort.java)
+ * [InsertionSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/InsertionSort.java)
+ * [MergeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/MergeSort.java)
+ * [PancakeSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/PancakeSort.java)
+ * [QuickSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/QuickSort.java)
+ * [RadixSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/RadixSort.java)
+ * [SelectionSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SelectionSort.java)
+ * [ShellSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/ShellSort.java)
+ * [SortAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortAlgorithm.java)
+ * [SortUtils](https://github.com/TheAlgorithms/Java/blob/master/Sorts/SortUtils.java)
From 0ff74ca9f89da7f5c097bf0d52123faa7bb95b1d Mon Sep 17 00:00:00 2001
From: shellhub
Date: Sat, 11 Jan 2020 14:19:49 +0800
Subject: [PATCH 0049/2014] optimization
---
Sorts/ShellSort.java | 36 ++++++++++++++----------------------
1 file changed, 14 insertions(+), 22 deletions(-)
diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java
index 49be29b9d200..199f31a8c1ea 100644
--- a/Sorts/ShellSort.java
+++ b/Sorts/ShellSort.java
@@ -2,48 +2,40 @@
import static Sorts.SortUtils.*;
-
-/**
- * @author dpunosevac
- * @author Podshivalov Nikita (https://github.com/nikitap492)
- * @see SortAlgorithm
- */
public class ShellSort implements SortAlgorithm {
/**
* This method implements Generic Shell Sort.
*
- * @param array The array to be sorted
+ * @param array the array to be sorted
*/
@Override
public > T[] sort(T[] array) {
- int N = array.length;
- int h = 1;
+ int length = array.length;
+ int gap = 1;
- while (h < N / 3) {
- h = 3 * h + 1;
+ /* Calculate gap for optimization purpose */
+ while (gap < length / 3) {
+ gap = 3 * gap + 1;
}
- while (h >= 1) {
- for (int i = h; i < N; i++) {
- for (int j = i; j >= h && less(array[j], array[j - h]); j -= h) {
- swap(array, j, j - h);
+ for (; gap > 0; gap /= 3) {
+ for (int i = gap; i < length; i++) {
+ int j;
+ for (j = i; j >= gap && less(array[j], array[j - gap]); j -= gap) {
+ array[j] = array[j - gap];
}
+ array[j] = array[i];
}
-
- h /= 3;
}
-
return array;
}
+ /* Driver Code */
public static void main(String[] args) {
Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12};
ShellSort sort = new ShellSort();
- Integer[] sorted = sort.sort(toSort);
-
- print(sorted);
-
+ print(sort.sort(toSort));
}
}
From be6b25946a652a80139ed57429dce86b10b8d256 Mon Sep 17 00:00:00 2001
From: Caesar
Date: Sun, 26 Jan 2020 14:15:18 +0800
Subject: [PATCH 0050/2014] Fix bug
---
DataStructures/Trees/BinaryTree.java | 17 ++++++++++++-----
1 file changed, 12 insertions(+), 5 deletions(-)
diff --git a/DataStructures/Trees/BinaryTree.java b/DataStructures/Trees/BinaryTree.java
index 75d3af18e56b..6ef4b5ada325 100644
--- a/DataStructures/Trees/BinaryTree.java
+++ b/DataStructures/Trees/BinaryTree.java
@@ -145,12 +145,19 @@ else if (temp.left != null && temp.right != null) {
successor.left.parent = successor;
//If the successor has a right child, the child's grandparent is it's new parent
- if (successor.right != null && successor.parent != temp) {
- successor.right.parent = successor.parent;
- successor.parent.left = successor.right;
- successor.right = temp.right;
- successor.right.parent = successor;
+ if(successor.parent!=temp){
+ if(successor.right!=null){
+ successor.right.parent = successor.parent;
+ successor.parent.left = successor.right;
+ successor.right = temp.right;
+ successor.right.parent = successor;
+ }else{
+ successor.parent.left=null;
+ successor.right=temp.right;
+ successor.right.parent=successor;
+ }
}
+
if (temp == root) {
successor.parent = null;
root = successor;
From 79467b330094ad964525c5eec50d86e564493758 Mon Sep 17 00:00:00 2001
From: Dekas Dimitrios
Date: Sun, 26 Jan 2020 09:57:09 +0200
Subject: [PATCH 0051/2014] Added Best/First/Worst Fit algorithm implementation
---
Others/BestFit.java | 89 ++++++++++++++++++++++++++++++++++++++++++++
Others/FirstFit.java | 70 ++++++++++++++++++++++++++++++++++
Others/WorstFit.java | 76 +++++++++++++++++++++++++++++++++++++
3 files changed, 235 insertions(+)
create mode 100644 Others/BestFit.java
create mode 100644 Others/FirstFit.java
create mode 100644 Others/WorstFit.java
diff --git a/Others/BestFit.java b/Others/BestFit.java
new file mode 100644
index 000000000000..fd072dc2015c
--- /dev/null
+++ b/Others/BestFit.java
@@ -0,0 +1,89 @@
+package Others;
+
+import java.util.Array-List;
+
+/**
+ * @author Dekas Dimitrios
+ */
+public class BestFit {
+ private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
+
+ /**
+ * Method to find the maximum valued element of an array filled with positive integers.
+ *
+ * @param array: an array filled with positive integers.
+ * @return the maximum valued element of the array.
+ */
+ private static int findMaxElement(int[] array) {
+ int max = -1;
+ for (int value : array) {
+ if (value > max) {
+ max = value;
+ }
+ }
+ return max;
+ }
+
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on the best fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findBestFit(int[] blockSizes, int processSize) {
+ // Initialize minDiff with an unreachable value by a difference between a blockSize and the processSize.
+ int minDiff = findMaxElement(blockSizes);
+ int index = NO_ALLOCATION; // If there is no block that can fit the process, return NO_ALLOCATION as the result.
+ for(int i=0 ; i < blockSizes.length ; i++) { // Find the most fitting memory block for the given process.
+ if(blockSizes[i] - processSize < minDiff && blockSizes[i] - processSize >= 0) {
+ minDiff = blockSizes[i] - processSize;
+ index = i;
+ }
+ }
+ return index;
+ }
+
+ /**
+ * Method to allocate memory to blocks according to the best fit
+ * algorithm. It should return an ArrayList of Integers, where the
+ * index is the process ID (zero-indexed) and the value is the block
+ * number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList bestFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the best-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for(int processSize : sizeOfProcesses) {
+ int chosenBlockIdx = findBestFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
+ }
+
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the bestFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION)
+ System.out.print(memAllocation.get(i));
+ else
+ System.out.print("Not Allocated");
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Others/FirstFit.java b/Others/FirstFit.java
new file mode 100644
index 000000000000..61a25b422017
--- /dev/null
+++ b/Others/FirstFit.java
@@ -0,0 +1,70 @@
+package Others;
+
+import java.util.ArrayList;
+
+/**
+ * @author Dekas Dimitrios
+ */
+public class FirstFit {
+ private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
+
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on the first fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findFirstFit(int[] blockSizes, int processSize) {
+ for(int i=0 ; i < blockSizes.length ; i++) {
+ if(blockSizes[i] >= processSize) {
+ return i;
+ }
+ }
+ // If there is not a block that can fit the process, return -255 as the result
+ return NO_ALLOCATION;
+ }
+
+ /**
+ * Method to allocate memory to blocks according to the first fit
+ * algorithm. It should return an ArrayList of Integers, where the
+ * index is the process ID (zero-indexed) and the value is the block
+ * number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList firstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the first-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for(int processSize : sizeOfProcesses) {
+ int chosenBlockIdx = findFirstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
+ }
+
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the firstFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION)
+ System.out.print(memAllocation.get(i));
+ else
+ System.out.print("Not Allocated");
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
diff --git a/Others/WorstFit.java b/Others/WorstFit.java
new file mode 100644
index 000000000000..0bb6c460b6b9
--- /dev/null
+++ b/Others/WorstFit.java
@@ -0,0 +1,76 @@
+package Others;
+
+import java.util.ArrayList;
+
+/**
+ * @author Dekas Dimitrios
+ */
+public class WorstFit {
+ private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
+ // it means that it has not been actually allocated.
+
+ /**
+ * Method to find the index of the memory block that is going to fit the given process based on the worst fit algorithm.
+ *
+ * @param blocks: the array with the available memory blocks.
+ * @param process: the size of the process.
+ * @return the index of the block that fits, or -255 if no such block exists.
+ */
+ private static int findWorstFit(int[] blockSizes, int processSize) {
+ int max = -1;
+ int index = -1;
+ for(int i=0 ; i < blockSizes.length ; i++) { // Find the index of the biggest memory block available.
+ if(blockSizes[i] > max) {
+ max = blockSizes[i];
+ index = i;
+ }
+ }
+ // If the biggest memory block cannot fit the process, return -255 as the result
+ if(processSize > blockSizes[index]) {
+ return NO_ALLOCATION;
+ }
+ return index;
+ }
+
+ /**
+ * Method to allocate memory to blocks according to the worst fit
+ * algorithm. It should return an ArrayList of Integers, where the
+ * index is the process ID (zero-indexed) and the value is the block
+ * number (also zero-indexed).
+ *
+ * @param sizeOfBlocks: an int array that contains the sizes of the memory blocks available.
+ * @param sizeOfProcesses: an int array that contains the sizes of the processes we need memory blocks for.
+ * @return the ArrayList filled with Integers repressenting the memory allocation that took place.
+ */
+ static ArrayList worstFit(int[] sizeOfBlocks, int[] sizeOfProcesses) {
+ // The array list responsible for saving the memory allocations done by the worst-fit algorithm
+ ArrayList memAlloc = new ArrayList<>();
+ // Do this for every process
+ for(int processSize : sizeOfProcesses) {
+ int chosenBlockIdx = findWorstFit(sizeOfBlocks, processSize); // Find the index of the memory block going to be used
+ memAlloc.add(chosenBlockIdx); // Store the chosen block index in the memAlloc array list
+ if(chosenBlockIdx != NO_ALLOCATION) { // Only if a block was chosen to store the process in it,
+ sizeOfBlocks[chosenBlockIdx] -= processSize; // resize the block based on the process size
+ }
+ }
+ return memAlloc;
+ }
+
+ /**
+ * Method to print the memory allocated.
+ *
+ * @param memAllocation: an ArrayList of Integer representing the memory allocation done by the worstFit method.
+ */
+ public static void printMemoryAllocation(ArrayList memAllocation) {
+ System.out.println("Process No.\tBlock No.");
+ System.out.println("===========\t=========");
+ for (int i = 0; i < memAllocation.size(); i++) {
+ System.out.print(" " + i + "\t\t");
+ if (memAllocation.get(i) != NO_ALLOCATION)
+ System.out.print(memAllocation.get(i));
+ else
+ System.out.print("Not Allocated");
+ System.out.println();
+ }
+ }
+}
\ No newline at end of file
From d40464a10d4eb85e225957bdce0545aad8604a39 Mon Sep 17 00:00:00 2001
From: Dekas Dimitrios
Date: Sun, 26 Jan 2020 10:39:07 +0200
Subject: [PATCH 0052/2014] Change Done
---
Others/BestFit.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Others/BestFit.java b/Others/BestFit.java
index fd072dc2015c..71814d22b9f1 100644
--- a/Others/BestFit.java
+++ b/Others/BestFit.java
@@ -1,6 +1,6 @@
package Others;
-import java.util.Array-List;
+import java.util.ArrayList;
/**
* @author Dekas Dimitrios
From 35849905bce916a1537f270730fb0f7a7c836fd7 Mon Sep 17 00:00:00 2001
From: Christian Clauss
Date: Mon, 27 Jan 2020 22:46:56 +0100
Subject: [PATCH 0053/2014] Update update_directory_md.yml
---
.github/workflows/update_directory_md.yml | 10 ++++------
1 file changed, 4 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/update_directory_md.yml b/.github/workflows/update_directory_md.yml
index a37bf23bd0f0..325fa04502af 100644
--- a/.github/workflows/update_directory_md.yml
+++ b/.github/workflows/update_directory_md.yml
@@ -5,12 +5,10 @@ jobs:
update_directory_md:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v1
- - shell: python # Legacy Python 2.7.15 :-(
- run: import sys ; print("Python {}.{}.{}".format(*sys.version_info))
- - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}"
- run: import sys ; print("Python {}.{}.{}".format(*sys.version_info))
- - shell: bash -c "$RUNNER_TOOL_CACHE/Python/3.8.0/x64/python {0}"
+ - uses: actions/checkout@master
+ - uses: actions/setup-python@master
+ - name: update_directory_md
+ shell: python
run: |
import os
from typing import Iterator
From e91999749ee3525e955386c506f885f594504fa4 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Mon, 27 Jan 2020 21:47:30 +0000
Subject: [PATCH 0054/2014] updating DIRECTORY.md
---
DIRECTORY.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 17faca9a0fac..50ae52c55844 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -135,6 +135,7 @@
## Others
* [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java)
* [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java)
+ * [BestFit](https://github.com/TheAlgorithms/Java/blob/master/Others/BestFit.java)
* [BrianKernighanAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/BrianKernighanAlgorithm.java)
* [CountChar](https://github.com/TheAlgorithms/Java/blob/master/Others/CountChar.java)
* [CountWords](https://github.com/TheAlgorithms/Java/blob/master/Others/CountWords.java)
@@ -144,6 +145,7 @@
* [Dijkstra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkstra.java)
* [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/Others/EulersFunction.java)
* [FibToN](https://github.com/TheAlgorithms/Java/blob/master/Others/FibToN.java)
+ * [FirstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/FirstFit.java)
* [FloydTriangle](https://github.com/TheAlgorithms/Java/blob/master/Others/FloydTriangle.java)
* [GuassLegendre](https://github.com/TheAlgorithms/Java/blob/master/Others/GuassLegendre.java)
* [InsertDeleteInArray](https://github.com/TheAlgorithms/Java/blob/master/Others/InsertDeleteInArray.java)
@@ -167,6 +169,7 @@
* [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/Others/StackPostfixNotation.java)
* [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/Others/TopKWords.java)
* [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/Others/TowerOfHanoi.java)
+ * [WorstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/WorstFit.java)
## Searches
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/BinarySearch.java)
From 4f45c5a479d5d723be4a5ee81789b3fe56f661b6 Mon Sep 17 00:00:00 2001
From: Hassan
Date: Tue, 28 Jan 2020 18:18:15 +0200
Subject: [PATCH 0055/2014] Fixing packages.
---
DataStructures/Graphs/BellmanFord.java | 2 ++
DataStructures/Queues/LinkedQueue.java | 2 +-
DataStructures/Stacks/NodeStack.java | 1 +
DataStructures/Stacks/StackArray.java | 2 ++
DataStructures/Stacks/StackArrayList.java | 2 ++
DataStructures/Stacks/StackOfLinkedList.java | 2 ++
Maths/Pow.java | 2 +-
7 files changed, 11 insertions(+), 2 deletions(-)
diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java
index 717cb2803031..61785acec06d 100644
--- a/DataStructures/Graphs/BellmanFord.java
+++ b/DataStructures/Graphs/BellmanFord.java
@@ -1,3 +1,5 @@
+package DataStructures.Graphs;
+
import java.util.*;
class BellmanFord
/*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
diff --git a/DataStructures/Queues/LinkedQueue.java b/DataStructures/Queues/LinkedQueue.java
index 1c85937b9a06..dac13dcaaad6 100644
--- a/DataStructures/Queues/LinkedQueue.java
+++ b/DataStructures/Queues/LinkedQueue.java
@@ -1,4 +1,4 @@
-package DataStructures;
+package DataStructures.Queues;
import java.util.NoSuchElementException;
diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java
index c598bb8fcba1..616e6a1e1548 100644
--- a/DataStructures/Stacks/NodeStack.java
+++ b/DataStructures/Stacks/NodeStack.java
@@ -1,3 +1,4 @@
+package DataStructures.Stacks;
/**
* Implementation of a stack using nodes.
* Unlimited size, no arraylist.
diff --git a/DataStructures/Stacks/StackArray.java b/DataStructures/Stacks/StackArray.java
index 88da42cd3dcb..4365dc448d2d 100644
--- a/DataStructures/Stacks/StackArray.java
+++ b/DataStructures/Stacks/StackArray.java
@@ -1,3 +1,5 @@
+package DataStructures.Stacks;
+
/**
* This class implements a Stack using a regular array.
*
diff --git a/DataStructures/Stacks/StackArrayList.java b/DataStructures/Stacks/StackArrayList.java
index afc804440403..666b9ea99055 100644
--- a/DataStructures/Stacks/StackArrayList.java
+++ b/DataStructures/Stacks/StackArrayList.java
@@ -1,3 +1,5 @@
+package DataStructures.Stacks;
+
import java.util.ArrayList;
/**
diff --git a/DataStructures/Stacks/StackOfLinkedList.java b/DataStructures/Stacks/StackOfLinkedList.java
index 5a2b8fa08258..60d8a1b0f7a0 100644
--- a/DataStructures/Stacks/StackOfLinkedList.java
+++ b/DataStructures/Stacks/StackOfLinkedList.java
@@ -1,5 +1,7 @@
package DataStructures.Stacks;
+import java.util.NoSuchElementException;
+
/**
* @author Varun Upadhyay (https://github.com/varunu28)
*/
diff --git a/Maths/Pow.java b/Maths/Pow.java
index 7c0cad1afc9e..ac58fbbbe7cd 100644
--- a/Maths/Pow.java
+++ b/Maths/Pow.java
@@ -1,4 +1,4 @@
-package maths;
+package Maths;
//POWER (exponentials) Examples (a^b)
public class Pow {
From a1f59c38b1054ced1325ece802d94c243444e055 Mon Sep 17 00:00:00 2001
From: Hassan
Date: Tue, 28 Jan 2020 18:34:52 +0200
Subject: [PATCH 0056/2014] Closing scanners.
---
Conversions/AnyBaseToAnyBase.java | 1 +
Conversions/AnytoAny.java | 1 +
Conversions/DecimalToBinary.java | 1 +
Conversions/HexToOct.java | 3 +--
Conversions/HexaDecimalToDecimal.java | 2 +-
Conversions/OctalToHexadecimal.java | 1 +
DataStructures/Graphs/BellmanFord.java | 1 +
DataStructures/HashMap/Hashing/Main.java | 1 +
DataStructures/Trees/RedBlackBST.java | 1 +
DynamicProgramming/EditDistance.java | 1 +
DynamicProgramming/Fibonacci.java | 1 +
DynamicProgramming/LongestIncreasingSubsequence.java | 1 +
Maths/PrimeCheck.java | 1 +
MinimizingLateness/MinimizingLateness.java | 1 +
Misc/PalindromePrime.java | 1 +
Others/Dijkshtra.java | 1 +
Others/InsertDeleteInArray.java | 1 +
Others/LowestBasePalindrome.java | 1 +
Others/PerlinNoise.java | 1 +
Others/PowerOfTwoOrNot.java | 2 +-
Others/ReturnSubsequence.java | 1 +
Others/RootPrecision.java | 2 ++
Others/SJF.java | 1 +
Others/StackPostfixNotation.java | 2 ++
Others/TopKWords.java | 1 +
Others/TowerOfHanoi.java | 1 +
ciphers/Caesar.java | 1 +
27 files changed, 29 insertions(+), 4 deletions(-)
diff --git a/Conversions/AnyBaseToAnyBase.java b/Conversions/AnyBaseToAnyBase.java
index cfcf0fe9ad61..2cef99260e6b 100644
--- a/Conversions/AnyBaseToAnyBase.java
+++ b/Conversions/AnyBaseToAnyBase.java
@@ -52,6 +52,7 @@ public static void main(String[] args) {
}
}
System.out.println(base2base(n, b1, b2));
+ in.close();
}
/**
diff --git a/Conversions/AnytoAny.java b/Conversions/AnytoAny.java
index 5fc744a9936c..1bc115404696 100644
--- a/Conversions/AnytoAny.java
+++ b/Conversions/AnytoAny.java
@@ -24,6 +24,7 @@ public static void main(String[] args) {
dec /= db;
}
System.out.println(dn);
+ scn.close();
}
}
diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java
index c709d0d16cff..cd84486ae812 100644
--- a/Conversions/DecimalToBinary.java
+++ b/Conversions/DecimalToBinary.java
@@ -53,6 +53,7 @@ public static void bitwiseConversion() {
n >>= 1;
}
System.out.println("\tBinary number: " + b);
+ input.close();
}
}
diff --git a/Conversions/HexToOct.java b/Conversions/HexToOct.java
index a46debfe9992..2807735f72fb 100644
--- a/Conversions/HexToOct.java
+++ b/Conversions/HexToOct.java
@@ -64,7 +64,6 @@ public static void main(String args[]) {
// convert decimal to octal
octalnum = decimal2octal(decnum);
System.out.println("Number in octal: " + octalnum);
-
-
+ scan.close();
}
}
diff --git a/Conversions/HexaDecimalToDecimal.java b/Conversions/HexaDecimalToDecimal.java
index 533009b8ae16..14b0d94d76c2 100644
--- a/Conversions/HexaDecimalToDecimal.java
+++ b/Conversions/HexaDecimalToDecimal.java
@@ -34,7 +34,7 @@ public static void main(String args[]) {
and it returns the decimal form in the variable dec_output.
*/
System.out.println("Number in Decimal: " + dec_output);
-
+ scan.close();
}
}
diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java
index 2cefc92002ca..dd8d877109b5 100644
--- a/Conversions/OctalToHexadecimal.java
+++ b/Conversions/OctalToHexadecimal.java
@@ -59,6 +59,7 @@ public static void main(String args[]) {
// Pass the decimla number to function and get converted Hex form of the number
String hex = DecimalToHex(decimal);
System.out.println("The Hexadecimal equivalant is: " + hex);
+ input.close();
}
}
diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java
index 61785acec06d..6dffede9e606 100644
--- a/DataStructures/Graphs/BellmanFord.java
+++ b/DataStructures/Graphs/BellmanFord.java
@@ -100,6 +100,7 @@ public void go()//Interactive run for understanding the class first time. Assume
System.out.println();
}
}
+ sc.close();
}
/**
* @param source Starting vertex
diff --git a/DataStructures/HashMap/Hashing/Main.java b/DataStructures/HashMap/Hashing/Main.java
index 66f65c1d9064..340f0760b2e5 100644
--- a/DataStructures/HashMap/Hashing/Main.java
+++ b/DataStructures/HashMap/Hashing/Main.java
@@ -42,6 +42,7 @@ public static void main(String[] args) {
return;
}
}
+ In.close();
}
}
}
\ No newline at end of file
diff --git a/DataStructures/Trees/RedBlackBST.java b/DataStructures/Trees/RedBlackBST.java
index 97a88e9a43de..197c96321975 100644
--- a/DataStructures/Trees/RedBlackBST.java
+++ b/DataStructures/Trees/RedBlackBST.java
@@ -309,6 +309,7 @@ public void insertDemo() {
printTreepre(root);
break;
}
+ scan.close();
}
public void deleteDemo() {
diff --git a/DynamicProgramming/EditDistance.java b/DynamicProgramming/EditDistance.java
index 210469b84108..20cb8803a754 100644
--- a/DynamicProgramming/EditDistance.java
+++ b/DynamicProgramming/EditDistance.java
@@ -74,5 +74,6 @@ public static void main(String[] args) {
//ans stores the final Edit Distance between the two strings
int ans = minDistance(s1, s2);
System.out.println("The minimum Edit Distance between \"" + s1 + "\" and \"" + s2 + "\" is " + ans);
+ input.close();
}
}
diff --git a/DynamicProgramming/Fibonacci.java b/DynamicProgramming/Fibonacci.java
index 112a014a378a..89be0836f6af 100644
--- a/DynamicProgramming/Fibonacci.java
+++ b/DynamicProgramming/Fibonacci.java
@@ -22,6 +22,7 @@ public static void main(String[] args) {
System.out.println(fibMemo(n));
System.out.println(fibBotUp(n));
System.out.println(fibOptimized(n));
+ sc.close();
}
/**
diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java
index 2b07e040db13..c8296518590d 100644
--- a/DynamicProgramming/LongestIncreasingSubsequence.java
+++ b/DynamicProgramming/LongestIncreasingSubsequence.java
@@ -17,6 +17,7 @@ public static void main(String[] args) {
}
System.out.println(LIS(ar));
+ sc.close();
}
private static int upperBound(int[] ar, int l, int r, int key) {
diff --git a/Maths/PrimeCheck.java b/Maths/PrimeCheck.java
index 3093894a3a3f..c972aa8c3e5a 100644
--- a/Maths/PrimeCheck.java
+++ b/Maths/PrimeCheck.java
@@ -13,6 +13,7 @@ public static void main(String[] args) {
} else {
System.out.println(n + " is not a prime number");
}
+ scanner.close();
}
/***
diff --git a/MinimizingLateness/MinimizingLateness.java b/MinimizingLateness/MinimizingLateness.java
index e5f71e9ef44a..1438f6f3dbcc 100644
--- a/MinimizingLateness/MinimizingLateness.java
+++ b/MinimizingLateness/MinimizingLateness.java
@@ -53,5 +53,6 @@ public static void main(String[] args) throws IOException {
System.out.println();
System.out.println("Output Data : ");
System.out.println(lateness);
+ in.close();
}
}
diff --git a/Misc/PalindromePrime.java b/Misc/PalindromePrime.java
index b13a23d83792..77a918c32297 100644
--- a/Misc/PalindromePrime.java
+++ b/Misc/PalindromePrime.java
@@ -9,6 +9,7 @@ public static void main(String[] args) { // Main funtion
System.out.println("Enter the quantity of First Palindromic Primes you want");
int n = in.nextInt(); // Input of how many first pallindromic prime we want
functioning(n); // calling function - functioning
+ in.close();
}
public static boolean prime(int num) { // checking if number is prime or not
diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java
index c2b1558e88db..d964d0596718 100644
--- a/Others/Dijkshtra.java
+++ b/Others/Dijkshtra.java
@@ -80,5 +80,6 @@ else if (i != src) {
System.out.print("-1" + " ");
}
}
+ in.close();
}
}
\ No newline at end of file
diff --git a/Others/InsertDeleteInArray.java b/Others/InsertDeleteInArray.java
index 40fd43b2e769..dfb702847275 100644
--- a/Others/InsertDeleteInArray.java
+++ b/Others/InsertDeleteInArray.java
@@ -44,5 +44,6 @@ public static void main(String[] args) {
}
for (i = 0; i < size2 - 1; i++)
System.out.println(b[i]);
+ s.close();
}
}
diff --git a/Others/LowestBasePalindrome.java b/Others/LowestBasePalindrome.java
index 97b445b2ff61..2f8831100d3d 100644
--- a/Others/LowestBasePalindrome.java
+++ b/Others/LowestBasePalindrome.java
@@ -29,6 +29,7 @@ public static void main(String[] args) {
}
System.out.println(n + " is a palindrome in base " + lowestBasePalindrome(n));
System.out.println(base2base(Integer.toString(n), 10, lowestBasePalindrome(n)));
+ in.close();
}
/**
diff --git a/Others/PerlinNoise.java b/Others/PerlinNoise.java
index dbd0a86e4512..f0e7f63dae31 100644
--- a/Others/PerlinNoise.java
+++ b/Others/PerlinNoise.java
@@ -162,5 +162,6 @@ public static void main(String[] args) {
System.out.println();
}
+ in.close();
}
}
diff --git a/Others/PowerOfTwoOrNot.java b/Others/PowerOfTwoOrNot.java
index 349eb9de5807..8f0400133066 100644
--- a/Others/PowerOfTwoOrNot.java
+++ b/Others/PowerOfTwoOrNot.java
@@ -20,6 +20,7 @@ public static void main(String[] args) {
} else {
System.out.println("Number is not a power of two");
}
+ sc.close();
}
@@ -32,5 +33,4 @@ public static void main(String[] args) {
public static boolean checkIfPowerOfTwoOrNot(int number) {
return number != 0 && ((number & (number - 1)) == 0);
}
-
}
diff --git a/Others/ReturnSubsequence.java b/Others/ReturnSubsequence.java
index bb1b413afd1d..89e945f8261e 100644
--- a/Others/ReturnSubsequence.java
+++ b/Others/ReturnSubsequence.java
@@ -13,6 +13,7 @@ public static void main(String[] args) {
for (int i = 0; i < subsequence.length; i++) {
System.out.println(subsequence[i]);
}
+ s.close();
}
/**
diff --git a/Others/RootPrecision.java b/Others/RootPrecision.java
index 388f1b2ec7b6..71690a4b2591 100644
--- a/Others/RootPrecision.java
+++ b/Others/RootPrecision.java
@@ -14,6 +14,8 @@ public static void main(String[] args) {
// P is precision value for eg - P is 3 in 2.564 and 5 in 3.80870.
int P = scn.nextInt();
System.out.println(squareRoot(N, P));
+
+ scn.close();
}
public static double squareRoot(int N, int P) {
diff --git a/Others/SJF.java b/Others/SJF.java
index e6b995f4846c..247f3da0989f 100644
--- a/Others/SJF.java
+++ b/Others/SJF.java
@@ -67,6 +67,7 @@ class Schedule {
processes.add(p);
burstAll += p.burstTime;
}
+ in.close();
}
diff --git a/Others/StackPostfixNotation.java b/Others/StackPostfixNotation.java
index 01e4c8a8eb1c..2857199d0401 100644
--- a/Others/StackPostfixNotation.java
+++ b/Others/StackPostfixNotation.java
@@ -7,6 +7,7 @@ public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String post = scanner.nextLine(); // Takes input with spaces in between eg. "1 21 +"
System.out.println(postfixEvaluate(post));
+ scanner.close();
}
// Evaluates the given postfix expression string and returns the result.
@@ -35,6 +36,7 @@ public static int postfixEvaluate(String exp) {
// "+", "-", "*", "/"
}
}
+ tokens.close();
return s.pop();
}
}
diff --git a/Others/TopKWords.java b/Others/TopKWords.java
index 840c3c2f7010..6cccfc27b95f 100644
--- a/Others/TopKWords.java
+++ b/Others/TopKWords.java
@@ -82,6 +82,7 @@ public static void main(String[] args) {
for (int i = 0; i < k; i++) {
System.out.println(list.get(list.size() - i - 1));
}
+ input.close();
}
}
diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java
index 2eca7fc744a0..7d35ed36d54f 100644
--- a/Others/TowerOfHanoi.java
+++ b/Others/TowerOfHanoi.java
@@ -22,5 +22,6 @@ public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfDiscs = scanner.nextInt(); //input of number of discs on pole 1
shift(numberOfDiscs, "Pole1", "Pole2", "Pole3"); //Shift function called
+ scanner.close();
}
}
diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java
index 06319f79df49..cec0ddce0065 100644
--- a/ciphers/Caesar.java
+++ b/ciphers/Caesar.java
@@ -126,6 +126,7 @@ public static void main(String[] args) {
case 'd':
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift));
}
+ input.close();
}
}
From d5ddc351d8bfa6f1a80bdc8f41b945b612ea8c08 Mon Sep 17 00:00:00 2001
From: Hassan
Date: Tue, 28 Jan 2020 19:35:16 +0200
Subject: [PATCH 0057/2014] Simple Substitution Cipher Algorithm added.
---
ciphers/SimpleSubstitutionCipher.java | 97 +++++++++++++++++++++++++++
1 file changed, 97 insertions(+)
create mode 100644 ciphers/SimpleSubstitutionCipher.java
diff --git a/ciphers/SimpleSubstitutionCipher.java b/ciphers/SimpleSubstitutionCipher.java
new file mode 100644
index 000000000000..983bc4f6d13c
--- /dev/null
+++ b/ciphers/SimpleSubstitutionCipher.java
@@ -0,0 +1,97 @@
+package ciphers;
+
+import java.util.*;
+
+/**
+ *
+ * The simple substitution cipher is a cipher that has been in use for many hundreds of years
+ * (an excellent history is given in Simon Singhs 'the Code Book').
+ * It basically consists of substituting every plaintext character for a different ciphertext character.
+ * It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted,
+ * it is completely jumbled.
+ *
+ * @author Hassan Elseoudy
+ */
+
+public class SimpleSubstitutionCipher {
+
+ /**
+ * Encrypt text by replacing each element with its opposite character.
+ *
+ * @param message
+ * @param cipherSmall
+ * @return Encrypted message
+ */
+ public static String encode(String message, String cipherSmall) {
+ String encoded = "";
+
+ // This map is used to encode
+ Map cipherMap = new HashMap();
+
+ char beginSmallLetter = 'a';
+ char beginCapitalLetter = 'A';
+
+ cipherSmall = cipherSmall.toLowerCase();
+ String cipherCapital = cipherSmall.toUpperCase();
+
+ // To handle Small and Capital letters
+ for(int i = 0; i < cipherSmall.length(); i++){
+ cipherMap.put(beginSmallLetter++,cipherSmall.charAt(i));
+ cipherMap.put(beginCapitalLetter++,cipherCapital.charAt(i));
+ }
+
+ for(int i = 0; i < message.length(); i++){
+ if(Character.isAlphabetic(message.charAt(i)))
+ encoded += cipherMap.get(message.charAt(i));
+ else
+ encoded += message.charAt(i);
+ }
+
+ return encoded;
+ }
+
+ /**
+ * Decrypt message by replacing each element with its opposite character in cipher.
+ *
+ * @param encryptedMessage
+ * @param cipherSmall
+ * @return message
+ */
+ public static String decode(String encryptedMessage, String cipherSmall) {
+ String decoded = "";
+
+
+ Map cipherMap = new HashMap();
+
+ char beginSmallLetter = 'a';
+ char beginCapitalLetter = 'A';
+
+ cipherSmall = cipherSmall.toLowerCase();
+ String cipherCapital = cipherSmall.toUpperCase();
+
+ for(int i = 0; i < cipherSmall.length(); i++){
+ cipherMap.put(cipherSmall.charAt(i),beginSmallLetter++);
+ cipherMap.put(cipherCapital.charAt(i),beginCapitalLetter++);
+ }
+
+ for(int i = 0; i < encryptedMessage.length(); i++){
+ if(Character.isAlphabetic(encryptedMessage.charAt(i)))
+ decoded += cipherMap.get(encryptedMessage.charAt(i));
+ else
+ decoded += encryptedMessage.charAt(i);
+ }
+
+ return decoded;
+ }
+
+ /**
+ *
+ * TODO remove main and make JUnit Testing
+ */
+ public static void main(String[] args) {
+ String a = encode("defend the east wall of the castle","phqgiumeaylnofdxjkrcvstzwb");
+ String b = decode(a,"phqgiumeaylnofdxjkrcvstzwb");
+ System.out.println(b);
+ }
+
+}
\ No newline at end of file
From e21d0efd6ae46bf744eb4d4164a4ca2c5e376d7d Mon Sep 17 00:00:00 2001
From: nikhil kala
Date: Wed, 29 Jan 2020 01:46:27 +0530
Subject: [PATCH 0058/2014] Update SimpleSubstitutionCipher.java
---
ciphers/SimpleSubstitutionCipher.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/ciphers/SimpleSubstitutionCipher.java b/ciphers/SimpleSubstitutionCipher.java
index 983bc4f6d13c..d9bae4f072c8 100644
--- a/ciphers/SimpleSubstitutionCipher.java
+++ b/ciphers/SimpleSubstitutionCipher.java
@@ -94,4 +94,4 @@ public static void main(String[] args) {
System.out.println(b);
}
-}
\ No newline at end of file
+}
From bf8845e8b59232389c96ba74acdd11397984221f Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Tue, 28 Jan 2020 20:17:13 +0000
Subject: [PATCH 0059/2014] updating DIRECTORY.md
---
DIRECTORY.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 50ae52c55844..46a9b06c04b1 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -5,6 +5,7 @@
* [Caesar](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Caesar.java)
* [ColumnarTranspositionCipher](https://github.com/TheAlgorithms/Java/blob/master/ciphers/ColumnarTranspositionCipher.java)
* [RSA](https://github.com/TheAlgorithms/Java/blob/master/ciphers/RSA.java)
+ * [SimpleSubstitutionCipher](https://github.com/TheAlgorithms/Java/blob/master/ciphers/SimpleSubstitutionCipher.java)
* [Vigenere](https://github.com/TheAlgorithms/Java/blob/master/ciphers/Vigenere.java)
## Conversions
From 5aa05fdf2c2004c75ed1fc5424e4c29554e4d418 Mon Sep 17 00:00:00 2001
From: nikhil kala
Date: Wed, 29 Jan 2020 01:50:50 +0530
Subject: [PATCH 0060/2014] Delete Dijkshtra.java
Duplicate and wrongly named.
---
Others/Dijkshtra.java | 85 -------------------------------------------
1 file changed, 85 deletions(-)
delete mode 100644 Others/Dijkshtra.java
diff --git a/Others/Dijkshtra.java b/Others/Dijkshtra.java
deleted file mode 100644
index d964d0596718..000000000000
--- a/Others/Dijkshtra.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package Others;
-
-import java.util.Arrays;
-import java.util.Scanner;
-import java.util.Stack;
-
-/**
- * @author Mayank K Jha
- */
-
-public class Dijkshtra {
-
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
-
- // n = Number of nodes or vertices
- int n = in.nextInt();
- // m = Number of Edges
- int m = in.nextInt();
-
- // Adjacency Matrix
- long[][] w = new long[n + 1][n + 1];
-
- // Initializing Matrix with Certain Maximum Value for path b/w any two vertices
- for (long[] row : w) {
- Arrays.fill(row, 1000000L);
- }
-
- /* From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
- For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l */
-
- // Taking Input as Edge Location b/w a pair of vertices
- for (int i = 0; i < m; i++) {
- int x = in.nextInt(), y = in.nextInt();
- long cmp = in.nextLong();
-
- // Comparing previous edge value with current value - Cycle Case
- if (w[x][y] > cmp) {
- w[x][y] = cmp;
- w[y][x] = cmp;
- }
- }
-
- // Implementing Dijkshtra's Algorithm
- Stack t = new Stack<>();
- int src = in.nextInt();
-
- for (int i = 1; i <= n; i++) {
- if (i != src) {
- t.push(i);
- }
- }
-
- Stack p = new Stack<>();
- p.push(src);
- w[src][src] = 0;
-
- while (!t.isEmpty()) {
- int min = 989997979;
- int loc = -1;
-
- for (int i = 0; i < t.size(); i++) {
- w[src][t.elementAt(i)] = Math.min(w[src][t.elementAt(i)], w[src][p.peek()] + w[p.peek()][t.elementAt(i)]);
- if (w[src][t.elementAt(i)] <= min) {
- min = (int) w[src][t.elementAt(i)];
- loc = i;
- }
- }
- p.push(t.elementAt(loc));
- t.removeElementAt(loc);
- }
-
- // Printing shortest path from the given source src
- for (int i = 1; i <= n; i++) {
- if (i != src && w[src][i] != 1000000L) {
- System.out.print(w[src][i] + " ");
- }
- // Printing -1 if there is no path b/w given pair of edges
- else if (i != src) {
- System.out.print("-1" + " ");
- }
- }
- in.close();
- }
-}
\ No newline at end of file
From 1f0f1a3cd9c604c5fad43bd16e708339e399b812 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Tue, 28 Jan 2020 20:21:07 +0000
Subject: [PATCH 0061/2014] updating DIRECTORY.md
---
DIRECTORY.md | 1 -
1 file changed, 1 deletion(-)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 46a9b06c04b1..a8052bc883b7 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -142,7 +142,6 @@
* [CountWords](https://github.com/TheAlgorithms/Java/blob/master/Others/CountWords.java)
* [CRC32](https://github.com/TheAlgorithms/Java/blob/master/Others/CRC32.java)
* [CRCAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/Others/CRCAlgorithm.java)
- * [Dijkshtra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkshtra.java)
* [Dijkstra](https://github.com/TheAlgorithms/Java/blob/master/Others/Dijkstra.java)
* [EulersFunction](https://github.com/TheAlgorithms/Java/blob/master/Others/EulersFunction.java)
* [FibToN](https://github.com/TheAlgorithms/Java/blob/master/Others/FibToN.java)
From 0bf21d6e2e86a7d6dd44a70461b91a86c1ab9add Mon Sep 17 00:00:00 2001
From: Hakan Arslan
Date: Sat, 29 Feb 2020 15:39:13 +0300
Subject: [PATCH 0062/2014] bytesToHex function is changed beecause of required
library is depracated on OpenJdk 11
---
ciphers/AESEncryption.java | 19 +++++++++++++++----
1 file changed, 15 insertions(+), 4 deletions(-)
diff --git a/ciphers/AESEncryption.java b/ciphers/AESEncryption.java
index 871bd52e2d14..884109f9bdb7 100644
--- a/ciphers/AESEncryption.java
+++ b/ciphers/AESEncryption.java
@@ -8,7 +8,6 @@
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
-import javax.xml.bind.DatatypeConverter;
/**
* This example program shows how AES encryption and decryption can be done in
@@ -19,6 +18,8 @@
*/
public class AESEncryption {
+
+ private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
/**
* 1. Generate a plain text for encryption 2. Get a secret key (printed in
* hexadecimal form). In actual use this must by encrypted and kept safe. The
@@ -103,12 +104,22 @@ public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws
/**
* Convert a binary byte array into readable hex form
- *
+ * Old library is deprecated on OpenJdk 11 and
+ * this is faster regarding other solution is using StringBuilder
+ * Credit
+ * {@link
+ * https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java/9855338#9855338}
* @param hash
* (in binary)
* @return hexHash
*/
- private static String bytesToHex(byte[] hash) {
- return DatatypeConverter.printHexBinary(hash);
+ public static String bytesToHex(byte[] bytes) {
+ char[] hexChars = new char[bytes.length * 2];
+ for (int j = 0; j < bytes.length; j++) {
+ int v = bytes[j] & 0xFF;
+ hexChars[j * 2] = HEX_ARRAY[v >>> 4];
+ hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
+ }
+ return new String(hexChars);
}
}
From e5ad1f2ef0287426e4bef4fbc2aad6776d02bad5 Mon Sep 17 00:00:00 2001
From: Wendell Lucas <49886455+wendelllsc@users.noreply.github.com>
Date: Tue, 17 Mar 2020 23:05:27 -0300
Subject: [PATCH 0063/2014] Using Try/catch and recursion
Adding try/catch and recursion to optimize the code
---
Maths/Factorial.java | 19 +++++++++++--------
1 file changed, 11 insertions(+), 8 deletions(-)
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 3feb43356129..61c82398bd12 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -16,13 +16,16 @@ public static void main(String[] args) {
* @return the factorial of {@code n}
*/
public static long factorial(int n) {
- if (n < 0) {
- throw new ArithmeticException("n < 0"); //Dont work with less than 0
- }
- long fac = 1;
- for (int i = 1; i <= n; ++i) {
- fac *= i;
- }
- return fac; //Return factorial
+ // Using recursion
+ try {
+ if (n == 0) {
+ return 1; // if n = 0, return factorial of n;
+ }else {
+ return n*factorial(n-1); // While N is greater than 0, call the function again, passing n-1 (Principle of factoring);
+ }
+ }catch (ArithmeticException e) {
+ System.out.println("Dont work with less than 0");
+ }
+ return n;
}
}
From 0eef7f4737b68ea4dd9daa4976eecd107a62c380 Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 21:09:57 +0100
Subject: [PATCH 0064/2014] Update DecimalToBinary.java
Close ressource leak Scanner input
---
Conversions/DecimalToBinary.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java
index cd84486ae812..ccd8c643fa9a 100644
--- a/Conversions/DecimalToBinary.java
+++ b/Conversions/DecimalToBinary.java
@@ -35,6 +35,7 @@ public static void conventionalConversion() {
n /= 2;
} //converting decimal to binary
System.out.println("\tBinary number: " + b);
+ input.close();
}
/**
From 7a52313e218146eceb72a7c0fd86c03cb36aa7b2 Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 21:36:35 +0100
Subject: [PATCH 0065/2014] Update Cycles.java
closing Scanner in
---
DataStructures/Graphs/Cycles.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/DataStructures/Graphs/Cycles.java b/DataStructures/Graphs/Cycles.java
index b6fd8b4c58c5..5e085ab7cd68 100644
--- a/DataStructures/Graphs/Cycles.java
+++ b/DataStructures/Graphs/Cycles.java
@@ -34,6 +34,7 @@ public Cycle() {
end = in.nextInt();
adjacencyMatrix[start][end] = 1;
}
+ in.close();
}
From c480377c7e4e6bd4372c576cde0ec52a9c46bc55 Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 21:37:31 +0100
Subject: [PATCH 0066/2014] Update PrimMST.java
removing unused import java.lang.*
---
DataStructures/Graphs/PrimMST.java | 2 --
1 file changed, 2 deletions(-)
diff --git a/DataStructures/Graphs/PrimMST.java b/DataStructures/Graphs/PrimMST.java
index 32487feddefb..474893775870 100644
--- a/DataStructures/Graphs/PrimMST.java
+++ b/DataStructures/Graphs/PrimMST.java
@@ -1,7 +1,5 @@
package DataStructures.Graphs;
-import java.lang.*;
-
/**
* A Java program for Prim's Minimum Spanning Tree (MST) algorithm.
* adjacency matrix representation of the graph
From ecfbadc7892ffb9f6b66bf1d8460ff8480663613 Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 21:41:58 +0100
Subject: [PATCH 0067/2014] Update Cycles.java
removing unused member variable finalCycles
---
DataStructures/Graphs/Cycles.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/DataStructures/Graphs/Cycles.java b/DataStructures/Graphs/Cycles.java
index 5e085ab7cd68..0b0ae22d7e8d 100644
--- a/DataStructures/Graphs/Cycles.java
+++ b/DataStructures/Graphs/Cycles.java
@@ -10,7 +10,7 @@ class Cycle {
private int[][] adjacencyMatrix;
private boolean[] visited;
ArrayList> cycles = new ArrayList>();
- private boolean[] finalCycles;
+
public Cycle() {
Scanner in = new Scanner(System.in);
From dd73b46a25d1182b59ed5e29e85386723156532b Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 21:56:35 +0100
Subject: [PATCH 0068/2014] Update Main.java
fixing bug
Program is causing a NoSuchElementException
---
DataStructures/HashMap/Hashing/Main.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/DataStructures/HashMap/Hashing/Main.java b/DataStructures/HashMap/Hashing/Main.java
index 340f0760b2e5..9611b6025135 100644
--- a/DataStructures/HashMap/Hashing/Main.java
+++ b/DataStructures/HashMap/Hashing/Main.java
@@ -8,6 +8,7 @@ public static void main(String[] args) {
int choice, key;
HashMap h = new HashMap(7);
+ Scanner In = new Scanner(System.in);
while (true) {
System.out.println("Enter your Choice :");
@@ -15,9 +16,7 @@ public static void main(String[] args) {
System.out.println("2. Delete Key");
System.out.println("3. Print Table");
System.out.println("4. Exit");
-
- Scanner In = new Scanner(System.in);
-
+
choice = In.nextInt();
switch (choice) {
@@ -39,10 +38,11 @@ public static void main(String[] args) {
break;
}
case 4: {
+ In.close();
return;
}
}
- In.close();
+
}
}
}
\ No newline at end of file
From c184e1cecbe4f7971ed3095053926aca2c4957d2 Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Fri, 20 Mar 2020 22:17:01 +0100
Subject: [PATCH 0069/2014] Update RedBlackBST.java
closing Scanner scan
---
DataStructures/Trees/RedBlackBST.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/DataStructures/Trees/RedBlackBST.java b/DataStructures/Trees/RedBlackBST.java
index 197c96321975..45501fd290e3 100644
--- a/DataStructures/Trees/RedBlackBST.java
+++ b/DataStructures/Trees/RedBlackBST.java
@@ -330,5 +330,6 @@ public void deleteDemo() {
printTree(root);
System.out.println("Pre order");
printTreepre(root);
+ scan.close();
}
}
\ No newline at end of file
From 31d57c0471a6934058f902d1f500fad00441fc0c Mon Sep 17 00:00:00 2001
From: Alexandra Englert
Date: Thu, 26 Mar 2020 16:52:53 +0100
Subject: [PATCH 0070/2014] Update RomanToInteger.java
declaring serialVersionUID
---
Conversions/RomanToInteger.java | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/Conversions/RomanToInteger.java b/Conversions/RomanToInteger.java
index 4563ce4a4a72..0672a1464bd3 100644
--- a/Conversions/RomanToInteger.java
+++ b/Conversions/RomanToInteger.java
@@ -4,7 +4,13 @@
public class RomanToInteger {
- private static Map map = new HashMap() {{
+ private static Map map = new HashMap() {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 87605733047260530L;
+
+ {
put('I', 1);
put('V', 5);
put('X', 10);
From 7ef06c0b26431a9f5da8872d30112ee9b6f0e102 Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:01:30 +0200
Subject: [PATCH 0071/2014] added type parameter
---
DataStructures/Graphs/ConnectedComponent.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/DataStructures/Graphs/ConnectedComponent.java b/DataStructures/Graphs/ConnectedComponent.java
index 7029a8d811f2..4582bfd4406f 100644
--- a/DataStructures/Graphs/ConnectedComponent.java
+++ b/DataStructures/Graphs/ConnectedComponent.java
@@ -108,7 +108,7 @@ public ArrayList depthFirstSearch(Node n, ArrayList visited) {
public class ConnectedComponent {
public static void main(String[] args) {
- Graph graphChars = new Graph();
+ Graph graphChars = new Graph<>();
// Graph 1
graphChars.addEdge('a', 'b');
@@ -123,7 +123,7 @@ public static void main(String[] args) {
graphChars.addEdge('w', 'w');
- Graph graphInts = new Graph();
+ Graph graphInts = new Graph<>();
// Graph 2
graphInts.addEdge(1, 2);
From 3f34fb6b9818065d42b2a8ec2b888a3be24eb4d1 Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:32:07 +0200
Subject: [PATCH 0072/2014] remove deprecated use of Character
---
DataStructures/Buffers/CircularBuffer.java | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/DataStructures/Buffers/CircularBuffer.java b/DataStructures/Buffers/CircularBuffer.java
index ae047b81568f..a723f693089c 100644
--- a/DataStructures/Buffers/CircularBuffer.java
+++ b/DataStructures/Buffers/CircularBuffer.java
@@ -26,12 +26,15 @@ private int getTrueIndex(int i) {
return i % _buffer_size;
}
+
public Character readOutChar() {
Character result = null;
+
//if we have data to read
if (_readable_data.get() > 0) {
- result = new Character(_buffer[getTrueIndex(_read_index)]);
+
+ result = Character.valueOf(_buffer[getTrueIndex(_read_index)]);
_readable_data.decrementAndGet();
_read_index++;
}
From 0c334a9487e8bf7e44cab8955f85c03335786f67 Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:32:48 +0200
Subject: [PATCH 0073/2014] remove unused variable
---
DataStructures/HashMap/Hashing/LinkedList.java | 1 -
1 file changed, 1 deletion(-)
diff --git a/DataStructures/HashMap/Hashing/LinkedList.java b/DataStructures/HashMap/Hashing/LinkedList.java
index 8c4ec0f732da..4953551f7040 100644
--- a/DataStructures/HashMap/Hashing/LinkedList.java
+++ b/DataStructures/HashMap/Hashing/LinkedList.java
@@ -12,7 +12,6 @@ public LinkedList() {
public void insert(int data) {
- Node temp = Head;
Node newnode = new Node(data);
size++;
From fecfe9d705c9618e5cfa8d86c1e65ec6ac930e30 Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:36:03 +0200
Subject: [PATCH 0074/2014] remove unused method
---
DataStructures/Lists/CursorLinkedList.java | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/DataStructures/Lists/CursorLinkedList.java b/DataStructures/Lists/CursorLinkedList.java
index 6e1caefc620b..b12794fd1067 100644
--- a/DataStructures/Lists/CursorLinkedList.java
+++ b/DataStructures/Lists/CursorLinkedList.java
@@ -4,6 +4,7 @@
public class CursorLinkedList {
+
private static class Node {
T element;
@@ -13,13 +14,8 @@ private static class Node {
this.element = element;
this.next = next;
}
-
- boolean isEmpty() {
- return element == null;
- }
}
-
private final int os;
private int head;
private final Node[] cursorSpace;
@@ -27,6 +23,7 @@ boolean isEmpty() {
private final static int CURSOR_SPACE_SIZE = 100;
+
{
// init at loading time
cursorSpace = new Node[CURSOR_SPACE_SIZE];
From 3629e32c0818c8e1dd6db5ecda4560973481de73 Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:36:48 +0200
Subject: [PATCH 0075/2014] remove unused variable
---
Misc/heap_sort.java | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/Misc/heap_sort.java b/Misc/heap_sort.java
index 5222be4093d1..cf44b2b5a5df 100644
--- a/Misc/heap_sort.java
+++ b/Misc/heap_sort.java
@@ -57,8 +57,7 @@ static void printArray(int[] arr) {
// Driver program
public static void main(String args[]) {
int arr[] = {12, 11, 13, 5, 6, 7};
- int n = arr.length;
-
+
heap_sort ob = new heap_sort();
ob.sort(arr);
From c560e72201e5c8b8961c94bb822fad7444e0066b Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:37:17 +0200
Subject: [PATCH 0076/2014] remove unnecessary SuppressWarning
---
Sorts/MergeSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Sorts/MergeSort.java b/Sorts/MergeSort.java
index 2b15a9ce09b4..f15e7af4578f 100644
--- a/Sorts/MergeSort.java
+++ b/Sorts/MergeSort.java
@@ -20,7 +20,7 @@ class MergeSort implements SortAlgorithm {
* @return sorted array
*/
@Override
- @SuppressWarnings("unchecked")
+
public > T[] sort(T[] unsorted) {
doSort(unsorted, 0, unsorted.length - 1);
return unsorted;
From b351c33ad381d95a658b2153c6f2b594170237ce Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:48:57 +0200
Subject: [PATCH 0077/2014] close Reader
---
DataStructures/Lists/SinglyLinkedList.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/DataStructures/Lists/SinglyLinkedList.java b/DataStructures/Lists/SinglyLinkedList.java
index 1196851a3d9e..5fda2f5f87bd 100644
--- a/DataStructures/Lists/SinglyLinkedList.java
+++ b/DataStructures/Lists/SinglyLinkedList.java
@@ -120,9 +120,9 @@ public void deleteNth(int position) {
cur = cur.next;
}
- Node destroy = cur.next;
+ //Node destroy = cur.next;
cur.next = cur.next.next;
- destroy = null; // clear to let GC do its work
+ //destroy = null; // clear to let GC do its work
size--;
}
From 5ce4cc2696ae53a7c913d74a5c3272169038ea2c Mon Sep 17 00:00:00 2001
From: EAlexa
Date: Tue, 7 Apr 2020 16:50:22 +0200
Subject: [PATCH 0078/2014] close Reader
---
MinimizingLateness/MinimizingLateness.java | 1 +
1 file changed, 1 insertion(+)
diff --git a/MinimizingLateness/MinimizingLateness.java b/MinimizingLateness/MinimizingLateness.java
index 1438f6f3dbcc..46e6fb4e06d7 100644
--- a/MinimizingLateness/MinimizingLateness.java
+++ b/MinimizingLateness/MinimizingLateness.java
@@ -26,6 +26,7 @@ public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("MinimizingLateness/lateness_data.txt"));
String ch = in.readLine();
if (ch == null || ch.isEmpty()) {
+ in.close();
return;
}
int indexCount = Integer.parseInt(ch);
From e7ddedb37c5dc7b807f8e0f95b73091b6f016ed9 Mon Sep 17 00:00:00 2001
From: Wesllhey Holanda
Date: Fri, 10 Apr 2020 14:43:32 -0300
Subject: [PATCH 0079/2014] dynamic array data structure
---
DataStructures/DynamicArray/DynamicArray.java | 158 ++++++++++++++++++
1 file changed, 158 insertions(+)
create mode 100644 DataStructures/DynamicArray/DynamicArray.java
diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java
new file mode 100644
index 000000000000..0a6a0723e2a1
--- /dev/null
+++ b/DataStructures/DynamicArray/DynamicArray.java
@@ -0,0 +1,158 @@
+package DataStructures.DynamicArray;
+
+import java.util.Arrays;
+import java.util.ConcurrentModificationException;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
+public class DynamicArray implements Iterable {
+
+ private int capacity = 10;
+
+ private int size = 0;
+
+ private Object[] elements;
+
+ public DynamicArray(final int capacity) {
+ this.capacity = capacity;
+ this.elements = new Object[this.capacity];
+ }
+
+ public DynamicArray() {
+ this.elements = new Object[this.capacity];
+ }
+
+ public int newCapacity() {
+ this.capacity <<= 1;
+
+ return this.capacity;
+ }
+
+ public void add(final E element) {
+ if (this.size == this.elements.length)
+ this.elements = Arrays.copyOf(this.elements, newCapacity());
+
+ this.elements[this.size] = element;
+ size++;
+ }
+
+ public void put(final int index, E element) {
+ Objects.checkIndex(index, this.size);
+
+ this.elements[index] = element;
+ }
+
+ public E get(final int index) {
+ return getElement(index);
+ }
+
+ public E remove(final int index) {
+ final E oldElement = getElement(index);
+ fastRemove(this.elements, index);
+
+ return oldElement;
+ }
+
+ public int size() {
+ return this.size;
+ }
+
+ public boolean isEmpty() {
+ return this.size == 0;
+ }
+
+ public Stream stream() {
+ return StreamSupport.stream(spliterator(), false);
+ }
+
+ private void fastRemove(final Object[] elements, final int index) {
+ final int newSize = this.size - 1;
+
+ if (newSize > index)
+ System.arraycopy(elements, index + 1, elements, index, newSize - index);
+
+ elements[this.size = newSize] = null;
+ }
+
+ private E getElement(final int index) {
+ Objects.checkIndex(index, this.size);
+ return (E) this.elements[index];
+ }
+
+ @Override
+ public String toString() {
+ return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
+ }
+
+ @Override
+ public Iterator iterator() {
+ return new DynamicArrayIterator();
+ }
+
+ private class DynamicArrayIterator implements Iterator {
+
+ private int cursor;
+
+ @Override
+ public boolean hasNext() {
+ return this.cursor != size;
+ }
+
+ @Override
+ public E next() {
+ if (this.cursor > DynamicArray.this.size) throw new NoSuchElementException();
+
+ if (this.cursor > DynamicArray.this.elements.length) throw new ConcurrentModificationException();
+
+ final E element = DynamicArray.this.getElement(this.cursor);
+
+ this.cursor++;
+
+ return element;
+ }
+
+ @Override
+ public void remove() {
+ if (this.cursor < 0) throw new IllegalStateException();
+
+ DynamicArray.this.remove(this.cursor);
+
+ this.cursor--;
+ }
+
+ @Override
+ public void forEachRemaining(Consumer super E> action) {
+ Objects.requireNonNull(action);
+
+ for (int i = 0; i < DynamicArray.this.size; i++) {
+ action.accept(DynamicArray.this.getElement(i));
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ DynamicArray names = new DynamicArray<>();
+ names.add("Peubes");
+ names.add("Marley");
+
+ for (String name : names) {
+ System.out.println(name);
+ }
+
+ names.stream().forEach(System.out::println);
+
+ System.out.println(names);
+
+ System.out.println(names.size());
+
+ names.remove(0);
+
+ for (String name : names) {
+ System.out.println(name);
+ }
+ }
+}
From 85c3c775e78b3e2b0e2e1bf503cd9c6c70756b74 Mon Sep 17 00:00:00 2001
From: markaster <61535772+markaster@users.noreply.github.com>
Date: Sat, 11 Apr 2020 13:36:57 +0800
Subject: [PATCH 0080/2014] Update LICENSE
---
LICENSE | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/LICENSE b/LICENSE
index a20869d96300..3b7951527ab3 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2019 The Algorithms
+Copyright (c) 2020 The Algorithms
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
From 338fced4d50598d1eac1dca6dad51475d9ea620a Mon Sep 17 00:00:00 2001
From: LittleFoot <2059416370@qq.com>
Date: Thu, 16 Apr 2020 21:31:01 +0800
Subject: [PATCH 0081/2014] change Sorts/ShellSort.java
---
Sorts/ShellSort.java | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java
index 199f31a8c1ea..67070b1b6a00 100644
--- a/Sorts/ShellSort.java
+++ b/Sorts/ShellSort.java
@@ -22,10 +22,11 @@ public > T[] sort(T[] array) {
for (; gap > 0; gap /= 3) {
for (int i = gap; i < length; i++) {
int j;
- for (j = i; j >= gap && less(array[j], array[j - gap]); j -= gap) {
+ T temp = array[i];
+ for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) {
array[j] = array[j - gap];
}
- array[j] = array[i];
+ array[j] = temp;
}
}
return array;
From 3ef9fe71409fca25b782320dce90f89cef88d874 Mon Sep 17 00:00:00 2001
From: littleFoot1 <52392154+littleFoot1@users.noreply.github.com>
Date: Thu, 16 Apr 2020 21:33:22 +0800
Subject: [PATCH 0082/2014] Update ShellSort.java
---
Sorts/ShellSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Sorts/ShellSort.java b/Sorts/ShellSort.java
index 67070b1b6a00..b29119a0c3af 100644
--- a/Sorts/ShellSort.java
+++ b/Sorts/ShellSort.java
@@ -22,7 +22,7 @@ public > T[] sort(T[] array) {
for (; gap > 0; gap /= 3) {
for (int i = gap; i < length; i++) {
int j;
- T temp = array[i];
+ T temp = array[i];
for (j = i; j >= gap && less(temp, array[j - gap]); j -= gap) {
array[j] = array[j - gap];
}
From fc8e36c6e319c87cefa270c16e76c64416344588 Mon Sep 17 00:00:00 2001
From: Moetez Skouri
Date: Wed, 29 Apr 2020 19:07:09 +0100
Subject: [PATCH 0083/2014] added removeDuplicates function
---
DataStructures/Lists/DoublyLinkedList.java | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java
index 677487e1d2b0..e1b0041dda39 100644
--- a/DataStructures/Lists/DoublyLinkedList.java
+++ b/DataStructures/Lists/DoublyLinkedList.java
@@ -160,6 +160,19 @@ else if (current == null)
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
}
}
+
+ public static void removeDuplicates(DoublyLinkedList l ) {
+ Link linkOne = l.head ;
+ while(linkOne.next != null) { // list is present
+ Link linkTwo = linkOne.next; // second link for comparison
+ while(linkTwo.next!= null) {
+ if(linkOne.value == linkTwo.value) // if there are duplicates values then
+ l.delete(linkTwo.value); // delete the link
+ linkTwo = linkTwo.next ; // go to next link
+ }
+ linkOne = linkOne.next; // go to link link to iterate the whole list again
+ }
+ }
/**
* Returns true if list is empty
From 21bd91afabcfa259912ffb56c09926846f2cef86 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Sun, 3 May 2020 19:38:41 +0000
Subject: [PATCH 0084/2014] updating DIRECTORY.md
---
DIRECTORY.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index a8052bc883b7..ddcd59ba7f7d 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -32,6 +32,8 @@
* [Bag](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Bags/Bag.java)
* Buffers
* [CircularBuffer](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Buffers/CircularBuffer.java)
+ * DynamicArray
+ * [DynamicArray](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/DynamicArray/DynamicArray.java)
* Graphs
* [BellmanFord](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/BellmanFord.java)
* [ConnectedComponent](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Graphs/ConnectedComponent.java)
From b12aa3d3b881085273a6a738b29a437e2a634170 Mon Sep 17 00:00:00 2001
From: Alaa El Bouhdidi
Date: Mon, 4 May 2020 09:46:31 +0200
Subject: [PATCH 0085/2014] Add a new sort algorithm, Sort/BitonicSort
---
Sorts/BitonicSort.java | 88 ++++++++++++++++++++++++++++++++++++++++++
1 file changed, 88 insertions(+)
create mode 100644 Sorts/BitonicSort.java
diff --git a/Sorts/BitonicSort.java b/Sorts/BitonicSort.java
new file mode 100644
index 000000000000..195ae1712d48
--- /dev/null
+++ b/Sorts/BitonicSort.java
@@ -0,0 +1,88 @@
+package Sorts;
+
+/* Java program for Bitonic Sort. Note that this program
+works only when size of input is a power of 2. */
+public class BitonicSort
+{
+ /* The parameter dir indicates the sorting direction,
+ ASCENDING or DESCENDING; if (a[i] > a[j]) agrees
+ with the direction, then a[i] and a[j] are
+ interchanged. */
+ void compAndSwap(int a[], int i, int j, int dir)
+ {
+ if ( (a[i] > a[j] && dir == 1) ||
+ (a[i] < a[j] && dir == 0))
+ {
+ // Swapping elements
+ int temp = a[i];
+ a[i] = a[j];
+ a[j] = temp;
+ }
+ }
+
+ /* It recursively sorts a bitonic sequence in ascending
+ order, if dir = 1, and in descending order otherwise
+ (means dir=0). The sequence to be sorted starts at
+ index position low, the parameter cnt is the number
+ of elements to be sorted.*/
+ void bitonicMerge(int a[], int low, int cnt, int dir)
+ {
+ if (cnt>1)
+ {
+ int k = cnt/2;
+ for (int i=low; i1)
+ {
+ int k = cnt/2;
+
+ // sort in ascending order since dir here is 1
+ bitonicSort(a, low, k, 1);
+
+ // sort in descending order since dir here is 0
+ bitonicSort(a,low+k, k, 0);
+
+ // Will merge wole sequence in ascending order
+ // since dir=1.
+ bitonicMerge(a, low, cnt, dir);
+ }
+ }
+
+ /*Caller of bitonicSort for sorting the entire array
+ of length N in ASCENDING order */
+ void sort(int a[], int N, int up)
+ {
+ bitonicSort(a, 0, N, up);
+ }
+
+ /* A utility function to print array of size n */
+ static void printArray(int arr[])
+ {
+ int n = arr.length;
+ for (int i=0; i
Date: Mon, 4 May 2020 13:23:33 +0000
Subject: [PATCH 0086/2014] updating DIRECTORY.md
---
DIRECTORY.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index ddcd59ba7f7d..eef10ec31b4b 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -185,6 +185,7 @@
* [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/Searches/TernarySearch.java)
## Sorts
+ * [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BitonicSort.java)
* [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java)
* [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java)
* [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java)
From d41fc152571f963cf8ca9e01345242c311e0bc72 Mon Sep 17 00:00:00 2001
From: VTolas <64403418+vtolas@users.noreply.github.com>
Date: Mon, 4 May 2020 20:42:16 +0200
Subject: [PATCH 0087/2014] Create PrimeFactorization.java
---
Maths/PrimeFactorization.java | 35 +++++++++++++++++++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 Maths/PrimeFactorization.java
diff --git a/Maths/PrimeFactorization.java b/Maths/PrimeFactorization.java
new file mode 100644
index 000000000000..9f647d3190c1
--- /dev/null
+++ b/Maths/PrimeFactorization.java
@@ -0,0 +1,35 @@
+package Maths;
+
+import java.lang.Math;
+import java.util.Scanner;
+
+public class algorithm {
+ public static void main(String[] args){
+ System.out.println("## all prime factors ##");
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter a number: ");
+ int n = scanner.nextInt();
+ System.out.print(("printing factors of " + n + " : "));
+ pfactors(n);
+ }
+ public static void pfactors(int n){
+
+ while (n%2==0)
+ {
+ System.out.print(2 + " ");
+ n /= 2;
+ }
+
+ for (int i=3; i<= Math.sqrt(n); i+=2)
+ {
+ while (n%i == 0)
+ {
+ System.out.print(i + " ");
+ n /= i;
+ }
+ }
+
+ if(n > 2)
+ System.out.print(n);
+ }
+}
From e59fc81075caa871e6d58fa752f1acdc7bdc5bb1 Mon Sep 17 00:00:00 2001
From: ben
Date: Tue, 5 May 2020 00:13:08 +0200
Subject: [PATCH 0088/2014] Finish both AmicableNumbers and VampireNumbers
---
Maths/VampireNumber.java | 94 ++++++++++++++++++++++++++++++++++++++++
1 file changed, 94 insertions(+)
create mode 100644 Maths/VampireNumber.java
diff --git a/Maths/VampireNumber.java b/Maths/VampireNumber.java
new file mode 100644
index 000000000000..c95189591634
--- /dev/null
+++ b/Maths/VampireNumber.java
@@ -0,0 +1,94 @@
+package Maths;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ n number theory, a vampire number (or true vampire number) is a composite natural number with an even number of digits,
+ that can be factored into two natural numbers each with half as many digits as the original number
+ and not both with trailing zeroes, where the two factors contain precisely
+ all the digits of the original number, in any order, counting multiplicity.
+ The first vampire number is 1260 = 21 × 60.
+ * *
+ *
+ * * link: https://en.wikipedia.org/wiki/Vampire_number
+ * *
+ *
+ *
+ */
+
+
+
+
+
+
+
+public class VampireNumber {
+
+ public static void main(String[] args) {
+
+ test(10,1000);
+ }
+
+ static void test(int startValue, int stopValue) {
+ int countofRes = 1;
+ StringBuilder res = new StringBuilder();
+
+
+ for (int i = startValue; i <= stopValue; i++) {
+ for (int j = i; j <= stopValue; j++) {
+ // System.out.println(i+ " "+ j);
+ if (isVampireNumber(i, j,true)) {
+ countofRes++;
+ res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i*j + ")" + "\n");
+ }
+ }
+ }
+ System.out.println(res);
+ }
+
+
+
+
+ static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers ) {
+
+ // this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for example
+ // 126 = 6 x 21
+ if (noPseudoVamireNumbers) {
+ if (a * 10 <= b || b * 10 <= a) {
+ return false;
+ }
+ }
+
+ String mulDigits = splitIntoDigits(a*b,0);
+ String faktorDigits = splitIntoDigits(a,b);
+
+ return mulDigits.equals(faktorDigits);
+ }
+
+
+
+// methode to Split the numbers to Digits
+ static String splitIntoDigits(int num, int num2) {
+
+ StringBuilder res = new StringBuilder();
+
+ ArrayList digits = new ArrayList<>();
+ while (num > 0) {
+ digits.add(num%10);
+ num /= 10;
+ }
+ while (num2 > 0) {
+ digits.add(num2%10);
+ num2/= 10;
+ }
+ Collections.sort(digits);
+ for (int i : digits) {
+ res.append(i);
+ }
+
+
+ return res.toString();
+ }
+}
\ No newline at end of file
From 082f104978d1224feb75384d690f20b521299934 Mon Sep 17 00:00:00 2001
From: ben
Date: Tue, 5 May 2020 00:15:17 +0200
Subject: [PATCH 0089/2014] Finish both AmicableNumbers and VampireNumbers
---
Maths/AmicableNumber.java | 87 +++++++++++++++++++++++++++++++++++++++
1 file changed, 87 insertions(+)
create mode 100644 Maths/AmicableNumber.java
diff --git a/Maths/AmicableNumber.java b/Maths/AmicableNumber.java
new file mode 100644
index 000000000000..1d81a393a6ff
--- /dev/null
+++ b/Maths/AmicableNumber.java
@@ -0,0 +1,87 @@
+package Maths;
+
+/**
+ * Amicable numbers are two different numbers so related
+ * that the sum of the proper divisors of each is equal to the other number.
+ * (A proper divisor of a number is a positive factor of that number other than the number itself.
+ * For example, the proper divisors of 6 are 1, 2, and 3.)
+ * A pair of amicable numbers constitutes an aliquot sequence of period 2.
+ * It is unknown if there are infinitely many pairs of amicable numbers.
+ * *
+ *
+ * * link: https://en.wikipedia.org/wiki/Amicable_numbers
+ * *
+ *
+ * Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284
+ * 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it 220
+ */
+
+public class AmicableNumber {
+
+ public static void main(String[] args) {
+
+ AmicableNumber.findAllInRange(1,3000);
+ /* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210)
+ 3: = ( 2620,2924) So it worked */
+
+ }
+
+ /**
+ * @param startValue
+ * @param stopValue
+ * @return
+ */
+ static void findAllInRange(int startValue, int stopValue) {
+
+ /* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation
+ * also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
+ * */
+ StringBuilder res = new StringBuilder();
+ int countofRes = 0;
+
+ for (int i = startValue; i < stopValue; i++) {
+ for (int j = i + 1; j <= stopValue; j++) {
+ if (isAmicableNumber(i, j)) {
+ countofRes++;
+ res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
+ }
+ }
+ }
+ res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n ");
+ System.out.println(res.toString());
+ }
+
+ /**
+ * Check if {@code numberOne and numberTwo } are AmicableNumbers or not
+ *
+ * @param numberOne numberTwo
+ * @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false
+ */
+ static boolean isAmicableNumber(int numberOne, int numberTwo) {
+
+ return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo && numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
+ }
+
+ /**
+ * calculated in recursive calls the Sum of all the Dividers beside it self
+ *
+ * @param number div = the next to test dividely by using the modulo operator
+ * @return sum of all the dividers
+ */
+ static int recursiveCalcOfDividerSum(int number, int div) {
+
+ if (div == 1) {
+ return 0;
+ } else if (number % --div == 0) {
+ return recursiveCalcOfDividerSum(number, div) + div;
+ } else {
+ return recursiveCalcOfDividerSum(number, div);
+ }
+ }
+
+
+
+
+
+
+}
From 59488a106392ba35abbf72fdf37a24a325ec9679 Mon Sep 17 00:00:00 2001
From: Moetez Skouri
Date: Tue, 5 May 2020 00:39:49 +0100
Subject: [PATCH 0090/2014] implement search with search helper
---
DataStructures/Trees/AVLTree.java | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/DataStructures/Trees/AVLTree.java b/DataStructures/Trees/AVLTree.java
index b496be6961fa..2e7119604cf5 100644
--- a/DataStructures/Trees/AVLTree.java
+++ b/DataStructures/Trees/AVLTree.java
@@ -202,6 +202,29 @@ private void reheight(Node node) {
}
}
+ public boolean search(int key) {
+ Node result = searchHelper(this.root,key);
+ if(result != null)
+ return true ;
+
+ return false ;
+ }
+
+ private Node searchHelper(Node root, int key)
+ {
+ //root is null or key is present at root
+ if (root==null || root.key==key)
+ return root;
+
+ // key is greater than root's key
+ if (root.key > key)
+ return searchHelper(root.left, key); // call the function on the node's left child
+
+ // key is less than root's key then
+ //call the function on the node's right child as it is greater
+ return searchHelper(root.right, key);
+ }
+
public static void main(String[] args) {
AVLTree tree = new AVLTree();
From 3b245025d33e40804e97e5baed48d9ac6b3d4f02 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Thu, 7 May 2020 07:04:08 +0000
Subject: [PATCH 0091/2014] updating DIRECTORY.md
---
DIRECTORY.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index eef10ec31b4b..2ff7d2a2fb5a 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -126,6 +126,7 @@
* [Pow](https://github.com/TheAlgorithms/Java/blob/master/Maths/Pow.java)
* [PowRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/PowRecursion.java)
* [PrimeCheck](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeCheck.java)
+ * [PrimeFactorization](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeFactorization.java)
## MinimizingLateness
* [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/MinimizingLateness/MinimizingLateness.java)
From 1c062e2c7a4377cb3145ae8983f98ef5eb30aa7a Mon Sep 17 00:00:00 2001
From: Vikrant Khedkar
Date: Thu, 7 May 2020 19:30:58 +0530
Subject: [PATCH 0092/2014] added scanner in factorail program
---
Maths/Factorial.java | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 3feb43356129..4f0262aec85d 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -1,9 +1,12 @@
package Maths;
+import java.util.*; //for importing scanner
-//change around 'n' for different factorial results
public class Factorial {
public static void main(String[] args) {
- int n = 5;
+ int n = 1;
+Scanner sc= new Scanner(System.in);
+System.out.println("Enter Number");
+n=sc.nextInt();
System.out.println(n + "! = " + factorial(n));
}
From f44f2c176b1a2bf902c7bd74bfcdb1d8960f3104 Mon Sep 17 00:00:00 2001
From: Vikrant Khedkar
Date: Thu, 7 May 2020 20:28:31 +0530
Subject: [PATCH 0093/2014] added comment in front of main method
---
Maths/Factorial.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 4f0262aec85d..07704161f358 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -2,7 +2,7 @@
import java.util.*; //for importing scanner
public class Factorial {
- public static void main(String[] args) {
+ public static void main(String[] args) { //main method
int n = 1;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Number");
From f6d67253e3d272b35076d844c5c93fa86aa30cf0 Mon Sep 17 00:00:00 2001
From: Vikrant khedkar
Date: Fri, 8 May 2020 10:38:05 +0530
Subject: [PATCH 0094/2014] Added indentation in the "main" function statement
block
---
Maths/Factorial.java | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/Maths/Factorial.java b/Maths/Factorial.java
index 07704161f358..2ade4132a4ff 100644
--- a/Maths/Factorial.java
+++ b/Maths/Factorial.java
@@ -3,11 +3,11 @@
public class Factorial {
public static void main(String[] args) { //main method
- int n = 1;
-Scanner sc= new Scanner(System.in);
-System.out.println("Enter Number");
-n=sc.nextInt();
- System.out.println(n + "! = " + factorial(n));
+ int n = 1;
+ Scanner sc= new Scanner(System.in);
+ System.out.println("Enter Number");
+ n=sc.nextInt();
+ System.out.println(n + "! = " + factorial(n));
}
//Factorial = n! = n1 * (n-1) * (n-2)*...1
From 4fef5da90928e5819663daccea28d46e93a9bf99 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Mon, 11 May 2020 03:20:49 +0000
Subject: [PATCH 0095/2014] updating DIRECTORY.md
---
DIRECTORY.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 2ff7d2a2fb5a..e77e30e84b82 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -109,6 +109,7 @@
* [AbsoluteMax](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMax.java)
* [AbsoluteMin](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteMin.java)
* [AbsoluteValue](https://github.com/TheAlgorithms/Java/blob/master/Maths/AbsoluteValue.java)
+ * [AmicableNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/AmicableNumber.java)
* [Factorial](https://github.com/TheAlgorithms/Java/blob/master/Maths/Factorial.java)
* [FactorialRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/FactorialRecursion.java)
* [FibonacciNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/FibonacciNumber.java)
@@ -127,6 +128,7 @@
* [PowRecursion](https://github.com/TheAlgorithms/Java/blob/master/Maths/PowRecursion.java)
* [PrimeCheck](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeCheck.java)
* [PrimeFactorization](https://github.com/TheAlgorithms/Java/blob/master/Maths/PrimeFactorization.java)
+ * [VampireNumber](https://github.com/TheAlgorithms/Java/blob/master/Maths/VampireNumber.java)
## MinimizingLateness
* [MinimizingLateness](https://github.com/TheAlgorithms/Java/blob/master/MinimizingLateness/MinimizingLateness.java)
From 979fa2327db414990d25833b1151648e13da57d3 Mon Sep 17 00:00:00 2001
From: Stepfen Shawn
Date: Tue, 12 May 2020 16:43:04 -0500
Subject: [PATCH 0096/2014] Update AVLTree.java
---
DataStructures/Trees/AVLTree.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/DataStructures/Trees/AVLTree.java b/DataStructures/Trees/AVLTree.java
index 2e7119604cf5..fb9e2cb34df9 100644
--- a/DataStructures/Trees/AVLTree.java
+++ b/DataStructures/Trees/AVLTree.java
@@ -202,7 +202,7 @@ private void reheight(Node node) {
}
}
- public boolean search(int key) {
+ public boolean search(int key) {
Node result = searchHelper(this.root,key);
if(result != null)
return true ;
From bcf808a238399f320771bd63a4dcf38dfaca4abe Mon Sep 17 00:00:00 2001
From: Stepfen Shawn
Date: Tue, 12 May 2020 17:01:38 -0500
Subject: [PATCH 0097/2014] Update VampireNumber.java
---
Maths/VampireNumber.java | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/Maths/VampireNumber.java b/Maths/VampireNumber.java
index c95189591634..056ce681a4ae 100644
--- a/Maths/VampireNumber.java
+++ b/Maths/VampireNumber.java
@@ -31,7 +31,7 @@ public static void main(String[] args) {
test(10,1000);
}
- static void test(int startValue, int stopValue) {
+ static void test(int startValue, int stopValue) {
int countofRes = 1;
StringBuilder res = new StringBuilder();
@@ -51,7 +51,7 @@ static void test(int startValue, int stopValue) {
- static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers ) {
+ static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers ) {
// this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for example
// 126 = 6 x 21
@@ -70,7 +70,7 @@ static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers ) {
// methode to Split the numbers to Digits
- static String splitIntoDigits(int num, int num2) {
+ static String splitIntoDigits(int num, int num2) {
StringBuilder res = new StringBuilder();
@@ -91,4 +91,4 @@ static String splitIntoDigits(int num, int num2) {
return res.toString();
}
-}
\ No newline at end of file
+}
From 63e5ce4c8f7657a8d9713bd1d7f94485b07635f4 Mon Sep 17 00:00:00 2001
From: Maria Lungeanu
Date: Thu, 14 May 2020 19:36:06 +0300
Subject: [PATCH 0098/2014] Fixed Error:(6, 8) java: class algorithm is public,
should be declared in a file named algorithm.java. Inside file
PrimeFactorization, the name of public class was wrong.
---
Maths/PrimeFactorization.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Maths/PrimeFactorization.java b/Maths/PrimeFactorization.java
index 9f647d3190c1..a488bf8e990c 100644
--- a/Maths/PrimeFactorization.java
+++ b/Maths/PrimeFactorization.java
@@ -3,7 +3,7 @@
import java.lang.Math;
import java.util.Scanner;
-public class algorithm {
+public class PrimeFactorization {
public static void main(String[] args){
System.out.println("## all prime factors ##");
Scanner scanner = new Scanner(System.in);
From 40620aea1b728c9a8fd1f931ec503660dd06e8c9 Mon Sep 17 00:00:00 2001
From: joshiujjawal22
Date: Mon, 18 May 2020 23:24:57 +0530
Subject: [PATCH 0099/2014] To find sum of triplets according to given value
---
Others/3 sum.java | 48 +++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 48 insertions(+)
create mode 100644 Others/3 sum.java
diff --git a/Others/3 sum.java b/Others/3 sum.java
new file mode 100644
index 000000000000..3c008ff78360
--- /dev/null
+++ b/Others/3 sum.java
@@ -0,0 +1,48 @@
+package Others;
+
+import java.util.Scanner;
+import java.util.Arrays;
+
+/**
+ * To find triplet equals to given sum in complexity O(n*log(n))
+ *
+ *
+ * Array must be sorted
+ *
+ * @author Ujjawal Joshi
+ * @date 2020.05.18
+ */
+
+
+class threesum{
+ public static void main(String args[])
+ {
+ Scanner sc =new Scanner(System.in);
+ int n=sc.nextInt(); //Length of an array
+
+ int a[]=new int[n];
+
+ for(int i=0;i
Date: Mon, 18 May 2020 23:35:06 +0530
Subject: [PATCH 0100/2014] Rotation of an array without using extra space
---
...on of array without using extra space.java | 54 +++++++++++++++++++
1 file changed, 54 insertions(+)
create mode 100644 Others/Rotation of array without using extra space.java
diff --git a/Others/Rotation of array without using extra space.java b/Others/Rotation of array without using extra space.java
new file mode 100644
index 000000000000..c25dbaefc8c9
--- /dev/null
+++ b/Others/Rotation of array without using extra space.java
@@ -0,0 +1,54 @@
+package Others;
+
+import java.util.*;
+
+/**
+ * Rotation of array without using extra space
+ *
+ *
+ * @author Ujjawal Joshi
+ * @date 2020.05.18
+ */
+
+class main{
+ public static void main(String[] args)
+ {
+ Scanner sc=new Scanner(System.in);
+ int n=sc.nextInt();
+ int a[][]=new int[n][n];
+
+ for(int i=0;i
Date: Tue, 19 May 2020 23:20:48 +0800
Subject: [PATCH 0101/2014] Handles all corner cases
---
Searches/Perfect BinarySearch | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 Searches/Perfect BinarySearch
diff --git a/Searches/Perfect BinarySearch b/Searches/Perfect BinarySearch
new file mode 100644
index 000000000000..28cdcb5be543
--- /dev/null
+++ b/Searches/Perfect BinarySearch
@@ -0,0 +1,21 @@
+ static int binarySearch(int[] arr, int target) {
+ int low = 0 ;
+ int high = arr.length - 1 ;
+
+ while(low <= high) {
+ int mid =(low + high) / 2;
+
+ if(arr[mid] == target) {
+ return mid;
+ }
+ else if(arr[mid] > target) {
+ high = mid - 1;
+ }
+ else {
+ low = mid + 1;
+ }
+
+ }
+ return -1;
+ }
+
From 6818098a32c14b1c6f8d6bf08f58f6c22d30ecc5 Mon Sep 17 00:00:00 2001
From: CodingCookieRookie
<38324769+CodingCookieRookie@users.noreply.github.com>
Date: Tue, 19 May 2020 23:53:52 +0800
Subject: [PATCH 0102/2014] Update SelectionSort.java
-Used compareTo
-Used a local swap method
---
Sorts/SelectionSort.java | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
diff --git a/Sorts/SelectionSort.java b/Sorts/SelectionSort.java
index 9b5b0cbcdd67..e6b7c8833f43 100644
--- a/Sorts/SelectionSort.java
+++ b/Sorts/SelectionSort.java
@@ -8,6 +8,17 @@
public class SelectionSort implements SortAlgorithm {
+ /**
+ * This method swaps the two elements in the array
+ * @param arr, i, j The array for the swap and
+ the indexes of the to-swap elements
+ */
+ public void swap(T[] arr, int i, int j) {
+ T temp = arr[i];
+ arr[i] = arr[j];
+ arr[j] = temp;
+ }
+
/**
* This method implements the Generic Selection Sort
*
@@ -22,14 +33,14 @@ public > T[] sort(T[] arr) {
int min = i;
for (int j = i + 1; j < n; j++) {
- if (SortUtils.less(arr[j], arr[min])) {
+ if (arr[min].compareTo(arr[j]) < 0) {
min = j;
}
}
// Swapping if index of min is changed
if (min != i) {
- SortUtils.swap(arr, i, min);
+ swap(arr, i, min);
}
}
From 72258d4ffeca8f435322d1da5ac6572c273a7e4a Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Thu, 21 May 2020 03:16:36 +0530
Subject: [PATCH 0103/2014] Create GenericHeap
---
DataStructures/Heaps/GenericHeap | 69 ++++++++++++++++++++++++++++++++
1 file changed, 69 insertions(+)
create mode 100644 DataStructures/Heaps/GenericHeap
diff --git a/DataStructures/Heaps/GenericHeap b/DataStructures/Heaps/GenericHeap
new file mode 100644
index 000000000000..1a17022a9022
--- /dev/null
+++ b/DataStructures/Heaps/GenericHeap
@@ -0,0 +1,69 @@
+import java.util.*;
+
+public class GenericHeap >{
+ ArrayList data=new ArrayList<>();
+ HashMap map=new HashMap<>();
+ public void add(T item) {
+ this.data.add(item);
+ map.put(item,this.data.size()-1);//
+ upHeapify(this.data.size()-1);
+ }
+ private void upHeapify(int ci) {
+ int pi=(ci-1)/2;
+ if(isLarger(this.data.get(ci),this.data.get(pi))>0) {
+ swap(pi,ci);
+ upHeapify(pi);
+ }
+ }
+ public void display() {
+ System.out.println(this.data);
+ }
+ public int size() {
+ return this.data.size();
+ }
+ public boolean isEmpty() {
+ return this.size()==0;
+ }
+ public T remove() {
+ this.swap(0,this.size()-1);
+ T rv=this.data.remove(this.size()-1);
+ downHeapify(0);
+ map.remove(rv);
+ return rv;
+ }
+ private void downHeapify(int pi) {
+ int lci=2*pi+1;
+ int rci=2*pi+2;
+ int mini=pi;
+ if(lci0) {
+ mini=lci;
+ }
+ if(rci0) {
+ mini=rci;
+ }
+ if(mini!=pi) {
+ this.swap(pi,mini);
+ downHeapify(mini);
+ }
+ }
+ public T get() {
+ return this.data.get(0);
+ }
+ //t has higher property then return +ve
+ private int isLarger(T t,T o) {
+ return t.compareTo(o);
+ }
+ private void swap(int i,int j) {
+ T ith=this.data.get(i);
+ T jth=this.data.get(j);
+ this.data.set(i,jth);
+ this.data.set(j,ith);
+ map.put(ith,j);
+ map.put(jth,i);
+ }
+ public void updatePriority(T item) {
+ int index=map.get(item);
+ //because we enter lesser value then old vale
+ upHeapify(index);
+ }
+}
From 63b9e137caf745da13b765d38cdeb834b84df407 Mon Sep 17 00:00:00 2001
From: Vineet Rathor <35703327+THE-VR7@users.noreply.github.com>
Date: Fri, 22 May 2020 02:28:42 +0530
Subject: [PATCH 0104/2014] Create BucketSort.java
---
Sorts/BucketSort.java | 68 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 68 insertions(+)
create mode 100644 Sorts/BucketSort.java
diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java
new file mode 100644
index 000000000000..58127927ee58
--- /dev/null
+++ b/Sorts/BucketSort.java
@@ -0,0 +1,68 @@
+
+import java.util.Random;
+
+public class Bucket_Sort
+{
+ static int[] sort(int[] sequence, int maxValue)
+ {
+ // Bucket Sort
+ int[] Bucket = new int[maxValue + 1];
+ int[] sorted_sequence = new int[sequence.length];
+
+ for (int i = 0; i < sequence.length; i++)
+ Bucket[sequence[i]]++;
+
+ int outPos = 0;
+ for (int i = 0; i < Bucket.length; i++)
+ for (int j = 0; j < Bucket[i]; j++)
+ sorted_sequence[outPos++] = i;
+
+ return sorted_sequence;
+ }
+
+ static void printSequence(int[] sorted_sequence)
+ {
+ for (int i = 0; i < sorted_sequence.length; i++)
+ System.out.print(sorted_sequence[i] + " ");
+ }
+
+ static int maxValue(int[] sequence)
+ {
+ int maxValue = 0;
+ for (int i = 0; i < sequence.length; i++)
+ if (sequence[i] > maxValue)
+ maxValue = sequence[i];
+ return maxValue;
+ }
+
+ public static void main(String args[])
+ {
+ System.out.println("Sorting of randomly generated numbers using BUCKET SORT");
+ Random random = new Random();
+ int N = 20;
+ int[] sequence = new int[N];
+
+ for (int i = 0; i < N; i++)
+ sequence[i] = Math.abs(random.nextInt(100));
+
+ int maxValue = maxValue(sequence);
+
+ System.out.println("\nOriginal Sequence: ");
+ printSequence(sequence);
+
+ System.out.println("\nSorted Sequence: ");
+ printSequence(sort(sequence, maxValue));
+ }
+}
+
+#Output:
+
+$ javac Bucket_Sort.java
+$ java Bucket_Sort
+
+Sorting of randomly generated numbers using BUCKET SORT
+
+Original Sequence:
+95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66
+Sorted Sequence:
+8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95
From 36e30a011114e336d0e5bf6ea8d9e7129d5b3bda Mon Sep 17 00:00:00 2001
From: Prateek Kumar Oraon
Date: Fri, 22 May 2020 03:53:05 +0530
Subject: [PATCH 0105/2014] String Matching using Finite Automata added in
Others/StringMatchFiniteAutomata.java
---
Others/StringMatchFiniteAutomata.java | 91 +++++++++++++++++++++++++++
1 file changed, 91 insertions(+)
create mode 100644 Others/StringMatchFiniteAutomata.java
diff --git a/Others/StringMatchFiniteAutomata.java b/Others/StringMatchFiniteAutomata.java
new file mode 100644
index 000000000000..34eb60b70454
--- /dev/null
+++ b/Others/StringMatchFiniteAutomata.java
@@ -0,0 +1,91 @@
+/**
+ * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
+ */
+import java.util.Scanner;
+
+//An implementaion of string matching using finite automata
+public class StringMatchFiniteAutomata{
+
+ public static final int CHARS = 256;
+ public static int[][] FA;
+ public static Scanner scanner = null;
+
+ public static void main(String[] args){
+
+ scanner = new Scanner(System.in);
+ System.out.println("Enter String");
+ String text = scanner.nextLine();
+ System.out.println("Enter pattern");
+ String pat = scanner.nextLine();
+
+ searchPat(text, pat);
+
+ scanner.close();
+
+ }
+
+ public static void searchPat(String text, String pat){
+
+ int m = pat.length();
+ int n = text.length();
+
+ FA = new int[m+1][CHARS];
+
+ computeFA(pat, m ,FA);
+
+ int state = 0;
+ for(int i=0;i0; ns--){
+
+ if(pat.charAt(ns-1) == x){
+
+ for(int i=0; i
Date: Fri, 22 May 2020 03:58:59 +0530
Subject: [PATCH 0106/2014] Added Rabin-Karp string matching algorithm in
Others/RabinKarp.java
---
Others/RabinKarp.java | 84 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 84 insertions(+)
create mode 100644 Others/RabinKarp.java
diff --git a/Others/RabinKarp.java b/Others/RabinKarp.java
new file mode 100644
index 000000000000..ba1e6869db0a
--- /dev/null
+++ b/Others/RabinKarp.java
@@ -0,0 +1,84 @@
+/**
+ * @author Prateek Kumar Oraon (https://github.com/prateekKrOraon)
+ */
+import java.util.Scanner;
+import java.lang.Math;
+
+//An implementation of Rabin-Karp string matching algorithm
+//Program will simply end if there is no match
+public class RabinKarp {
+
+ public static Scanner scanner = null;
+ public final static int d = 256;
+
+ public static void main(String[] args){
+
+ scanner = new Scanner(System.in);
+ System.out.println("Enter String");
+ String text = scanner.nextLine();
+ System.out.println("Enter pattern");
+ String pattern = scanner.nextLine();
+
+ int q = 101;
+ searchPat(text,pattern,q);
+
+ }
+
+ private static void searchPat(String text, String pattern, int q) {
+
+ int m = pattern.length();
+ int n = text.length();
+ int t = 0;
+ int p = 0;
+ int h = 1;
+ int j = 0;
+ int i = 0;
+
+ h = (int)Math.pow(d,m-1)%q;
+
+ for(i =0 ; i< m; i++){
+ //hash value is calculated for each character and then added with the hash value of the next character for pattern
+ // as well as the text for length equal to the length of pattern
+ p = (d*p + pattern.charAt(i))%q;
+ t = (d*t + text.charAt(i))%q;
+ }
+
+ for(i=0; i<=n-m;i++){
+
+ //if the calculated hash value of the pattern and text matches then
+ //all the characters of the pattern is matched with the text of length equal to length of the pattern
+ //if all matches then pattern exist in string
+ //if not then the hash value of the first character of the text is subtracted and hash value of the next character after the end
+ //of the evaluated characters is added
+ if(p==t){
+
+ //if hash value matches then the individual characters are matched
+ for(j=0;j
Date: Fri, 22 May 2020 16:23:41 +0530
Subject: [PATCH 0107/2014] Created Graph Algos
it contains Dijkstra, Prims, dft, bft, dfs, bfs and many more.
---
DataStructures/Graphs/GraphAlgos | 437 +++++++++++++++++++++++++++++++
1 file changed, 437 insertions(+)
create mode 100644 DataStructures/Graphs/GraphAlgos
diff --git a/DataStructures/Graphs/GraphAlgos b/DataStructures/Graphs/GraphAlgos
new file mode 100644
index 000000000000..780a73e45540
--- /dev/null
+++ b/DataStructures/Graphs/GraphAlgos
@@ -0,0 +1,437 @@
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import Heaps.GenericHeap;
+public class Graph {
+ private class vertex{
+ HashMap nbrs=new HashMap<>();
+ }
+ HashMap vertcs;
+ public Graph(){
+ vertcs=new HashMap<>();
+ }
+ public int numVertex() {
+ return this.vertcs.size();
+ }
+ public boolean containsVertex(String vname) {
+ return this.vertcs.containsKey(vname);
+ }
+ public void addVertex(String vname) {
+
+ vertex vtx=new vertex();
+ this.vertcs.put(vname,vtx);
+ }
+ public void removeVertex(String vname) {
+ vertex vtx=this.vertcs.get(vname);
+ ArrayList keys=new ArrayList<>(vtx.nbrs.keySet());
+ for(String key:keys) {
+ vertex nbrvtx=this.vertcs.get(key);
+ nbrvtx.nbrs.remove(vname);
+ }
+ this.vertcs.remove(vname);
+ }
+
+ public int numEdge() {
+ int count=0;
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ vertex vtx=this.vertcs.get(key);
+ count+=vtx.nbrs.size();
+ }
+ return count/2;
+ }
+ public boolean containsEdge(String vname1,String vname2) {
+ vertex vtx1=this.vertcs.get(vname1);
+ vertex vtx2=this.vertcs.get(vname2);
+ if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2))
+ return false;
+ return true;
+ }
+ public void addEdge(String vname1,String vname2,int cost) {
+ vertex vtx1=this.vertcs.get(vname1);
+ vertex vtx2=this.vertcs.get(vname2);
+ if(vtx1==null||vtx2==null||vtx1.nbrs.containsKey(vname2))
+ return;
+ vtx1.nbrs.put(vname2,cost);
+ vtx2.nbrs.put(vname1,cost);
+ }
+ public void removeEdge(String vname1,String vname2) {
+ vertex vtx1=this.vertcs.get(vname1);
+ vertex vtx2=this.vertcs.get(vname2);
+ if(vtx1==null||vtx2==null||!vtx1.nbrs.containsKey(vname2))
+ return;
+ vtx1.nbrs.remove(vname2);
+ vtx2.nbrs.remove(vname1);
+ }
+
+ public void display() {
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ vertex vtx=this.vertcs.get(key);
+ System.out.println(key+" := "+vtx.nbrs);
+ }
+ }
+
+ public boolean hasPath(String source ,String dest,HashMap processed) {
+ processed.put(source, true);
+ if(containsEdge(source,dest)) {
+ return true;
+ }
+ vertex vtx=this.vertcs.get(source);
+ ArrayList keys=new ArrayList<>(vtx.nbrs.keySet());
+ for(String key:keys) {
+ if(!processed.containsKey(key) && hasPath(key,dest,processed))
+ return true;
+ }
+ return false;
+
+ }
+ private class pair{
+ String vname;
+ String psf;
+ }
+ public boolean bfs(String source,String dest) { // breadth first search
+ HashMap processed=new HashMap<>();
+
+ LinkedList queue=new LinkedList<>();
+ pair sp=new pair();
+ sp.vname=source;
+ sp.psf=source;
+ queue.addLast(sp);
+
+ while(!queue.isEmpty()) {
+ pair rp=queue.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+
+ if(containsEdge(rp.vname,dest)) {
+ System.out.println(rp.psf+dest);
+ return true;
+ }
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ queue.addLast(np);
+ }
+ }
+ }
+ return false;
+ }
+ public boolean dfs(String source,String dest) { //deapth first search
+ LinkedList stack=new LinkedList<>();
+ HashMap processed=new HashMap<>();
+ pair sp=new pair();
+ sp.vname=source;
+ sp.psf=source;
+ stack.addFirst(sp);
+ while(!stack.isEmpty()) {
+ pair rp=stack.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+ if(containsEdge(rp.vname,dest)) {
+ System.out.println(rp.psf+dest);
+ return true;
+ }
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ stack.addFirst(np);
+ }
+ }
+
+ }
+ return false;
+ }
+ public void bft() { //breadth first traversal
+ HashMap processed=new HashMap<>();
+ LinkedList queue=new LinkedList<>();
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ if(processed.containsKey(key))
+ continue;
+ pair sp=new pair();
+ sp.vname=key;
+ sp.psf=key;
+ queue.addLast(sp);
+
+ while(!queue.isEmpty()) {
+ pair rp=queue.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+
+ System.out.println(rp.vname+" via "+rp.psf);
+
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ queue.addLast(np);
+ }
+ }
+ }
+ }
+ }
+ public void dft() { //deapt first traversal
+ HashMap processed=new HashMap<>();
+ LinkedList stack=new LinkedList<>();
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ pair sp=new pair();
+ sp.vname=key;
+ sp.psf=key;
+ stack.addFirst(sp);
+
+ while(!stack.isEmpty()) {
+ pair rp=stack.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+
+ System.out.println(rp.vname+" via "+rp.psf);
+
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ stack.addFirst(np);
+ }
+ }
+ }
+ }
+ }
+
+
+ public boolean isCyclic() {
+ HashMap processed=new HashMap<>();
+ LinkedList queue=new LinkedList<>();
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ if(processed.containsKey(key))
+ continue;
+ pair sp=new pair();
+ sp.vname=key;
+ sp.psf=key;
+ queue.addLast(sp);
+
+ while(!queue.isEmpty()) {
+ pair rp=queue.removeFirst();
+ if(processed.containsKey(rp.vname))
+ return true;
+ processed.put(rp.vname,true);
+
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ queue.addLast(np);
+ }
+ }
+ }
+ }
+ return false;
+ }
+ public boolean isConnected() {
+ int flag=0;
+ HashMap processed=new HashMap<>();
+ LinkedList queue=new LinkedList<>();
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ if(processed.containsKey(key))
+ continue;
+ flag++;
+ pair sp=new pair();
+ sp.vname=key;
+ sp.psf=key;
+ queue.addLast(sp);
+
+ while(!queue.isEmpty()) {
+ pair rp=queue.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ queue.addLast(np);
+ }
+ }
+ }
+ }
+ if(flag>=2)
+ return false;
+ else
+ return true;
+ }
+ public boolean isTree() {
+ return !isCyclic()&&isConnected();
+ }
+ public ArrayList> getConnectedComp() {
+ ArrayList> ans=new ArrayList<>();
+ HashMap processed=new HashMap<>();
+ LinkedList queue=new LinkedList<>();
+ ArrayList keys=new ArrayList<>(this.vertcs.keySet());
+ for(String key:keys) {
+ if(processed.containsKey(key))
+ continue;
+ ArrayList subans=new ArrayList<>();
+ pair sp=new pair();
+ sp.vname=key;
+ sp.psf=key;
+ queue.addLast(sp);
+
+ while(!queue.isEmpty()) {
+ pair rp=queue.removeFirst();
+ if(processed.containsKey(rp.vname))
+ continue;
+ processed.put(rp.vname,true);
+
+ subans.add(rp.vname);
+
+ vertex vtx=this.vertcs.get(rp.vname);
+ ArrayList nbrs=new ArrayList<>(vtx.nbrs.keySet());
+ for(String nbr:nbrs) {
+ if(!processed.containsKey(nbr)) {
+ pair np=new pair();
+ np.vname=nbr;
+ np.psf=rp.psf+nbr;
+ queue.addLast(np);
+ }
+ }
+ }
+ ans.add(subans);
+ }
+ return ans;
+ }
+ private class PrimsPair implements Comparable{
+ String vname;
+ String acqvname;
+ int cost;
+ public int compareTo(PrimsPair o) {
+ return o.cost-this.cost;
+ }
+
+ }
+ public Graph prims() {
+ HashMap map=new HashMap<>();
+ GenericHeap heap=new GenericHeap<>();
+ Graph mst=new Graph();
+ for(String vrtx:this.vertcs.keySet()) {
+ PrimsPair np=new PrimsPair();
+ np.acqvname=null;
+ np.vname=vrtx;
+ np.cost=Integer.MAX_VALUE;
+ heap.add(np);
+ map.put(vrtx, np);
+ }
+ while(!heap.isEmpty()) {
+ PrimsPair rp=heap.remove();
+ map.remove(rp.vname);
+
+ if(rp.acqvname==null) {
+ mst.addVertex(rp.vname);
+ }else {
+ mst.addVertex(rp.vname);
+ mst.addEdge(rp.vname, rp.acqvname, rp.cost);
+ }
+
+ for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) {
+ if(map.containsKey(nbr)) {
+ //old cost that is from diff path stored in map
+ int oc=map.get(nbr).cost;
+ // cost that present vname need cost to go to nbr
+ int nc=this.vertcs.get(rp.vname).nbrs.get(nbr);
+ if(nc{
+ String vname;
+ String psf;
+ int cost;
+ public int compareTo(DijktsraPair o) {
+ return o.cost-this.cost;
+ }
+
+ }
+ public HashMap Dijktsra(String source) {
+ HashMap map=new HashMap<>();
+ GenericHeap heap=new GenericHeap<>();
+ HashMap ans =new HashMap<>();
+ for(String vrtx:this.vertcs.keySet()) {
+ DijktsraPair np=new DijktsraPair();
+ np.psf="";
+ np.vname=vrtx;
+ np.cost=Integer.MAX_VALUE;
+ if(vrtx==source) {
+ np.cost=0;
+ np.psf=source;
+ }
+ heap.add(np);
+ map.put(vrtx, np);
+ }
+ while(!heap.isEmpty()) {
+ DijktsraPair rp=heap.remove();
+ map.remove(rp.vname);
+
+ ans.put(rp.vname,rp.cost);
+
+ for(String nbr:this.vertcs.get(rp.vname).nbrs.keySet()) {
+ if(map.containsKey(nbr)) {
+ //old cost that is from diff path stored in map
+ int oc=map.get(nbr).cost;
+ // cost that present vname need cost to go to nbr
+ int nc=rp.cost+this.vertcs.get(rp.vname).nbrs.get(nbr);
+ if(nc
Date: Sat, 23 May 2020 05:30:43 +0530
Subject: [PATCH 0108/2014] Create SinglyLinkedList
---
DataStructures/Lists/SinglyLinkedList | 101 ++++++++++++++++++++++++++
1 file changed, 101 insertions(+)
create mode 100644 DataStructures/Lists/SinglyLinkedList
diff --git a/DataStructures/Lists/SinglyLinkedList b/DataStructures/Lists/SinglyLinkedList
new file mode 100644
index 000000000000..0b51813037f4
--- /dev/null
+++ b/DataStructures/Lists/SinglyLinkedList
@@ -0,0 +1,101 @@
+package LinkedList;
+import java.util.*;
+import java.lang.*;
+import java.io.*;
+class LinkedList {
+ private class Node{
+ int data;
+ Node next;
+
+ Node(int data) {
+ this.data = data;
+ this.next = null;
+ }
+ }
+ public Node head = null;
+ public Node tail = null;
+ private int size=0;
+
+ public void addLast(int data) {
+ Node newNode = new Node(data);
+
+ if(this.head == null) {
+ this.head = newNode;
+ this.tail = newNode;
+ this.size++;
+ }
+ else {
+ this.tail.next = newNode;
+ this.tail = newNode;
+ this.size++;
+ }
+ }
+
+
+ public void display() {
+ Node current = this.head;
+ if(this.head == null) {
+ return;
+ }
+ while(current != null) {
+ System.out.print(current.data + " ");
+ current = current.next;
+ }
+ System.out.println();
+ }
+
+ public void formLL2(LinkedList LL1) {
+ Node current=LL1.head;
+ while(current.next!=null&¤t.next.next!=null) {
+ int sum=current.data+current.next.next.data;
+ this.addLast(sum);
+ current=current.next.next;
+ }
+ }
+ public void formLL3(LinkedList LL1) {
+ Node current=LL1.head.next;
+ while(current.next!=null&¤t.next.next!=null) {
+ int sum=current.data+current.next.next.data;
+ this.addLast(sum);
+ current=current.next.next;
+ }
+ }
+ public Node mid() {
+ Node slow=this.head;
+ Node fast=this.head;
+ while(fast.next!=null && fast.next.next!=null) {
+ slow=slow.next;
+ fast=fast.next.next;
+ }
+ return slow;
+ }
+ public Node midValue() {
+ int sum=this.head.data+this.tail.data;
+ Node mid=new Node(sum);
+ return mid;
+ }
+ public void formRes(LinkedList LL1,LinkedList LL2,LinkedList LL3,Node MID) {
+ Node LL1mid=LL1.mid();
+ Node currentLL1=LL1.head;
+ Node currentLL2=LL2.head;
+ Node currentLL3=LL3.head;
+ while(currentLL1!=null) {
+ this.addLast(currentLL1.data);
+
+ if(currentLL2!=null) {
+ this.addLast(currentLL2.data);
+ currentLL2=currentLL2.next;
+ }else if(currentLL1.equals(LL1mid)) {
+ this.addLast(MID.data);
+ }
+ else if(currentLL2==null&¤tLL3!=null) {
+ this.addLast(currentLL3.data);
+ currentLL3=currentLL3.next;
+ }
+ currentLL1=currentLL1.next;
+ }
+ }
+ public void Size() {
+ System.out.println(this.size);
+ }
+ }
From 4842a4ca61d4721aa48af740e483569d3c304a07 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Sat, 23 May 2020 05:32:30 +0530
Subject: [PATCH 0109/2014] Update and rename SinglyLinkedList to ListAddnFun
---
DataStructures/Lists/{SinglyLinkedList => ListAddnFun} | 1 -
1 file changed, 1 deletion(-)
rename DataStructures/Lists/{SinglyLinkedList => ListAddnFun} (99%)
diff --git a/DataStructures/Lists/SinglyLinkedList b/DataStructures/Lists/ListAddnFun
similarity index 99%
rename from DataStructures/Lists/SinglyLinkedList
rename to DataStructures/Lists/ListAddnFun
index 0b51813037f4..47553e184358 100644
--- a/DataStructures/Lists/SinglyLinkedList
+++ b/DataStructures/Lists/ListAddnFun
@@ -1,4 +1,3 @@
-package LinkedList;
import java.util.*;
import java.lang.*;
import java.io.*;
From ef2be071b09617df3f4354920d99d17dc9561feb Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Sat, 23 May 2020 05:33:40 +0530
Subject: [PATCH 0110/2014] Create AVLSimple
---
DataStructures/Trees/AVLSimple | 106 +++++++++++++++++++++++++++++++++
1 file changed, 106 insertions(+)
create mode 100644 DataStructures/Trees/AVLSimple
diff --git a/DataStructures/Trees/AVLSimple b/DataStructures/Trees/AVLSimple
new file mode 100644
index 000000000000..1f2c2bd6aba2
--- /dev/null
+++ b/DataStructures/Trees/AVLSimple
@@ -0,0 +1,106 @@
+public class AVLTree {
+ private class Node{
+ int data;
+ int height;
+ Node left;
+ Node right;
+ Node(int data){
+ this.data=data;
+ this.height=1;
+ }
+
+ }
+ private Node root;
+ public void insert(int data) {
+ this.root=insert(this.root,data);
+ }
+ private Node insert(Node node,int item) {
+ if(node==null) {
+ Node add=new Node(item);
+ return add;
+ }
+ if(node.data>item) {
+ node.left=insert(node.left,item);
+ }
+ if(node.data- 1&&itemnode.right.data)
+ return leftRotate(node);
+ //RL case
+ if(bf<-1&&item1&&item>node.left.data) {
+ node.left=leftRotate(node.left);
+ return rightRotate(node);
+ }
+
+ return node;
+ }
+ public void display() {
+ this.display(this.root);
+ System.out.println(this.root.height);
+ }
+ private void display (Node node) {
+ String str="";
+ if(node.left!=null)
+ str+=node.left.data+"=>";
+ else
+ str+="END=>";
+ str+=node.data+"";
+ if(node.right!=null)
+ str+="<="+node.right.data;
+ else
+ str+="<=END";
+ System.out.println(str);
+ if(node.left!=null)
+ display(node.left);
+ if(node.right!=null)
+ display(node.right);
+ }
+ private int height(Node node) {
+ if(node==null) {
+ return 0;
+ }
+ return node.height;
+
+ }
+ private int bf(Node node) {
+ if(node==null)
+ return 0;
+ return height(node.left)-height(node.right);
+ }
+
+ private Node rightRotate(Node c) {
+ Node b=c.left;
+ Node T3=b.right;
+
+ b.right=c;
+ c.left=T3;
+ c.height=Math.max(height(c.left),height(c.right))+1;
+ b.height=Math.max(height(b.left),height(b.right))+1;
+ return b;
+
+ }
+ private Node leftRotate(Node c) {
+ Node b=c.right;
+ Node T3=b.left;
+
+ b.left=c;
+ c.right=T3;
+ c.height=Math.max(height(c.left),height(c.right))+1;
+ b.height=Math.max(height(b.left),height(b.right))+1;
+ return b;
+
+ }
+
+}
From 07aee8ba8129af1310b9e4fd08834214439f940c Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Sat, 23 May 2020 05:34:56 +0530
Subject: [PATCH 0111/2014] Create BoardPath
---
DynamicProgramming/BoardPath | 52 ++++++++++++++++++++++++++++++++++++
1 file changed, 52 insertions(+)
create mode 100644 DynamicProgramming/BoardPath
diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath
new file mode 100644
index 000000000000..4b471a88ed64
--- /dev/null
+++ b/DynamicProgramming/BoardPath
@@ -0,0 +1,52 @@
+
+public class BoardPath {
+ public static long startTime;
+ public static long endTime;
+ public static void startAlgo() {
+ startTime=System.currentTimeMillis();
+ }
+ public static long endAlgo() {
+ endTime=System.currentTimeMillis();
+ return endTime-startTime;
+ }
+ public static int bpR(int start,int end){
+ if(start==end) {
+ return 1;
+ }
+ else if(start>end)
+ return 0;
+ int count=0;
+ for(int dice=1;dice<=6;dice++) {
+ count+=bpR(start+dice,end);
+ }
+ return count;
+ }
+ public static int bpRS(int curr,int end,int strg[]){
+ if(curr==end) {
+ return 1;
+ }
+ else if(curr>end)
+ return 0;
+ if(strg[curr]!=0)
+ return strg[curr];
+ int count=0;
+ for(int dice=1;dice<=6;dice++) {
+ count+=bpRS(curr+dice,end,strg);
+ }
+ strg[curr]=count;
+ return count;
+ }
+ public static int bpIS(int curr,int end,int[]strg){
+ strg[end]=1;
+ for(int i=end-1;i>=0;i--) {
+ int count=0;
+ for(int dice=1;dice<=6&&dice+i
Date: Sat, 23 May 2020 05:35:47 +0530
Subject: [PATCH 0112/2014] Create CountNumBinaryStrings
---
DynamicProgramming/CountNumBinaryStrings | 69 ++++++++++++++++++++++++
1 file changed, 69 insertions(+)
create mode 100644 DynamicProgramming/CountNumBinaryStrings
diff --git a/DynamicProgramming/CountNumBinaryStrings b/DynamicProgramming/CountNumBinaryStrings
new file mode 100644
index 000000000000..c71fbd63c682
--- /dev/null
+++ b/DynamicProgramming/CountNumBinaryStrings
@@ -0,0 +1,69 @@
+public class CountNumBinaryStr {
+ public static long startTime;
+ public static long endTime;
+ public static void startAlgo() {
+ startTime=System.currentTimeMillis();
+ }
+ public static long endAlgo() {
+ endTime=System.currentTimeMillis();
+ return endTime-startTime;
+ }
+ public static int numStrIS(int n) {
+ int[] zeros=new int[n];
+ int []ones=new int[n];
+ //seed
+ zeros[0]=1;
+ ones[0]=1;
+ for(int i=1;i
Date: Sat, 23 May 2020 05:54:34 +0530
Subject: [PATCH 0113/2014] Delete LinkedList.java
---
.../HashMap/Hashing/LinkedList.java | 63 -------------------
1 file changed, 63 deletions(-)
delete mode 100644 DataStructures/HashMap/Hashing/LinkedList.java
diff --git a/DataStructures/HashMap/Hashing/LinkedList.java b/DataStructures/HashMap/Hashing/LinkedList.java
deleted file mode 100644
index 4953551f7040..000000000000
--- a/DataStructures/HashMap/Hashing/LinkedList.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package DataStructures.HashMap.Hashing;
-
-class LinkedList {
-
- private Node Head;
- private int size;
-
- public LinkedList() {
- Head = null;
- size = 0;
- }
-
- public void insert(int data) {
-
- Node newnode = new Node(data);
-
- size++;
-
- if(Head == null) {
- Head = newnode;
- }
- else {
- newnode.next = Head;
- Head = newnode;
- }
- }
-
- public void delete(int data) {
- if(size == 0) {
- System.out.println("UnderFlow!");
- return;
- }
-
- else {
- Node curr = Head;
- if (curr.data == data) {
- Head = curr.next;
- size--;
- return;
- }
- else {
-
- while(curr.next.next != null) {
- if(curr.next.data == data){
- curr.next = curr.next.next;
- return;
- }
- }
-
- System.out.println("Key not Found");
- }
- }
- }
-
- public void display() {
- Node temp = Head;
- while(temp != null) {
- System.out.printf("%d ",temp.data);
- temp = temp.next;
- }
- System.out.println();
- }
-}
\ No newline at end of file
From 3a234f0914198b6477445426a565c99e3dacae34 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Sat, 23 May 2020 05:56:23 +0530
Subject: [PATCH 0114/2014] Delete Node.java
---
DataStructures/HashMap/Hashing/Node.java | 11 -----------
1 file changed, 11 deletions(-)
delete mode 100644 DataStructures/HashMap/Hashing/Node.java
diff --git a/DataStructures/HashMap/Hashing/Node.java b/DataStructures/HashMap/Hashing/Node.java
deleted file mode 100644
index 74ab01f9d2a9..000000000000
--- a/DataStructures/HashMap/Hashing/Node.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package DataStructures.HashMap.Hashing;
-
-class Node {
- int data;
- Node next;
-
- public Node(int data) {
- this.data = data;
- this.next = null;
- }
-}
\ No newline at end of file
From 01d5814557dbe674886def8ceef86208c8994bbc Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Sat, 23 May 2020 05:57:55 +0530
Subject: [PATCH 0115/2014] Create Intersection
---
DataStructures/HashMap/Hashing/Intersection | 37 +++++++++++++++++++++
1 file changed, 37 insertions(+)
create mode 100644 DataStructures/HashMap/Hashing/Intersection
diff --git a/DataStructures/HashMap/Hashing/Intersection b/DataStructures/HashMap/Hashing/Intersection
new file mode 100644
index 000000000000..cfe1f74d73eb
--- /dev/null
+++ b/DataStructures/HashMap/Hashing/Intersection
@@ -0,0 +1,37 @@
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.Set;
+
+public class Intersection {
+
+ public static ArrayList Main(int arr[],int arr2[]) {
+ HashMap hmap=new HashMap<>();
+ HashMap hmap2=new HashMap<>();
+ for(int i=0;i res=new ArrayList<>();
+ for(int i=0;i0) {
+ int val=hmap.get(arr2[i]);
+ hmap.put(arr2[i],val-1);
+ res.add(arr2[i]);
+ }
+
+ }
+ return res;
+ }
+ public Intersection() {
+
+ }
+
+
+
+}
From ed497cec3782086f6834c410af31f21b51778732 Mon Sep 17 00:00:00 2001
From: Vineet Rathor <35703327+THE-VR7@users.noreply.github.com>
Date: Sat, 23 May 2020 13:16:09 +0530
Subject: [PATCH 0116/2014] Update BucketSort.java
---
Sorts/BucketSort.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/Sorts/BucketSort.java b/Sorts/BucketSort.java
index 58127927ee58..7556faf57406 100644
--- a/Sorts/BucketSort.java
+++ b/Sorts/BucketSort.java
@@ -55,6 +55,8 @@ public static void main(String args[])
}
}
+
+/*
#Output:
$ javac Bucket_Sort.java
@@ -66,3 +68,4 @@ public static void main(String args[])
95 9 95 87 8 81 18 54 57 53 92 15 38 24 8 56 29 69 64 66
Sorted Sequence:
8 8 9 15 18 24 29 38 53 54 56 57 64 66 69 81 87 92 95 95
+*/
From ce04b7fb5de43cf17ce709cb6fcd98300dcde918 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Sat, 23 May 2020 09:43:52 +0000
Subject: [PATCH 0117/2014] updating DIRECTORY.md
---
DIRECTORY.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index e77e30e84b82..aee8eea6f2a2 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -163,6 +163,7 @@
* [PerlinNoise](https://github.com/TheAlgorithms/Java/blob/master/Others/PerlinNoise.java)
* [PowerOfTwoOrNot](https://github.com/TheAlgorithms/Java/blob/master/Others/PowerOfTwoOrNot.java)
* [QueueUsingTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/Others/QueueUsingTwoStacks.java)
+ * [RabinKarp](https://github.com/TheAlgorithms/Java/blob/master/Others/RabinKarp.java)
* [RemoveDuplicateFromString](https://github.com/TheAlgorithms/Java/blob/master/Others/RemoveDuplicateFromString.java)
* [ReturnSubsequence](https://github.com/TheAlgorithms/Java/blob/master/Others/ReturnSubsequence.java)
* [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java)
@@ -172,6 +173,7 @@
* [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java)
* [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java)
* [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/Others/StackPostfixNotation.java)
+ * [StringMatchFiniteAutomata](https://github.com/TheAlgorithms/Java/blob/master/Others/StringMatchFiniteAutomata.java)
* [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/Others/TopKWords.java)
* [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/Others/TowerOfHanoi.java)
* [WorstFit](https://github.com/TheAlgorithms/Java/blob/master/Others/WorstFit.java)
From 1ef46dbfd49245ba7c6b5adf29b914e3d4db8b2f Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 02:50:24 +0530
Subject: [PATCH 0118/2014] Update GraphAlgos
---
DataStructures/Graphs/GraphAlgos | 50 ++++++++++++++++++++++++++++++++
1 file changed, 50 insertions(+)
diff --git a/DataStructures/Graphs/GraphAlgos b/DataStructures/Graphs/GraphAlgos
index 780a73e45540..19938c48f042 100644
--- a/DataStructures/Graphs/GraphAlgos
+++ b/DataStructures/Graphs/GraphAlgos
@@ -1,3 +1,53 @@
+package DataStructures.Graphs;
+/*
+Implementation of graph by using hashmap for vertices of class which contains hashmap for vertex and then algos like prims dijktsra ,depth for search and traversal ,breadth for search and traversal ,algo for cycle present or not ,connected or not ,if not connected then connect it
+Test case
+Graph gp=new Graph();
+ gp.addVertex("A");
+ gp.addVertex("B");
+ gp.addVertex("C");
+ gp.addVertex("D");
+ gp.addVertex("E");
+ gp.addVertex("F");
+ gp.addVertex("G");
+ gp.addEdge("A", "B", 2);
+ gp.addEdge("A", "D", 10);
+ gp.addEdge("B", "C", 3);
+ gp.addEdge("C", "D", 1);
+ gp.addEdge("D", "E", 8);
+ gp.addEdge("E", "F", 5);
+ gp.addEdge("E", "G", 6);
+ gp.addEdge("F", "G", 4);
+
+// gp.display();
+// System.out.println(gp.numVertex());
+// System.out.println(gp.numEdge());
+// System.out.println(gp.containsEdge("A", "C"));
+//
+// System.out.println(gp.containsEdge("E", "F"));
+// gp.removeEdge("D", "E");
+// gp.display();
+// gp.removeVertex("F");
+// gp.addVertex("F");
+// gp.display();
+// System.out.println(gp.hasPath("A", "F", new HashMap<>()));
+// System.out.println(gp.dfs("A", "F"));
+// gp.bft();
+// gp.dft();
+// gp.removeEdge("B","C");
+// gp.removeEdge("F","G");
+// System.out.println(gp.isConnected());
+// System.out.println(gp.isCyclic());
+// System.out.println(gp.isTree());
+// System.out.println(gp.getConnectedComp());
+// gp.prims().display();
+ System.out.println(gp.Dijktsra("A"));
+
+
+
+*/
+
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
From a5f42e293bfbe2c16efdef8c837bf2e36dcc7750 Mon Sep 17 00:00:00 2001
From: Maria Lungeanu
Date: Mon, 25 May 2020 00:21:28 +0300
Subject: [PATCH 0119/2014] Fixed Error:(6, 8) java: class algorithm is public,
should be declared in a file named algorithm.java. Inside file
PrimeFactorization, the name of public class was wrong.
---
Conversions/DecimalToBinary.java | 4 +-
Conversions/OctalToHexadecimal.java | 8 +-
DataStructures/DynamicArray/DynamicArray.java | 4 +-
DataStructures/Graphs/BellmanFord.java | 2 +-
DataStructures/Graphs/MatrixGraphs.java | 3 +-
DataStructures/Heaps/HeapElement.java | 18 +-
DataStructures/Heaps/MaxHeap.java | 8 +-
DataStructures/Heaps/MinHeap.java | 8 +-
DataStructures/Lists/CircleLinkedList.java | 2 +-
DataStructures/Lists/DoublyLinkedList.java | 12 +-
DataStructures/Stacks/NodeStack.java | 4 +-
DataStructures/Trees/LevelOrderTraversal.java | 4 +-
.../Trees/LevelOrderTraversalQueue.java | 4 +-
DataStructures/Trees/ValidBSTOrNot.java | 3 +-
.../LongestIncreasingSubsequence.java | 2 +-
.../MatrixChainMultiplication.java | 2 +-
Maths/GCD.java | 2 +-
Others/Dijkstra.java | 409 ++++++++++--------
Others/TopKWords.java | 3 +-
Others/TowerOfHanoi.java | 2 +-
Searches/IterativeBinarySearch.java | 2 +-
Sorts/QuickSort.java | 2 +-
ciphers/Caesar.java | 2 +
ciphers/ColumnarTranspositionCipher.java | 2 +-
divideconquer/ClosestPair.java | 19 +-
25 files changed, 293 insertions(+), 238 deletions(-)
diff --git a/Conversions/DecimalToBinary.java b/Conversions/DecimalToBinary.java
index ccd8c643fa9a..4dd1ba4f4414 100644
--- a/Conversions/DecimalToBinary.java
+++ b/Conversions/DecimalToBinary.java
@@ -27,7 +27,7 @@ public static void main(String args[]) {
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
- System.out.printf("Conventional conversion.\n\tEnter the decimal number: ");
+ System.out.printf("Conventional conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = n % 2;
@@ -46,7 +46,7 @@ public static void conventionalConversion() {
public static void bitwiseConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
- System.out.printf("Bitwise conversion.\n\tEnter the decimal number: ");
+ System.out.printf("Bitwise conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = (n & 1);
diff --git a/Conversions/OctalToHexadecimal.java b/Conversions/OctalToHexadecimal.java
index dd8d877109b5..4f15c488237b 100644
--- a/Conversions/OctalToHexadecimal.java
+++ b/Conversions/OctalToHexadecimal.java
@@ -15,7 +15,7 @@ public class OctalToHexadecimal {
* @param s The Octal Number
* @return The Decimal number
*/
- public static int OctToDec(String s) {
+ public static int octToDec(String s) {
int i = 0;
for (int j = 0; j < s.length(); j++) {
char num = s.charAt(j);
@@ -32,7 +32,7 @@ public static int OctToDec(String s) {
* @param d The Decimal Number
* @return The Hexadecimal number
*/
- public static String DecimalToHex(int d) {
+ public static String decimalToHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0)
return "0";
@@ -54,10 +54,10 @@ public static void main(String args[]) {
String oct = input.next();
// Pass the octal number to function and get converted deciaml form
- int decimal = OctToDec(oct);
+ int decimal = octToDec(oct);
// Pass the decimla number to function and get converted Hex form of the number
- String hex = DecimalToHex(decimal);
+ String hex = decimalToHex(decimal);
System.out.println("The Hexadecimal equivalant is: " + hex);
input.close();
}
diff --git a/DataStructures/DynamicArray/DynamicArray.java b/DataStructures/DynamicArray/DynamicArray.java
index 0a6a0723e2a1..f70c45cec815 100644
--- a/DataStructures/DynamicArray/DynamicArray.java
+++ b/DataStructures/DynamicArray/DynamicArray.java
@@ -41,7 +41,7 @@ public void add(final E element) {
}
public void put(final int index, E element) {
- Objects.checkIndex(index, this.size);
+// Objects.checkIndex(index, this.size);
this.elements[index] = element;
}
@@ -79,7 +79,7 @@ private void fastRemove(final Object[] elements, final int index) {
}
private E getElement(final int index) {
- Objects.checkIndex(index, this.size);
+// Objects.checkIndex(index, this.size);
return (E) this.elements[index];
}
diff --git a/DataStructures/Graphs/BellmanFord.java b/DataStructures/Graphs/BellmanFord.java
index 6dffede9e606..41c89bb020ee 100644
--- a/DataStructures/Graphs/BellmanFord.java
+++ b/DataStructures/Graphs/BellmanFord.java
@@ -23,7 +23,7 @@ class Edge
* @param v End vertex
* @param c Weight
*/
- Edge(int a,int b,int c)
+ public Edge(int a,int b,int c)
{
u=a;
v=b;
diff --git a/DataStructures/Graphs/MatrixGraphs.java b/DataStructures/Graphs/MatrixGraphs.java
index e7fb9cc4fb2f..32a7c990e3ef 100644
--- a/DataStructures/Graphs/MatrixGraphs.java
+++ b/DataStructures/Graphs/MatrixGraphs.java
@@ -127,8 +127,7 @@ public boolean removeEdge(int from, int to) {
* @return returns a string describing this graph
*/
public String toString() {
- String s = new String();
- s = " ";
+ String s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
s = s + String.valueOf(i) + " ";
}
diff --git a/DataStructures/Heaps/HeapElement.java b/DataStructures/Heaps/HeapElement.java
index 113146012918..028d9b3e67de 100644
--- a/DataStructures/Heaps/HeapElement.java
+++ b/DataStructures/Heaps/HeapElement.java
@@ -117,7 +117,21 @@ public String toString() {
* @return true if the keys on both elements are identical and the additional info objects
* are identical.
*/
- public boolean equals(HeapElement otherHeapElement) {
- return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
+ @Override
+ public boolean equals(Object o) {
+ if (o != null) {
+ if (!(o instanceof HeapElement)) return false;
+ HeapElement otherHeapElement = (HeapElement) o;
+ return (this.key == otherHeapElement.key) && (this.additionalInfo.equals(otherHeapElement.additionalInfo));
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 0;
+ result = 31*result + (int) key;
+ result = 31*result + (additionalInfo != null ? additionalInfo.hashCode() : 0);
+ return result;
}
}
diff --git a/DataStructures/Heaps/MaxHeap.java b/DataStructures/Heaps/MaxHeap.java
index fed09bcba045..3945caa97fde 100644
--- a/DataStructures/Heaps/MaxHeap.java
+++ b/DataStructures/Heaps/MaxHeap.java
@@ -49,9 +49,9 @@ private void swap(int index1, int index2) {
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
- while (getElementKey((int) Math.floor(elementIndex / 2)) < key) {
- swap(elementIndex, (int) Math.floor(elementIndex / 2));
- elementIndex = (int) Math.floor(elementIndex / 2);
+ while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) {
+ swap(elementIndex, (int) Math.floor(elementIndex / 2.0));
+ elementIndex = (int) Math.floor(elementIndex / 2.0);
}
}
@@ -101,7 +101,7 @@ public void deleteElement(int elementIndex) {
maxHeap.set(elementIndex - 1, getElement(maxHeap.size()));
maxHeap.remove(maxHeap.size());
// Shall the new element be moved up...
- if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex);
+ if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) ||
((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))))
diff --git a/DataStructures/Heaps/MinHeap.java b/DataStructures/Heaps/MinHeap.java
index 4b435e6d81d7..39ee6ebf7b8f 100644
--- a/DataStructures/Heaps/MinHeap.java
+++ b/DataStructures/Heaps/MinHeap.java
@@ -44,9 +44,9 @@ private void swap(int index1, int index2) {
// Toggle an element up to its right place as long as its key is lower than its parent's
private void toggleUp(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
- while (getElementKey((int) Math.floor(elementIndex / 2)) > key) {
- swap(elementIndex, (int) Math.floor(elementIndex / 2));
- elementIndex = (int) Math.floor(elementIndex / 2);
+ while (getElementKey((int) Math.floor(elementIndex / 2.0)) > key) {
+ swap(elementIndex, (int) Math.floor(elementIndex / 2.0));
+ elementIndex = (int) Math.floor(elementIndex / 2.0);
}
}
@@ -96,7 +96,7 @@ public void deleteElement(int elementIndex) {
minHeap.set(elementIndex - 1, getElement(minHeap.size()));
minHeap.remove(minHeap.size());
// Shall the new element be moved up...
- if (getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2))) toggleUp(elementIndex);
+ if (getElementKey(elementIndex) < getElementKey((int)Math.floor(elementIndex / 2.0))) toggleUp(elementIndex);
// ... or down ?
else if (((2 * elementIndex <= minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))) ||
((2 * elementIndex < minHeap.size()) && (getElementKey(elementIndex) > getElementKey(elementIndex * 2))))
diff --git a/DataStructures/Lists/CircleLinkedList.java b/DataStructures/Lists/CircleLinkedList.java
index 67235172dfb7..b46441a1fa47 100644
--- a/DataStructures/Lists/CircleLinkedList.java
+++ b/DataStructures/Lists/CircleLinkedList.java
@@ -14,7 +14,7 @@ private Node(E value, Node next) {
//For better O.O design this should be private allows for better black box design
private int size;
//this will point to dummy node;
- private Node head;
+ private Node head = null;
//constructer for class.. here we will make a dummy node for circly linked list implementation with reduced error catching as our list will never be empty;
public CircleLinkedList() {
diff --git a/DataStructures/Lists/DoublyLinkedList.java b/DataStructures/Lists/DoublyLinkedList.java
index e1b0041dda39..706b33c7e10d 100644
--- a/DataStructures/Lists/DoublyLinkedList.java
+++ b/DataStructures/Lists/DoublyLinkedList.java
@@ -86,9 +86,12 @@ public void insertTail(int x) {
public Link deleteHead() {
Link temp = head;
head = head.next; // oldHead <--> 2ndElement(head)
- head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
- if (head == null)
+
+ if (head == null) {
tail = null;
+ } else {
+ head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so will be removed
+ }
return temp;
}
@@ -100,10 +103,13 @@ public Link deleteHead() {
public Link deleteTail() {
Link temp = tail;
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
- tail.next = null; // 2ndLast(tail) --> null
+
if (tail == null) {
head = null;
+ } else{
+ tail.next = null; // 2ndLast(tail) --> null
}
+
return temp;
}
diff --git a/DataStructures/Stacks/NodeStack.java b/DataStructures/Stacks/NodeStack.java
index 616e6a1e1548..0f1d58686b0d 100644
--- a/DataStructures/Stacks/NodeStack.java
+++ b/DataStructures/Stacks/NodeStack.java
@@ -74,7 +74,7 @@ public void push(Item item) {
} else {
newNs.setPrevious(NodeStack.head);
NodeStack.head.setNext(newNs);
- NodeStack.head = newNs;
+ NodeStack.head.setHead(newNs);
}
NodeStack.setSize(NodeStack.getSize() + 1);
@@ -89,7 +89,7 @@ public Item pop() {
Item item = (Item) NodeStack.head.getData();
- NodeStack.head = NodeStack.head.getPrevious();
+ NodeStack.head.setHead(NodeStack.head.getPrevious());
NodeStack.head.setNext(null);
NodeStack.setSize(NodeStack.getSize() - 1);
diff --git a/DataStructures/Trees/LevelOrderTraversal.java b/DataStructures/Trees/LevelOrderTraversal.java
index bcf172495d13..69e65fe64089 100644
--- a/DataStructures/Trees/LevelOrderTraversal.java
+++ b/DataStructures/Trees/LevelOrderTraversal.java
@@ -15,8 +15,8 @@ public Node(int item) {
// Root of the Binary Tree
Node root;
- public LevelOrderTraversal() {
- root = null;
+ public LevelOrderTraversal( Node root) {
+ this.root = root;
}
/* function to print level order traversal of tree*/
diff --git a/DataStructures/Trees/LevelOrderTraversalQueue.java b/DataStructures/Trees/LevelOrderTraversalQueue.java
index d43d62d68f5f..5f85f987d673 100644
--- a/DataStructures/Trees/LevelOrderTraversalQueue.java
+++ b/DataStructures/Trees/LevelOrderTraversalQueue.java
@@ -19,11 +19,9 @@ public Node(int item) {
}
}
- Node root;
-
/* Given a binary tree. Print its nodes in level order
using array for implementing queue */
- void printLevelOrder() {
+ void printLevelOrder(Node root) {
Queue queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
diff --git a/DataStructures/Trees/ValidBSTOrNot.java b/DataStructures/Trees/ValidBSTOrNot.java
index a1a737fe4fe9..ba50c079eac4 100644
--- a/DataStructures/Trees/ValidBSTOrNot.java
+++ b/DataStructures/Trees/ValidBSTOrNot.java
@@ -13,14 +13,13 @@ public Node(int item) {
}
//Root of the Binary Tree
- Node root;
/* can give min and max value according to your code or
can write a function to find min and max value of tree. */
/* returns true if given search tree is binary
search tree (efficient version) */
- boolean isBST() {
+ boolean isBST(Node root) {
return isBSTUtil(root, Integer.MIN_VALUE,
Integer.MAX_VALUE);
}
diff --git a/DynamicProgramming/LongestIncreasingSubsequence.java b/DynamicProgramming/LongestIncreasingSubsequence.java
index c8296518590d..e30adfeffd39 100644
--- a/DynamicProgramming/LongestIncreasingSubsequence.java
+++ b/DynamicProgramming/LongestIncreasingSubsequence.java
@@ -22,7 +22,7 @@ public static void main(String[] args) {
private static int upperBound(int[] ar, int l, int r, int key) {
while (l < r - 1) {
- int m = (l + r) / 2;
+ int m = (l + r) >>> 1;
if (ar[m] >= key)
r = m;
else
diff --git a/DynamicProgramming/MatrixChainMultiplication.java b/DynamicProgramming/MatrixChainMultiplication.java
index 66b2a35824e2..9073400d3299 100644
--- a/DynamicProgramming/MatrixChainMultiplication.java
+++ b/DynamicProgramming/MatrixChainMultiplication.java
@@ -25,7 +25,7 @@ public static void main(String[] args) {
count++;
}
for (Matrix m : mArray) {
- System.out.format("A(%d) = %2d x %2d\n", m.count(), m.col(), m.row());
+ System.out.format("A(%d) = %2d x %2d%n", m.count(), m.col(), m.row());
}
size = mArray.size();
diff --git a/Maths/GCD.java b/Maths/GCD.java
index fb9aeb21ee1b..bff1c33c80f5 100644
--- a/Maths/GCD.java
+++ b/Maths/GCD.java
@@ -52,6 +52,6 @@ public static void main(String[] args) {
// call gcd function (input array)
System.out.println(gcd(myIntArray)); // => 4
- System.out.printf("gcd(40,24)=%d gcd(24,40)=%d\n", gcd(40, 24), gcd(24, 40)); // => 8
+ System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
}
}
diff --git a/Others/Dijkstra.java b/Others/Dijkstra.java
index af8e33b0b320..b1a0987d0245 100644
--- a/Others/Dijkstra.java
+++ b/Others/Dijkstra.java
@@ -1,192 +1,219 @@
-package Others;
-
-
-/**
- * Dijkstra's algorithm,is a graph search algorithm that solves the single-source
- * shortest path problem for a graph with nonnegative edge path costs, producing
- * a shortest path tree.
- *
- * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
- * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
- *
- * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
- * Also most of the comments are from RosettaCode.
- */
-
-import java.util.*;
-
-public class Dijkstra {
- private static final Graph.Edge[] GRAPH = {
- // Distance from node "a" to node "b" is 7.
- // In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
- // a new edge would be needed for that
- new Graph.Edge("a", "b", 7),
- new Graph.Edge("a", "c", 9),
- new Graph.Edge("a", "f", 14),
- new Graph.Edge("b", "c", 10),
- new Graph.Edge("b", "d", 15),
- new Graph.Edge("c", "d", 11),
- new Graph.Edge("c", "f", 2),
- new Graph.Edge("d", "e", 6),
- new Graph.Edge("e", "f", 9),
- };
- private static final String START = "a";
- private static final String END = "e";
-
- /**
- * main function
- * Will run the code with "GRAPH" that was defined above.
- */
- public static void main(String[] args) {
- Graph g = new Graph(GRAPH);
- g.dijkstra(START);
- g.printPath(END);
- //g.printAllPaths();
- }
-}
-
-class Graph {
- // mapping of vertex names to Vertex objects, built from a set of Edges
- private final Map graph;
-
- /**
- * One edge of the graph (only used by Graph constructor)
- */
- public static class Edge {
- public final String v1, v2;
- public final int dist;
-
- public Edge(String v1, String v2, int dist) {
- this.v1 = v1;
- this.v2 = v2;
- this.dist = dist;
- }
- }
-
- /**
- * One vertex of the graph, complete with mappings to neighbouring vertices
- */
- public static class Vertex implements Comparable {
- public final String name;
- // MAX_VALUE assumed to be infinity
- public int dist = Integer.MAX_VALUE;
- public Vertex previous = null;
- public final Map neighbours = new HashMap<>();
-
- public Vertex(String name) {
- this.name = name;
- }
-
- private void printPath() {
- if (this == this.previous) {
- System.out.printf("%s", this.name);
- } else if (this.previous == null) {
- System.out.printf("%s(unreached)", this.name);
- } else {
- this.previous.printPath();
- System.out.printf(" -> %s(%d)", this.name, this.dist);
- }
- }
-
- public int compareTo(Vertex other) {
- if (dist == other.dist)
- return name.compareTo(other.name);
-
- return Integer.compare(dist, other.dist);
- }
-
- @Override
- public String toString() {
- return "(" + name + ", " + dist + ")";
- }
- }
-
- /**
- * Builds a graph from a set of edges
- */
- public Graph(Edge[] edges) {
- graph = new HashMap<>(edges.length);
-
- // one pass to find all vertices
- for (Edge e : edges) {
- if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
- if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
- }
-
- // another pass to set neighbouring vertices
- for (Edge e : edges) {
- graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
- // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
- }
- }
-
- /**
- * Runs dijkstra using a specified source vertex
- */
- public void dijkstra(String startName) {
- if (!graph.containsKey(startName)) {
- System.err.printf("Graph doesn't contain start vertex \"%s\"\n", startName);
- return;
- }
- final Vertex source = graph.get(startName);
- NavigableSet q = new TreeSet<>();
-
- // set-up vertices
- for (Vertex v : graph.values()) {
- v.previous = v == source ? source : null;
- v.dist = v == source ? 0 : Integer.MAX_VALUE;
- q.add(v);
- }
-
- dijkstra(q);
- }
-
- /**
- * Implementation of dijkstra's algorithm using a binary heap.
- */
- private void dijkstra(final NavigableSet q) {
- Vertex u, v;
- while (!q.isEmpty()) {
- // vertex with shortest distance (first iteration will return source)
- u = q.pollFirst();
- if (u.dist == Integer.MAX_VALUE)
- break; // we can ignore u (and any other remaining vertices) since they are unreachable
-
- // look at distances to each neighbour
- for (Map.Entry a : u.neighbours.entrySet()) {
- v = a.getKey(); // the neighbour in this iteration
-
- final int alternateDist = u.dist + a.getValue();
- if (alternateDist < v.dist) { // shorter path to neighbour found
- q.remove(v);
- v.dist = alternateDist;
- v.previous = u;
- q.add(v);
- }
- }
- }
- }
-
- /**
- * Prints a path from the source to the specified vertex
- */
- public void printPath(String endName) {
- if (!graph.containsKey(endName)) {
- System.err.printf("Graph doesn't contain end vertex \"%s\"\n", endName);
- return;
- }
-
- graph.get(endName).printPath();
- System.out.println();
- }
-
- /**
- * Prints the path from the source to every vertex (output order is not guaranteed)
- */
- public void printAllPaths() {
- for (Vertex v : graph.values()) {
- v.printPath();
- System.out.println();
- }
- }
+package Others;
+
+
+/**
+ * Dijkstra's algorithm,is a graph search algorithm that solves the single-source
+ * shortest path problem for a graph with nonnegative edge path costs, producing
+ * a shortest path tree.
+ *
+ * NOTE: The inputs to Dijkstra's algorithm are a directed and weighted graph consisting
+ * of 2 or more nodes, generally represented by an adjacency matrix or list, and a start node.
+ *
+ * Original source of code: https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Java
+ * Also most of the comments are from RosettaCode.
+ */
+
+import java.util.*;
+
+public class Dijkstra {
+ private static final Graph.Edge[] GRAPH = {
+ // Distance from node "a" to node "b" is 7.
+ // In the current Graph there is no way to move the other way (e,g, from "b" to "a"),
+ // a new edge would be needed for that
+ new Graph.Edge("a", "b", 7),
+ new Graph.Edge("a", "c", 9),
+ new Graph.Edge("a", "f", 14),
+ new Graph.Edge("b", "c", 10),
+ new Graph.Edge("b", "d", 15),
+ new Graph.Edge("c", "d", 11),
+ new Graph.Edge("c", "f", 2),
+ new Graph.Edge("d", "e", 6),
+ new Graph.Edge("e", "f", 9),
+ };
+ private static final String START = "a";
+ private static final String END = "e";
+
+ /**
+ * main function
+ * Will run the code with "GRAPH" that was defined above.
+ */
+ public static void main(String[] args) {
+ Graph g = new Graph(GRAPH);
+ g.dijkstra(START);
+ g.printPath(END);
+ //g.printAllPaths();
+ }
+}
+
+class Graph {
+ // mapping of vertex names to Vertex objects, built from a set of Edges
+ private final Map graph;
+
+ /**
+ * One edge of the graph (only used by Graph constructor)
+ */
+ public static class Edge {
+ public final String v1, v2;
+ public final int dist;
+
+ public Edge(String v1, String v2, int dist) {
+ this.v1 = v1;
+ this.v2 = v2;
+ this.dist = dist;
+ }
+ }
+
+ /**
+ * One vertex of the graph, complete with mappings to neighbouring vertices
+ */
+ public static class Vertex implements Comparable {
+ public final String name;
+ // MAX_VALUE assumed to be infinity
+ public int dist = Integer.MAX_VALUE;
+ public Vertex previous = null;
+ public final Map neighbours = new HashMap<>();
+
+ public Vertex(String name) {
+ this.name = name;
+ }
+
+ private void printPath() {
+ if (this == this.previous) {
+ System.out.printf("%s", this.name);
+ } else if (this.previous == null) {
+ System.out.printf("%s(unreached)", this.name);
+ } else {
+ this.previous.printPath();
+ System.out.printf(" -> %s(%d)", this.name, this.dist);
+ }
+ }
+
+ public int compareTo(Vertex other) {
+ if (dist == other.dist)
+ return name.compareTo(other.name);
+
+ return Integer.compare(dist, other.dist);
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) return true;
+ if (object == null || getClass() != object.getClass()) return false;
+ if (!super.equals(object)) return false;
+
+ Vertex vertex = (Vertex) object;
+
+ if (dist != vertex.dist) return false;
+ if (name != null ? !name.equals(vertex.name) : vertex.name != null) return false;
+ if (previous != null ? !previous.equals(vertex.previous) : vertex.previous != null) return false;
+ if (neighbours != null ? !neighbours.equals(vertex.neighbours) : vertex.neighbours != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = super.hashCode();
+ result = 31 * result + (name != null ? name.hashCode() : 0);
+ result = 31 * result + dist;
+ result = 31 * result + (previous != null ? previous.hashCode() : 0);
+ result = 31 * result + (neighbours != null ? neighbours.hashCode() : 0);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return "(" + name + ", " + dist + ")";
+ }
+ }
+
+ /**
+ * Builds a graph from a set of edges
+ */
+ public Graph(Edge[] edges) {
+ graph = new HashMap<>(edges.length);
+
+ // one pass to find all vertices
+ for (Edge e : edges) {
+ if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));
+ if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));
+ }
+
+ // another pass to set neighbouring vertices
+ for (Edge e : edges) {
+ graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);
+ // graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); // also do this for an undirected graph
+ }
+ }
+
+ /**
+ * Runs dijkstra using a specified source vertex
+ */
+ public void dijkstra(String startName) {
+ if (!graph.containsKey(startName)) {
+ System.err.printf("Graph doesn't contain start vertex \"%s\"%n", startName);
+ return;
+ }
+ final Vertex source = graph.get(startName);
+ NavigableSet q = new TreeSet<>();
+
+ // set-up vertices
+ for (Vertex v : graph.values()) {
+ v.previous = v == source ? source : null;
+ v.dist = v == source ? 0 : Integer.MAX_VALUE;
+ q.add(v);
+ }
+
+ dijkstra(q);
+ }
+
+ /**
+ * Implementation of dijkstra's algorithm using a binary heap.
+ */
+ private void dijkstra(final NavigableSet q) {
+ Vertex u, v;
+ while (!q.isEmpty()) {
+ // vertex with shortest distance (first iteration will return source)
+ u = q.pollFirst();
+ if (u.dist == Integer.MAX_VALUE)
+ break; // we can ignore u (and any other remaining vertices) since they are unreachable
+
+ // look at distances to each neighbour
+ for (Map.Entry a : u.neighbours.entrySet()) {
+ v = a.getKey(); // the neighbour in this iteration
+
+ final int alternateDist = u.dist + a.getValue();
+ if (alternateDist < v.dist) { // shorter path to neighbour found
+ q.remove(v);
+ v.dist = alternateDist;
+ v.previous = u;
+ q.add(v);
+ }
+ }
+ }
+ }
+
+ /**
+ * Prints a path from the source to the specified vertex
+ */
+ public void printPath(String endName) {
+ if (!graph.containsKey(endName)) {
+ System.err.printf("Graph doesn't contain end vertex \"%s\"%n", endName);
+ return;
+ }
+
+ graph.get(endName).printPath();
+ System.out.println();
+ }
+
+ /**
+ * Prints the path from the source to every vertex (output order is not guaranteed)
+ */
+ public void printAllPaths() {
+ for (Vertex v : graph.values()) {
+ v.printPath();
+ System.out.println();
+ }
+ }
+
}
\ No newline at end of file
diff --git a/Others/TopKWords.java b/Others/TopKWords.java
index 6cccfc27b95f..b3f0e5846b12 100644
--- a/Others/TopKWords.java
+++ b/Others/TopKWords.java
@@ -50,7 +50,8 @@ public Map getDictionary() {
} finally {
try {
// you always have to close the I/O streams
- fis.close();
+ if (fis != null)
+ fis.close();
} catch (IOException e) {
e.printStackTrace();
}
diff --git a/Others/TowerOfHanoi.java b/Others/TowerOfHanoi.java
index 7d35ed36d54f..db31959558a3 100644
--- a/Others/TowerOfHanoi.java
+++ b/Others/TowerOfHanoi.java
@@ -12,7 +12,7 @@ public static void shift(int n, String startPole, String intermediatePole, Strin
// Shift function is called in recursion for swapping the n-1 disc from the startPole to the intermediatePole
shift(n - 1, startPole, endPole, intermediatePole);
- System.out.println("\nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
+ System.out.println("%nMove \"" + n + "\" from " + startPole + " --> " + endPole); // Result Printing
// Shift function is called in recursion for swapping the n-1 disc from the intermediatePole to the endPole
shift(n - 1, intermediatePole, startPole, endPole);
}
diff --git a/Searches/IterativeBinarySearch.java b/Searches/IterativeBinarySearch.java
index 8df51a7d789b..5a3a6d9e11cc 100644
--- a/Searches/IterativeBinarySearch.java
+++ b/Searches/IterativeBinarySearch.java
@@ -40,7 +40,7 @@ public > int find(T[] array, T key) {
r = array.length - 1;
while (l <= r) {
- k = (l + r) / 2;
+ k = (l + r) >>> 1;
cmp = key.compareTo(array[k]);
if (cmp == 0) {
diff --git a/Sorts/QuickSort.java b/Sorts/QuickSort.java
index 47f79de0c35d..ef564ac722cb 100644
--- a/Sorts/QuickSort.java
+++ b/Sorts/QuickSort.java
@@ -64,7 +64,7 @@ private static > int randomPartition(T[] array, int left
**/
private static > int partition(T[] array, int left, int right) {
- int mid = (left + right) / 2;
+ int mid = (left + right) >>> 1;
T pivot = array[mid];
while (left <= right) {
diff --git a/ciphers/Caesar.java b/ciphers/Caesar.java
index cec0ddce0065..76893f45327e 100644
--- a/ciphers/Caesar.java
+++ b/ciphers/Caesar.java
@@ -125,6 +125,8 @@ public static void main(String[] args) {
case 'D':
case 'd':
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift));
+ default:
+ System.out.println("default case");
}
input.close();
}
diff --git a/ciphers/ColumnarTranspositionCipher.java b/ciphers/ColumnarTranspositionCipher.java
index 26acc628e393..60af4ff5429c 100644
--- a/ciphers/ColumnarTranspositionCipher.java
+++ b/ciphers/ColumnarTranspositionCipher.java
@@ -117,7 +117,7 @@ private static Object[][] tableBuilder(String word) {
* order to respect the Columnar Transposition Cipher Rule.
*/
private static int numberOfRows(String word) {
- if ((double) word.length() / keyword.length() > word.length() / keyword.length()) {
+ if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else {
return word.length() / keyword.length();
diff --git a/divideconquer/ClosestPair.java b/divideconquer/ClosestPair.java
index 375d3e1a949c..67ebe89b8628 100644
--- a/divideconquer/ClosestPair.java
+++ b/divideconquer/ClosestPair.java
@@ -31,6 +31,15 @@ public final class ClosestPair {
* Minimum point length.
*/
private static double minNum = Double.MAX_VALUE;
+
+ public static void setMinNum(double minNum) {
+ ClosestPair.minNum = minNum;
+ }
+
+ public static void setSecondCount(int secondCount) {
+ ClosestPair.secondCount = secondCount;
+ }
+
/**
* secondCount
*/
@@ -213,7 +222,7 @@ public double closestPair(final Location[] a, final int indexNum) {
for (int i = 0; i < totalNum; i++) {
double xGap = Math.abs(divideArray[divideX].x - divideArray[i].x);
if (xGap < minValue) {
- secondCount++; // size of the array
+ ClosestPair.setSecondCount(secondCount + 1); // size of the array
} else {
if (divideArray[i].x > divideArray[divideX].x) {
break;
@@ -250,7 +259,7 @@ public double closestPair(final Location[] a, final int indexNum) {
minValue = length;
// Conditional for registering final coordinate
if (length < minNum) {
- minNum = length;
+ ClosestPair.setMinNum(length);
point1 = firstWindow[i];
point2 = firstWindow[j];
}
@@ -260,7 +269,7 @@ public double closestPair(final Location[] a, final int indexNum) {
}
}
}
- secondCount = 0;
+ ClosestPair.setSecondCount(0);
return minValue;
}
@@ -288,7 +297,7 @@ public double bruteForce(final Location[] arrayParam) {
length = Math.sqrt(Math.pow(xGap, 2) + Math.pow(yGap, 2));
// Conditional statement for registering final coordinate
if (length < minNum) {
- minNum = length;
+ ClosestPair.setMinNum(length);
}
point1 = arrayParam[0];
@@ -311,7 +320,7 @@ public double bruteForce(final Location[] arrayParam) {
minValue = length;
if (length < minNum) {
// Registering final coordinate
- minNum = length;
+ ClosestPair.setMinNum(length);
point1 = arrayParam[i];
point2 = arrayParam[j];
}
From f710f3aafac8be42219c1be4ed7dbfa03c878b4b Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:02:15 +0530
Subject: [PATCH 0120/2014] Update ListAddnFun
---
DataStructures/Lists/ListAddnFun | 41 ++++++++++++++++++++++++++++++++
1 file changed, 41 insertions(+)
diff --git a/DataStructures/Lists/ListAddnFun b/DataStructures/Lists/ListAddnFun
index 47553e184358..afbd2ae431d8 100644
--- a/DataStructures/Lists/ListAddnFun
+++ b/DataStructures/Lists/ListAddnFun
@@ -1,3 +1,44 @@
+package DataStructures.Lists;
+
+/*
+ * This class implements a SinglyLinked List.
+ * A linked list is similar to an array, it hold values.
+ * However, links in a linked list do not have indexes. With
+ * a linked list you do not need to predetermine it's size as
+ * it grows and shrinks as it is edited.
+ *it has functions called mid that gives node at mid
+ * in addn to linked list there is algo that
+ * construct a linked list with alternate sums of linked list
+ * and added to new one and add mid value
+ * i.e sum of first and last value of inital list
+
+ Test Case:
+
+
+ LinkedList LL1 = new LinkedList();
+ Scanner scn=new Scanner(System.in);
+ int numNodes=scn.nextInt();
+ for(int i=0;i<2*numNodes;i++) {
+ LL1.addLast(scn.nextInt());
+ }
+ LL1.display();
+ LinkedList LL2=new LinkedList();
+ LL2.formLL2(LL1);
+ LL2.display();
+ LinkedList LL3=new LinkedList();
+ LL3.formLL3(LL1);
+ LL3.display();
+ Node MID=LL1.midValue();
+ System.out.println(MID.data);
+ LinkedList updLL1=new LinkedList();
+ updLL1.formRes(LL1,LL2,LL3,MID);
+ updLL1.display();
+ updLL1.Size();
+
+ */
+
+
+
import java.util.*;
import java.lang.*;
import java.io.*;
From 82e2132557bbf295f2f1d3b03bc41092bd736f78 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:06:36 +0530
Subject: [PATCH 0121/2014] Update AVLSimple
---
DataStructures/Trees/AVLSimple | 31 +++++++++++++++++++++++++++++++
1 file changed, 31 insertions(+)
diff --git a/DataStructures/Trees/AVLSimple b/DataStructures/Trees/AVLSimple
index 1f2c2bd6aba2..ace0c46b9374 100644
--- a/DataStructures/Trees/AVLSimple
+++ b/DataStructures/Trees/AVLSimple
@@ -1,3 +1,34 @@
+
+package DataStructures.Trees;
+
+/*
+* Avl is algo that balance itself while adding new alues to tree
+* by rotating branches of binary tree and make itself Binary seaarch tree
+* there are four cases which has to tackle
+* rotating - left right ,left left,right right,right left
+
+Test Case:
+
+AVLTree tree=new AVLTree();
+ tree.insert(20);
+ tree.insert(25);
+ tree.insert(30);
+ tree.insert(10);
+ tree.insert(5);
+ tree.insert(15);
+ tree.insert(27);
+ tree.insert(19);
+ tree.insert(16);
+
+ tree.display();
+
+
+
+
+*/
+
+
+
public class AVLTree {
private class Node{
int data;
From 920852aa0e41015a05fe72976675b4c439560bab Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:11:14 +0530
Subject: [PATCH 0122/2014] Update BoardPath
---
DynamicProgramming/BoardPath | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath
index 4b471a88ed64..91f1f011a6a0 100644
--- a/DynamicProgramming/BoardPath
+++ b/DynamicProgramming/BoardPath
@@ -1,4 +1,29 @@
+package DynamicProgramming.BoardPath;
+/*
+* this is an important Algo in which
+* we have starting and ending of board and we have to reach
+* we have to count no. of ways
+* that help to reach end point i.e number by rolling dice
+* which have 1 to 6 digits
+Test Case:
+here target is 10
+
+int n=10;
+ startAlgo();
+ System.out.println(bpR(0,n));
+ System.out.println(endAlgo()+"ms");
+ int[] strg=new int [n+1];
+ startAlgo();
+ System.out.println(bpRS(0,n,strg));
+ System.out.println(endAlgo()+"ms");
+ startAlgo();
+ System.out.println(bpIS(0,n,strg));
+ System.out.println(endAlgo()+"ms");
+
+
+
+*/
public class BoardPath {
public static long startTime;
public static long endTime;
From 94cfab0cfc060685c2f899d876b15be9cd279757 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:12:16 +0530
Subject: [PATCH 0123/2014] Update BoardPath
---
DynamicProgramming/BoardPath | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/DynamicProgramming/BoardPath b/DynamicProgramming/BoardPath
index 91f1f011a6a0..5ca14d1fab9b 100644
--- a/DynamicProgramming/BoardPath
+++ b/DynamicProgramming/BoardPath
@@ -1,4 +1,4 @@
-package DynamicProgramming.BoardPath;
+package DynamicProgramming;
/*
* this is an important Algo in which
* we have starting and ending of board and we have to reach
From ec4f6a11102f9419eeaa36042fa265a95bf5e4e2 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:17:26 +0530
Subject: [PATCH 0124/2014] Update CountNumBinaryStrings
---
DynamicProgramming/CountNumBinaryStrings | 28 ++++++++++++++++++++++++
1 file changed, 28 insertions(+)
diff --git a/DynamicProgramming/CountNumBinaryStrings b/DynamicProgramming/CountNumBinaryStrings
index c71fbd63c682..3dd0bf7ded9c 100644
--- a/DynamicProgramming/CountNumBinaryStrings
+++ b/DynamicProgramming/CountNumBinaryStrings
@@ -1,3 +1,31 @@
+package DynamicProgramming;
+/*
+* here is a important algo in this we have to count
+* maximum no. of different binary strings which doesnot have
+* consectuive 1s
+
+
+
+Test Case:
+
+int n=30;
+
+ startAlgo();
+ System.out.println(numStrIS(n));
+ System.out.println(endAlgo()+"ms");
+
+ startAlgo();
+ CountNumBinaryStr out=new CountNumBinaryStr();
+ System.out.println(out.numStrR(n).ans);
+ System.out.println(endAlgo()+"ms");
+
+ startAlgo();
+ System.out.println(countStrings(n,0));
+ System.out.println(endAlgo()+"ms");
+
+
+
+*/
public class CountNumBinaryStr {
public static long startTime;
public static long endTime;
From a23a17ba6540818b266ad56a2fb181512dd4f1b5 Mon Sep 17 00:00:00 2001
From: Ritik2604 <49342895+Ritik2604@users.noreply.github.com>
Date: Mon, 25 May 2020 03:22:27 +0530
Subject: [PATCH 0125/2014] Update Intersection
---
DataStructures/HashMap/Hashing/Intersection | 27 +++++++++++++++++++++
1 file changed, 27 insertions(+)
diff --git a/DataStructures/HashMap/Hashing/Intersection b/DataStructures/HashMap/Hashing/Intersection
index cfe1f74d73eb..8b54eeae1a95 100644
--- a/DataStructures/HashMap/Hashing/Intersection
+++ b/DataStructures/HashMap/Hashing/Intersection
@@ -1,3 +1,30 @@
+package DataStructures.HashMap.Hashing;
+/*
+* this is algo which implies common mathematical set theory concept
+* called intersection in which result is common values of both the sets
+* here metaphor of sets is HashMap
+
+
+Test Case:
+ Scanner scn=new Scanner(System.in);
+ int len =scn.nextInt();
+ int arr[]=new int[len];
+ int arr2[]=new int[len];
+
+ for(int i=0;i<2*len;i++) {
+
+ if(i=len) {
+ arr2[i-len]=scn.nextInt();
+ }
+ }
+ System.out.println(Main(arr,arr2));
+
+
+
+*/
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
From c76c4ddda7becf3c633323041f5128bcdb7d5e71 Mon Sep 17 00:00:00 2001
From: MohamedBechir <57349735+MohamedBechir@users.noreply.github.com>
Date: Sun, 24 May 2020 23:00:46 +0100
Subject: [PATCH 0126/2014] Update CONTRIBUTING.md file
I tried to update the CONTRIBUTING.md file in order to simplify as much as possible the process for the developers which will encourage them to join the project and hence enlarge our community.
Thank you for putting it under review, if there are any changes feel free to ask me to do it.
---
CONTRIBUTING.md | 27 +++++++++++++++++++++++++--
1 file changed, 25 insertions(+), 2 deletions(-)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d502de24281c..62f268c98f18 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,2 +1,25 @@
-## Contribution Guidelines
-Read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute.
+:+1::tada: Before guiding you through the contribution process TheAlgorithms/Java thank you for being one of us! :+1::tada:
+
+## How to contribute?
+
+#### **Did you find a bug?**
+
+* **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues).
+
+* If you are unable to find an open issue refering to the same problem, depending on the type of issue follow the appropriate steps:
+
+#### **Do you want to contribute to the documentation?**
+
+* Please read the documentation in here [Contributing to the Documentation]() ,[open a new one issue](https://github.com/TheAlgorithms/Java/issues/new), make changes and then create a pull request, it will be put under review and accepted if it is approprite.
+
+#### **Do you want to add a new feature?**
+* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new). Be sure to include a **title and a clear description** and a **test case** demonstrating the new feature that you want to add to the project.
+
+#### **Do you want to fix a bug?**
+* [Open a new one issue](https://github.com/TheAlgorithms/Java/issues/new).Be sure to include a **title and a clear description** and a **test case** demonstrating the expected behaviour that is not occuring.
+
+#### **Do you have questions about the source code?**
+
+* Ask any question about how to use the repository in the [TheAlgorithms room in GITTER](https://gitter.im/TheAlgorithms/community?source=orgpage#) or [open a new one issue](https://github.com/TheAlgorithms/Java/issues/new)
+
+:+1::tada: That's all you need to know about the process now it's your turn to help us improve the repository, thank you again! :+1::tada:
From 91b9ac759cff34e85e02ae17014bc55ab788cd4c Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Mon, 25 May 2020 11:36:04 +0000
Subject: [PATCH 0127/2014] updating DIRECTORY.md
---
DIRECTORY.md | 2 --
1 file changed, 2 deletions(-)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index aee8eea6f2a2..d8a5165f015c 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -45,9 +45,7 @@
* HashMap
* Hashing
* [HashMap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/HashMap.java)
- * [LinkedList](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/LinkedList.java)
* [Main](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Main.java)
- * [Node](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/HashMap/Hashing/Node.java)
* Heaps
* [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/EmptyHeapException.java)
* [Heap](https://github.com/TheAlgorithms/Java/blob/master/DataStructures/Heaps/Heap.java)
From 8b6415f9b3c02ba3243061fd7637c581dcd4171e Mon Sep 17 00:00:00 2001
From: Sombit Bose
Date: Mon, 25 May 2020 23:59:48 +0530
Subject: [PATCH 0128/2014] Update CONTRIBUTION.md
Added some issue related to assignment of any particular algorithm
---
CONTRIBUTING.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 62f268c98f18..92a2dbf3e104 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,6 +6,8 @@
* **Ensure the bug was not already reported** by searching on GitHub under [Project Issues](https://github.com/TheAlgorithms/Java/issues).
+* Please avoid opening issues asking to be "assigned” to a particular algorithm. This merely creates unnecessary noise for maintainers. Instead, please submit your implementation in a pull request and it will be evaluated by project maintainers.
+
* If you are unable to find an open issue refering to the same problem, depending on the type of issue follow the appropriate steps:
#### **Do you want to contribute to the documentation?**
From 3b52109fc0d0ec43cbd21eecba0892353edac37a Mon Sep 17 00:00:00 2001
From: joshiujjawal22
Date: Fri, 29 May 2020 12:32:24 +0530
Subject: [PATCH 0129/2014] Added test cases
---
Others/3 sum.java | 14 ++++++++++++-
...on of array without using extra space.java | 21 +++++++++++++++++++
2 files changed, 34 insertions(+), 1 deletion(-)
diff --git a/Others/3 sum.java b/Others/3 sum.java
index 3c008ff78360..577044aab1d2 100644
--- a/Others/3 sum.java
+++ b/Others/3 sum.java
@@ -11,6 +11,18 @@
*
* @author Ujjawal Joshi
* @date 2020.05.18
+ *
+ * Test Cases:
+ Input:
+ * 6 //Length of array
+ 12 3 4 1 6 9
+ target=24
+ * Output:3 9 12
+ * Explanation: There is a triplet (12, 3 and 9) present
+ in the array whose sum is 24.
+ *
+ *
+
*/
@@ -26,7 +38,7 @@ public static void main(String args[])
{
a[i]=sc.nextInt();
}
- System.out.println("Number to be find");
+ System.out.println("Target");
int n_find=sc.nextInt();
Arrays.sort(a); // Sort the array if array is not sorted
diff --git a/Others/Rotation of array without using extra space.java b/Others/Rotation of array without using extra space.java
index c25dbaefc8c9..76380be37300 100644
--- a/Others/Rotation of array without using extra space.java
+++ b/Others/Rotation of array without using extra space.java
@@ -8,6 +8,27 @@
*
* @author Ujjawal Joshi
* @date 2020.05.18
+ *
+ * Test Cases:
+
+ Input:
+ 2 //Size of matrix
+ 1 2
+ 3 4
+ Output:
+ 3 1
+ 4 2
+ ------------------------------
+ Input:
+ 3 //Size of matrix
+ 1 2 3
+ 4 5 6
+ 7 8 9
+ Output:
+ 7 4 1
+ 8 5 2
+ 9 6 3
+ *
*/
class main{
From a6398d1d27c897009dbe55a057b6cfd81ee0da21 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Fri, 29 May 2020 10:17:28 +0000
Subject: [PATCH 0130/2014] updating DIRECTORY.md
---
DIRECTORY.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index d8a5165f015c..a4738bcc0b69 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -137,6 +137,7 @@
* [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/Misc/PalindromePrime.java)
## Others
+ * [3 sum](https://github.com/TheAlgorithms/Java/blob/master/Others/3%20sum.java)
* [Abecedarian](https://github.com/TheAlgorithms/Java/blob/master/Others/Abecedarian.java)
* [Armstrong](https://github.com/TheAlgorithms/Java/blob/master/Others/Armstrong.java)
* [BestFit](https://github.com/TheAlgorithms/Java/blob/master/Others/BestFit.java)
@@ -167,6 +168,7 @@
* [ReverseStackUsingRecursion](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseStackUsingRecursion.java)
* [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/Others/ReverseString.java)
* [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/Others/RootPrecision.java)
+ * [Rotation of array without using extra space](https://github.com/TheAlgorithms/Java/blob/master/Others/Rotation%20of%20array%20without%20using%20extra%20space.java)
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/Others/SieveOfEratosthenes.java)
* [SJF](https://github.com/TheAlgorithms/Java/blob/master/Others/SJF.java)
* [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/Others/SkylineProblem.java)
From e3a78a64000c1974a84287ac3129dd99857ecb19 Mon Sep 17 00:00:00 2001
From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
Date: Mon, 1 Jun 2020 04:39:59 +0000
Subject: [PATCH 0131/2014] updating DIRECTORY.md
---
DIRECTORY.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index a4738bcc0b69..13651165369d 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -193,6 +193,7 @@
* [BitonicSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BitonicSort.java)
* [BogoSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BogoSort.java)
* [BubbleSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BubbleSort.java)
+ * [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/BucketSort.java)
* [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CocktailShakerSort.java)
* [CombSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CombSort.java)
* [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/Sorts/CountingSort.java)
From b1caf8c6aea2bab16ce0117b8941b64b6834dde8 Mon Sep 17 00:00:00 2001
From: Swati Prajapati <42577922+swatiprajapati08@users.noreply.github.com>
Date: Mon, 1 Jun 2020 23:41:32 +0530
Subject: [PATCH 0132/2014] Minimum sum partition
Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.
---
DynamicProgramming/Minimum sum partition | 64 ++++++++++++++++++++++++
1 file changed, 64 insertions(+)
create mode 100644 DynamicProgramming/Minimum sum partition
diff --git a/DynamicProgramming/Minimum sum partition b/DynamicProgramming/Minimum sum partition
new file mode 100644
index 000000000000..2ab1d134cad2
--- /dev/null
+++ b/DynamicProgramming/Minimum sum partition
@@ -0,0 +1,64 @@
+// Partition a set into two subsets such that the difference of subset sums is minimum
+
+import java.util.*;
+import java.lang.*;
+import java.io.*;
+class GFG
+ {
+ public static void main (String[] args)
+ {
+ Scanner sc=new Scanner(System.in);
+ int t=sc.nextInt();
+ while(t-->0)
+ {
+ int n=sc.nextInt();
+ int arr[]=new int[n];
+ int sum=0;
+ for(int i=0;i
Date: Wed, 3 Jun 2020 15:19:55 +0530
Subject: [PATCH 0133/2014] Update Minimum sum partition
Added some test cases for better understanding.
---
DynamicProgramming/Minimum sum partition | 14 ++++++++++++++
1 file changed, 14 insertions(+)
diff --git a/DynamicProgramming/Minimum sum partition b/DynamicProgramming/Minimum sum partition
index 2ab1d134cad2..3763d5bd68a8 100644
--- a/DynamicProgramming/Minimum sum partition
+++ b/DynamicProgramming/Minimum sum partition
@@ -1,5 +1,19 @@
// Partition a set into two subsets such that the difference of subset sums is minimum
+/*
+Input: arr[] = {1, 6, 11, 5}
+Output: 1
+Explanation:
+Subset1 = {1, 5, 6}, sum of Subset1 = 12
+Subset2 = {11}, sum of Subset2 = 11
+
+Input: arr[] = {36, 7, 46, 40}
+Output: 23
+Explanation:
+Subset1 = {7, 46} ; sum of Subset1 = 53
+Subset2 = {36, 40} ; sum of Subset2 = 76
+ */
+
import java.util.*;
import java.lang.*;
import java.io.*;
From 7179718df290ccf0ecaaab044508aa309ffada8b Mon Sep 17 00:00:00 2001
From: lollerfirst <43107113+lollerfirst@users.noreply.github.com>
Date: Tue, 9 Jun 2020 08:40:46 +0200
Subject: [PATCH 0134/2014] Update ParseInteger.java
Fixed error for empty string.
---
Maths/ParseInteger.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/Maths/ParseInteger.java b/Maths/ParseInteger.java
index 91177bb49dd6..c9c11528c1dc 100644
--- a/Maths/ParseInteger.java
+++ b/Maths/ParseInteger.java
@@ -16,7 +16,7 @@ public static void main(String[] args) {
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
*/
public static int parseInt(String s) {
- if (s == null) {
+ if (s == null || s.length() == 0) {
throw new NumberFormatException("null");
}
boolean isNegative = s.charAt(0) == '-';
From 15536392f93d1c24d47c191ac1b67e0442666f23 Mon Sep 17 00:00:00 2001
From: MarcosVillacanas
Date: Fri, 12 Jun 2020 13:16:52 +0200
Subject: [PATCH 0135/2014] marcosvillacanas-A-Star
---
DataStructures/Graphs/A_Star.java | 158 ++++++++++++++++++++++++++++++
1 file changed, 158 insertions(+)
create mode 100644 DataStructures/Graphs/A_Star.java
diff --git a/DataStructures/Graphs/A_Star.java b/DataStructures/Graphs/A_Star.java
new file mode 100644
index 000000000000..59ebd7aa5993
--- /dev/null
+++ b/DataStructures/Graphs/A_Star.java
@@ -0,0 +1,158 @@
+package A_Star;
+
+import java.util.*;
+
+public class A_Star {
+
+ private static class Graph {
+ //Graph's structure can be changed only applying changes to this class.
+ private ArrayList [] graph;
+
+ //Initialise ArrayLists in Constructor
+ public Graph(int size) {
+ this.graph = new ArrayList[size];
+ for (int i = 0; i < size; i++) {
+ this.graph[i] = new ArrayList<>();
+ }
+ }
+
+ private ArrayList