Date: Tue, 29 Oct 2019 12:40:39 +0800
Subject: [PATCH 0079/1800] 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 0080/1800] 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 0081/1800] 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 0082/1800] 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 0083/1800] 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 0084/1800] 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 0085/1800] 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 0086/1800] 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 0087/1800] 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 0088/1800] 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 0089/1800] 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 0090/1800] 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 0091/1800] 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 0092/1800] 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 0093/1800] 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 0094/1800] 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 0095/1800] 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 0096/1800] 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 0097/1800] 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 0098/1800] 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 0099/1800] 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 0100/1800] 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 0101/1800] 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 0102/1800] 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 0103/1800] 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 0104/1800] 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 0105/1800] 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 0106/1800] 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 0107/1800] 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 0108/1800] 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 0109/1800] 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 0110/1800] 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 0111/1800] 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 0112/1800] 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 0113/1800] 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 0114/1800] 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 0115/1800] 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 0116/1800] 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 0117/1800] 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 0118/1800] 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 0119/1800] 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 0120/1800] 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 0121/1800] 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 0122/1800] 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 0123/1800] 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 0124/1800] 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 0125/1800] 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 0126/1800] 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 0127/1800] 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 0128/1800] 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 0129/1800] 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 0130/1800] 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 0131/1800] 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 0132/1800] 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 0133/1800] 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 0134/1800] 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 0135/1800] 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 0136/1800] 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 0137/1800] 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 0138/1800] 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 0139/1800] 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 0140/1800] 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 0141/1800] 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 0142/1800] 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 0143/1800] 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 0144/1800] 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 0145/1800] 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 0146/1800] 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 0147/1800] 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