From 77bcd4daa3c932fec3cb49fa032bdf5f17bce48d Mon Sep 17 00:00:00 2001
From: funCodeSonali <90191207+funCodeSonali@users.noreply.github.com>
Date: Sun, 3 Apr 2022 18:41:43 +0530
Subject: [PATCH 0001/1577] Fix singly linked list (#2988)
---
pom.xml | 8 +
.../lists/SinglyLinkedList.java | 274 +++++++++---------
2 files changed, 139 insertions(+), 143 deletions(-)
diff --git a/pom.xml b/pom.xml
index 48f9e1cbbbc6..571c14060f33 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,6 +43,14 @@
maven-surefire-plugin2.22.2
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 16
+ 16
+
+
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index fb33e6e6ecf7..0ab65b8496b8 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -44,16 +44,14 @@ public SinglyLinkedList(Node head, int size) {
public boolean detectLoop() {
Node currentNodeFast = head;
Node currentNodeSlow = head;
- boolean flag = false;
- while (currentNodeFast != null && currentNodeFast.next != null && currentNodeSlow != null && currentNodeSlow.next != null) {
+ while (currentNodeFast != null && currentNodeFast.next != null) {
currentNodeFast = currentNodeFast.next.next;
currentNodeSlow = currentNodeSlow.next;
if (currentNodeFast == currentNodeSlow) {
- flag = true;
- break;
+ return true;
}
}
- return flag;
+ return false;
}
/**
@@ -84,7 +82,7 @@ public void swapNodes(int valueFirst, int valueSecond) {
if(previousA != null){
previousA.next = currentB;
}
- else{
+ else{
// make 'b' as the new head
head = currentB;
}
@@ -98,7 +96,7 @@ public void swapNodes(int valueFirst, int valueSecond) {
head = currentA;
}
// Swap next pointer
-
+
Node temp = currentA.next;
currentA.next = currentB.next;
currentB.next = temp;
@@ -109,6 +107,10 @@ public void swapNodes(int valueFirst, int valueSecond) {
*
*/
Node reverseList(Node node) {
+ Node prevNode = head;
+ while(prevNode.next!=node){
+ prevNode = prevNode.next;
+ }
Node prev = null, curr = node, next;
while (curr != null) {
next = curr.next;
@@ -116,8 +118,8 @@ Node reverseList(Node node) {
prev = curr;
curr = next;
}
- node = prev;
- return node;
+ prevNode.next = prev;
+ return head;
}
/**
@@ -161,6 +163,14 @@ public Node getHead() {
return head;
}
+ /**
+ * Set head of the list.
+ *
+ */
+ public void setHead(Node head) {
+ this.head = head;
+ }
+
/**
* Calculate the count of the list manually
*
@@ -205,138 +215,33 @@ public String toString() {
return joiner.toString();
}
- /**
- * Driver Code
- */
- public static void main(String[] arg) {
- SinglyLinkedList list = new SinglyLinkedList();
- assert list.isEmpty();
- assert list.size() == 0 && list.count() == 0;
- assert list.toString().equals("");
-
- /* Test insert function */
- list.insertHead(5);
- list.insertHead(7);
- list.insertHead(10);
- list.insert(3);
- list.insertNth(1, 4);
- assert list.toString().equals("10->7->5->3->1");
-
- /* Test search function */
- assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
-
- /* Test get function */
- assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
-
- /* Test delete function */
- list.deleteHead();
- list.deleteNth(1);
- list.delete();
- assert list.toString().equals("7->3");
-
- assert list.size == 2 && list.size() == list.count();
-
- list.clear();
- assert list.isEmpty();
-
- try {
- list.delete();
- assert false;
- /* this should not happen */
- } catch (Exception e) {
- assert true;
- /* this should happen */
- }
-
- Node instance = new Node();
- Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
- head = instance.deleteDuplicates(head);
- instance.print(head);
-
- }
-}
-
-/**
- * This class is the nodes of the SinglyLinked List. They consist of a value and
- * a pointer to the node after them.
- */
-class Node {
-
- /**
- * Head refer to the front of the list
- */
- public Node head;
-
- /**
- * Size of SinglyLinkedList
- */
- public int size;
-
-
-
- /**
- * The value of the node
- */
- int value;
-
- /**
- * Point to the next node
- */
- Node next;
-
- Node() {
- }
-
- /**
- * Constructor
- *
- * @param value Value to be put in the node
- */
- Node(int value) {
- this(value, null);
- }
+ public void deleteDuplicates() {
- /**
- * Constructor
- *
- * @param value Value to be put in the node
- * @param next Reference to the next node
- */
- Node(int value, Node next) {
- this.value = value;
- this.next = next;
- }
-
- public Node deleteDuplicates(Node head) {
- // sentinel
- Node sentinel = new Node(0, head);
-
- // predecessor = the last node
- // before the sublist of duplicates
- Node pred = sentinel;
-
- while (head != null) {
+ Node pred = head;
+ // predecessor = the node
+ // having sublist of its duplicates
+ Node newHead = head;
+ while (newHead != null) {
// if it's a beginning of duplicates sublist
// skip all duplicates
- if (head.next != null && head.value == head.next.value) {
+ if (newHead.next != null && newHead.value == newHead.next.value) {
// move till the end of duplicates sublist
- while (head.next != null && head.value == head.next.value) {
- head = head.next;
+ while (newHead.next != null && newHead.value == newHead.next.value) {
+ newHead = newHead.next;
}
// skip all duplicates
- pred.next = head.next;
+ pred.next = newHead.next;
+ newHead = null;
+
// otherwise, move predecessor
- } else {
- pred = pred.next;
}
-
// move forward
- head = head.next;
+ pred = pred.next;
+ newHead = pred;
}
- return sentinel.next;
}
- public void print(Node head) {
+ public void print() {
Node temp = head;
while (temp != null && temp.next != null) {
System.out.print(temp.value + "->");
@@ -344,6 +249,7 @@ public void print(Node head) {
}
if (temp != null) {
System.out.print(temp.value);
+ System.out.println();
}
}
@@ -379,13 +285,15 @@ public void insertNth(int data, int position) {
head = newNode;
size++;
return;
- } else if (position == 0) {
+ }
+ if (position == 0) {
/* insert at the head of the list */
newNode.next = head;
head = newNode;
size++;
return;
}
+
Node cur = head;
for (int i = 0; i < position - 1; ++i) {
cur = cur.next;
@@ -393,25 +301,13 @@ public void insertNth(int data, int position) {
newNode.next = cur.next;
cur.next = newNode;
size++;
+
}
/**
* Swaps nodes of two given values a and b.
*
*/
- public void swapNodes(int a, int b) {
- Node currentNode = head;
- Node temp = null;
- while (currentNode != null) {
- if (currentNode.next.value == a) {
- temp = currentNode.next;
- }
- if (currentNode.next.value == b) {
- currentNode.next = temp;
- }
- currentNode = currentNode.next;
- }
- }
/**
* Deletes a node at the head
@@ -479,4 +375,96 @@ public void checkBounds(int position, int low, int high) {
throw new IndexOutOfBoundsException(position + "");
}
}
+ /**
+ * Driver Code
+ */
+ public static void main(String[] arg) {
+ SinglyLinkedList list = new SinglyLinkedList();
+ assert list.isEmpty();
+ assert list.size() == 0 && list.count() == 0;
+ assert list.toString().equals("");
+
+ /* Test insert function */
+ list.insertHead(5);
+ list.insertHead(7);
+ list.insertHead(10);
+ list.insert(3);
+ list.insertNth(1, 4);
+ assert list.toString().equals("10->7->5->3->1");
+ System.out.println(list.toString());
+ /* Test search function */
+ assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
+
+ /* Test get function */
+ assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
+
+ /* Test delete function */
+ list.deleteHead();
+ list.deleteNth(1);
+ list.delete();
+ assert list.toString().equals("7->3");
+ System.out.println(list.toString());
+ assert list.size == 2 && list.size() == list.count();
+
+ list.clear();
+ assert list.isEmpty();
+
+ try {
+ list.delete();
+ assert false;
+ /* this should not happen */
+ } catch (Exception e) {
+ assert true;
+ /* this should happen */
+ }
+
+ SinglyLinkedList instance = new SinglyLinkedList();
+ Node head = new Node(0, new Node(2, new Node(3, new Node(3, new Node(4)))));
+ instance.setHead(head);
+ instance.deleteDuplicates();
+ instance.print();
+
+ }
+
+}
+
+/**
+ * This class is the nodes of the SinglyLinked List. They consist of a value and
+ * a pointer to the node after them.
+ */
+class Node {
+
+ /**
+ * The value of the node
+ */
+ int value;
+
+ /**
+ * Point to the next node
+ */
+ Node next;
+
+ Node() {
+ }
+
+ /**
+ * Constructor
+ *
+ * @param value Value to be put in the node
+ */
+ Node(int value) {
+ this(value, null);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param value Value to be put in the node
+ * @param next Reference to the next node
+ */
+ Node(int value, Node next) {
+ this.value = value;
+ this.next = next;
+ }
+
}
From 1b02b41fcc20ada8db2d41cff34177c27514170b Mon Sep 17 00:00:00 2001
From: Aldo Telese <63289653+aldotele@users.noreply.github.com>
Date: Sun, 3 Apr 2022 15:19:24 +0200
Subject: [PATCH 0002/1577] Add test for Palindrome (#2993)
---
.../thealgorithms/strings/PalindromeTest.java | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/strings/PalindromeTest.java
diff --git a/src/test/java/com/thealgorithms/strings/PalindromeTest.java b/src/test/java/com/thealgorithms/strings/PalindromeTest.java
new file mode 100644
index 000000000000..6ae1a9133714
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/PalindromeTest.java
@@ -0,0 +1,18 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class PalindromeTest {
+ @Test
+ public void palindrome() {
+ String input1 = "kayak";
+ String input2 = "kayaks";
+ Assertions.assertTrue(Palindrome.isPalindrome(input1));
+ Assertions.assertFalse(Palindrome.isPalindrome(input2));
+ Assertions.assertTrue(Palindrome.isPalindromeRecursion(input1));
+ Assertions.assertFalse(Palindrome.isPalindromeRecursion(input2));
+ Assertions.assertTrue(Palindrome.isPalindrome1(input1));
+ Assertions.assertFalse(Palindrome.isPalindrome1(input2));
+ }
+}
From 140f6ec6e390a3ca4e84276c010736e93fdc6a39 Mon Sep 17 00:00:00 2001
From: Aldo Telese <63289653+aldotele@users.noreply.github.com>
Date: Mon, 4 Apr 2022 10:21:53 +0200
Subject: [PATCH 0003/1577] Add test for Upper (#3001)
---
.../com/thealgorithms/strings/UpperTest.java | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/strings/UpperTest.java
diff --git a/src/test/java/com/thealgorithms/strings/UpperTest.java b/src/test/java/com/thealgorithms/strings/UpperTest.java
new file mode 100644
index 000000000000..542b175c94bf
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/UpperTest.java
@@ -0,0 +1,17 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class UpperTest {
+ @Test
+ public void toUpperCase() {
+ String input1 = "hello world";
+ String input2 = "hElLo WoRlD";
+ String input3 = "HELLO WORLD";
+ assertEquals("HELLO WORLD", Upper.toUpperCase(input1));
+ assertEquals("HELLO WORLD", Upper.toUpperCase(input2));
+ assertEquals("HELLO WORLD", Upper.toUpperCase(input3));
+ }
+}
From 8d099ee7d1776cc6c146c06995a7ce11eee989f1 Mon Sep 17 00:00:00 2001
From: Aldo Telese <63289653+aldotele@users.noreply.github.com>
Date: Mon, 4 Apr 2022 10:34:27 +0200
Subject: [PATCH 0004/1577] Update Anagrams and add unit test (#3002)
* Add test for Anagrams
* Update Anagrams.java
Co-authored-by: Yang Libin
---
.../com/thealgorithms/strings/Anagrams.java | 136 ++++++++----------
.../thealgorithms/strings/AnagramsTest.java | 21 +++
2 files changed, 77 insertions(+), 80 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/strings/AnagramsTest.java
diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java
index f76db06c4d58..7ab6b1277624 100644
--- a/src/main/java/com/thealgorithms/strings/Anagrams.java
+++ b/src/main/java/com/thealgorithms/strings/Anagrams.java
@@ -1,21 +1,23 @@
-/** Author : Siddhant Swarup Mallick
- * Github : https://github.com/siddhant2002
- */
+package com.thealgorithms.strings;
-/** PROBLEM DESCRIPTION :
- * An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.[1] For example, the word anagram itself can be rearranged into nag a ram, also the word binary into brainy and the word adobe into abode. Reference from https://en.wikipedia.org/wiki/Anagram
- */
+import java.util.Arrays;
+import java.util.HashMap;
-package com.thealgorithms.strings;
-import java.util.*;
-public class Anagrams
-{
+
+/**
+ * An anagram is a word or phrase formed by rearranging the letters of a different word or phrase,
+ * typically using all the original letters exactly once.[1]
+ * For example, the word anagram itself can be rearranged into nag a ram,
+ * also the word binary into brainy and the word adobe into abode.
+ * Reference from https://en.wikipedia.org/wiki/Anagram
+ */
+public class Anagrams {
// 4 approaches are provided for anagram checking. approach 2 and approach 3 are similar but differ in running time.
- public static void main(String args[]) {
+ public static void main(String[] args) {
String first = "deal";
String second = "lead";
// All the below methods takes input but doesn't return any output to the main method.
- Anagrams nm=new Anagrams();
+ Anagrams nm = new Anagrams();
System.out.println(nm.approach2(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach1(first, second)); /* To activate methods for different approaches*/
System.out.println(nm.approach3(first, second)); /* To activate methods for different approaches*/
@@ -37,52 +39,38 @@ public static void main(String args[]) {
*/
}
- boolean approach1(String s, String t)
- {
- if (s.length() != t.length())
- {
+ boolean approach1(String s, String t) {
+ if (s.length() != t.length()) {
return false;
- }
- else
- {
+ } else {
char c[] = s.toCharArray();
char d[] = t.toCharArray();
Arrays.sort(c);
Arrays.sort(d); /* In this approach the strings are stored in the character arrays and both the arrays are sorted. After that both the arrays are compared for checking anangram */
- if (Arrays.equals(c, d))
- {
+ if (Arrays.equals(c, d)) {
return true;
- } else
- {
+ } else {
return false;
}
}
}
- boolean approach2(String a, String b)
- {
- if(a.length()!=b.length())
- {
+ boolean approach2(String a, String b) {
+ if (a.length() != b.length()) {
return false;
- }
- else
- {
- int m[]=new int[26];
- int n[]=new int[26];
- for(char c: a.toCharArray())
- {
- m[c-'a']++;
+ } else {
+ int m[] = new int[26];
+ int n[] = new int[26];
+ for (char c : a.toCharArray()) {
+ m[c - 'a']++;
}
// In this approach the frequency of both the strings are stored and after that the frequencies are iterated from 0 to 26(from 'a' to 'z' ). If the frequencies match then anagram message is displayed in the form of boolean format
// Running time and space complexity of this algo is less as compared to others
- for(char c:b.toCharArray())
- {
- n[c-'a']++;
+ for (char c : b.toCharArray()) {
+ n[c - 'a']++;
}
- for(int i=0;i<26;i++)
- {
- if(m[i]!=n[i])
- {
+ for (int i = 0; i < 26; i++) {
+ if (m[i] != n[i]) {
return false;
}
}
@@ -90,61 +78,49 @@ boolean approach2(String a, String b)
}
}
- boolean approach3(String s, String t)
- {
- if(s.length()!=t.length())
- {
+ boolean approach3(String s, String t) {
+ if (s.length() != t.length()) {
return false;
}
// this is similar to approach number 2 but here the string is not converted to character array
- else
- {
- int a[]=new int[26];
- int b[]=new int[26];
- int k=s.length();
- for(int i=0;i nm=new HashMap<>();
- HashMap kk=new HashMap<>();
- for(char c: s.toCharArray())
- {
- nm.put(c, nm.getOrDefault(c,0)+1);
+ else {
+ HashMap nm = new HashMap<>();
+ HashMap kk = new HashMap<>();
+ for (char c : s.toCharArray()) {
+ nm.put(c, nm.getOrDefault(c, 0) + 1);
}
- for(char c: t.toCharArray())
- {
-
- kk.put(c, kk.getOrDefault(c,0)+1);
+ for (char c : t.toCharArray()) {
+
+ kk.put(c, kk.getOrDefault(c, 0) + 1);
}
// It checks for equal frequencies
- for(char c:nm.keySet())
- {
- if(!nm.get(c).equals(kk.get(c)))
- {
+ for (char c : nm.keySet()) {
+ if (!nm.get(c).equals(kk.get(c))) {
return false;
}
- }
+ }
return true;
}
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/com/thealgorithms/strings/AnagramsTest.java b/src/test/java/com/thealgorithms/strings/AnagramsTest.java
new file mode 100644
index 000000000000..36b337e5e9ba
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/AnagramsTest.java
@@ -0,0 +1,21 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class AnagramsTest {
+ @Test
+ public void isAlphabetical() {
+ String input1 = "late";
+ Anagrams anagrams = new Anagrams();
+ assertTrue(anagrams.approach1(input1, "tale"));
+ assertTrue(anagrams.approach1(input1, "teal"));
+ assertTrue(anagrams.approach2(input1, "tale"));
+ assertTrue(anagrams.approach2(input1, "teal"));
+ assertTrue(anagrams.approach3(input1, "tale"));
+ assertTrue(anagrams.approach3(input1, "teal"));
+ assertTrue(anagrams.approach4(input1, "tale"));
+ assertTrue(anagrams.approach4(input1, "teal"));
+ }
+}
From e7ff9864144b9f223e68dc41f0a328ac47c8974c Mon Sep 17 00:00:00 2001
From: acbin <44314231+acbin@users.noreply.github.com>
Date: Mon, 4 Apr 2022 16:44:38 +0800
Subject: [PATCH 0005/1577] Fix CheckVowels (#3004)
Close #2990
---
.../thealgorithms/strings/CheckVowels.java | 43 +++++++------------
1 file changed, 16 insertions(+), 27 deletions(-)
diff --git a/src/main/java/com/thealgorithms/strings/CheckVowels.java b/src/main/java/com/thealgorithms/strings/CheckVowels.java
index 6121812a11a1..a683a5065901 100644
--- a/src/main/java/com/thealgorithms/strings/CheckVowels.java
+++ b/src/main/java/com/thealgorithms/strings/CheckVowels.java
@@ -1,19 +1,16 @@
package com.thealgorithms.strings;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
/**
* Vowel Count is a system whereby character strings are placed in order based
* on the position of the characters in the conventional ordering of an
* alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
*/
-class CheckVowels {
-
- public static void main(String[] args) {
- assert !hasVowels("This is a strings");
- assert hasVowels("Hello World");
- assert hasVowels("Java is fun");
- assert !hasVowels("123hi");
- assert hasVowels("Coding vs Programming");
- }
+public class CheckVowels {
+ private static final Set VOWELS = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
/**
* Check if a string is has vowels or not
@@ -22,11 +19,7 @@ public static void main(String[] args) {
* @return {@code true} if given string has vowels, otherwise {@code false}
*/
public static boolean hasVowels(String input) {
- if (input.matches("[AEIOUaeiou]")) {
- countVowels(input);
- return true;
- }
- return false;
+ return countVowels(input) > 0;
}
/**
@@ -34,20 +27,16 @@ public static boolean hasVowels(String input) {
*
* @param input a string prints the count of vowels
*/
- public static void countVowels(String input) {
- input = input.toLowerCase();
- int count = 0;
- int i = 0;
- while (i < input.length()) {
- if (input.charAt(i) == 'a'
- || input.charAt(i) == 'e'
- || input.charAt(i) == 'i'
- || input.charAt(i) == 'o'
- || input.charAt(i) == 'u') {
- count++;
+ public static int countVowels(String input) {
+ if (input == null) {
+ return 0;
+ }
+ int cnt = 0;
+ for (char c : input.toLowerCase().toCharArray()) {
+ if (VOWELS.contains(c)) {
+ ++cnt;
}
- i++;
}
- System.out.println(count);
+ return cnt;
}
}
From ab544c3b9ff07175c7200ed1cdcfdc756e2c605e Mon Sep 17 00:00:00 2001
From: acbin <44314231+acbin@users.noreply.github.com>
Date: Tue, 5 Apr 2022 17:02:20 +0800
Subject: [PATCH 0006/1577] Fix Null Pointer Exception in strings/Upper (#3005)
Co-authored-by: Yang Libin
---
src/main/java/com/thealgorithms/strings/Upper.java | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/main/java/com/thealgorithms/strings/Upper.java b/src/main/java/com/thealgorithms/strings/Upper.java
index 102d3a190a72..8f306a20e8f0 100644
--- a/src/main/java/com/thealgorithms/strings/Upper.java
+++ b/src/main/java/com/thealgorithms/strings/Upper.java
@@ -19,6 +19,9 @@ public static void main(String[] args) {
* @return the {@code String}, converted to uppercase.
*/
public static String toUpperCase(String s) {
+ if (s == null || "".equals(s)) {
+ return s;
+ }
char[] values = s.toCharArray();
for (int i = 0; i < values.length; ++i) {
if (Character.isLetter(values[i]) && Character.isLowerCase(values[i])) {
From 060069cf732ce8e47088d4fb4d615e9f12c1cf26 Mon Sep 17 00:00:00 2001
From: Siddhant Swarup Mallick <78552027+siddhant2002@users.noreply.github.com>
Date: Wed, 6 Apr 2022 21:32:30 +0530
Subject: [PATCH 0007/1577] Add Golomb Sequence (fixes #2889) (#2991)
---
.../CountFriendsPairing.java | 35 +++++++++++
.../others/CountFriendsPairingTest.java | 62 +++++++++++++++++++
2 files changed, 97 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
create mode 100644 src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
new file mode 100644
index 000000000000..a5d069391dfb
--- /dev/null
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
@@ -0,0 +1,35 @@
+/** Author : Siddhant Swarup Mallick
+ * Github : https://github.com/siddhant2002
+ */
+/**
+ * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal to number of times n appears in the sequence.
+ */
+
+/**
+ * Wikipedia Link - https://en.wikipedia.org/wiki/Golomb_sequence
+ */
+
+/** Program description - To find the Golomb sequence upto n */
+
+package com.thealgorithms.dynamicprogramming;
+
+public class CountFriendsPairing {
+ public static boolean countFriendsPairing(int n, int a[]) {
+ int dp[] = new int[n + 1];
+ // array of n+1 size is created
+ dp[0] = 1;
+ // since 1st index position value is fixed so it's marked as 1
+ for (int i = 1; i < n; i++) {
+ dp[i] = 1 + dp[i - dp[dp[i - 1]]];
+ // formula for ith golomb sequence is dp(i) = 1 + dp(i – dp(dp(i - 1)))
+ }
+ for (int i = 1; i < n; i++) {
+ if (a[i - 1] != dp[i]) {
+ return false;
+ // checks whether the calculated answer matches with the expected answer
+ }
+ }
+ return true;
+ // returns true if calculated answer matches with the expected answer
+ }
+}
diff --git a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
new file mode 100644
index 000000000000..1e1d2111240e
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
@@ -0,0 +1,62 @@
+package com.thealgorithms.others;
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+import com.thealgorithms.dynamicprogramming.CountFriendsPairing;
+public class CountFriendsPairingTest {
+ @Test
+ void testForOneElement()
+ {
+ int a[] = {1,2,2};
+ assertTrue(CountFriendsPairing.countFriendsPairing(3,a));
+ }
+
+ @Test
+ void testForTwoElements()
+ {
+ int a[] = {1,2,2,3};
+ assertTrue(CountFriendsPairing.countFriendsPairing(4,a));
+ }
+
+ @Test
+ void testForThreeElements()
+ {
+ int a[] = {1,2,2,3,3};
+ assertTrue(CountFriendsPairing.countFriendsPairing(5,a));
+ }
+
+ @Test
+ void testForFourElements()
+ {
+ int a[] = {1,2,2,3,3,4};
+ assertTrue(CountFriendsPairing.countFriendsPairing(6,a));
+ }
+
+ @Test
+ void testForFiveElements()
+ {
+ int a[] = {1,2,2,3,3,4,4};
+ assertTrue(CountFriendsPairing.countFriendsPairing(7,a));
+ }
+
+ @Test
+ void testForSixElements()
+ {
+ int a[] = {1,2,2,3,3,4,4,4};
+ assertTrue(CountFriendsPairing.countFriendsPairing(8,a));
+ }
+
+ @Test
+ void testForSevenElements()
+ {
+ int a[] = {1,2,2,3,3,4,4,4,5};
+ assertTrue(CountFriendsPairing.countFriendsPairing(9,a));
+ }
+
+ @Test
+ void testForEightElements()
+ {
+ int a[] = {1,2,2,3,3,4,4,4,5,5};
+ assertTrue(CountFriendsPairing.countFriendsPairing(10,a));
+ }
+}
\ No newline at end of file
From cca403800821bded04e663722acefb54bb2cde5d Mon Sep 17 00:00:00 2001
From: Eduardo Cabral <47820549+FerroEduardo@users.noreply.github.com>
Date: Thu, 7 Apr 2022 14:49:44 -0300
Subject: [PATCH 0008/1577] Run actions only if code related files changes
(#3000)
---
.github/workflows/build.yml | 14 +++++++++++++-
.github/workflows/prettify.yml | 14 +++++++++++++-
.github/workflows/update_directory.yml | 14 +++++++++++++-
3 files changed, 39 insertions(+), 3 deletions(-)
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 7e3feabdd260..efd76cc7eb79 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -1,5 +1,17 @@
name: Build
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
+ pull_request:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
jobs:
build:
runs-on: ubuntu-latest
diff --git a/.github/workflows/prettify.yml b/.github/workflows/prettify.yml
index da58f5f06379..a5d7c318f564 100644
--- a/.github/workflows/prettify.yml
+++ b/.github/workflows/prettify.yml
@@ -1,5 +1,17 @@
name: Prettify
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
+ pull_request:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
jobs:
prettier:
runs-on: ubuntu-latest
diff --git a/.github/workflows/update_directory.yml b/.github/workflows/update_directory.yml
index 0a9265c5d801..90a90f490efd 100644
--- a/.github/workflows/update_directory.yml
+++ b/.github/workflows/update_directory.yml
@@ -1,6 +1,18 @@
# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push
name: Update Directory
-on: [push, pull_request]
+on:
+ push:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
+ pull_request:
+ paths:
+ - 'src/**'
+ - '**.yml'
+ - '**.xml'
+ - '**.Dockerfile'
jobs:
update_directory_md:
runs-on: ubuntu-latest
From 719e1d8132f1aeea3e7ab2eb7ec86270a30d68df Mon Sep 17 00:00:00 2001
From: Vivek
Date: Sun, 10 Apr 2022 19:41:05 +0530
Subject: [PATCH 0009/1577] Update Armstrong Number (#2981)
---
DIRECTORY.md | 68 +++++++++++--------
pom.xml | 7 ++
.../com/thealgorithms/maths/Armstrong.java | 39 +++--------
.../thealgorithms/maths/ArmstrongTest.java | 23 +++++++
4 files changed, 81 insertions(+), 56 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/ArmstrongTest.java
diff --git a/DIRECTORY.md b/DIRECTORY.md
index aebc14852b14..5b3ee19d0eee 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -8,6 +8,7 @@
* [IIRFilter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java)
* backtracking
* [Combination](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Combination.java)
+ * [FloodFill](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/FloodFill.java)
* [KnightsTour](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/KnightsTour.java)
* [NQueens](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/NQueens.java)
* [Permutation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Permutation.java)
@@ -93,7 +94,6 @@
* [MergeSortedArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java)
* [MergeSortedSinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java)
* [RandomNode](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java)
- * [RemoveDuplicateNodes](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/RemoveDuplicateNodes.java)
* [SearchSinglyLinkedListRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java)
* [SinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java)
* queues
@@ -108,15 +108,18 @@
* [DecimalToAnyUsingStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/DecimalToAnyUsingStack.java)
* [DuplicateBrackets](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/DuplicateBrackets.java)
* [InfixToPostfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/InfixToPostfix.java)
+ * [LargestRectangle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/LargestRectangle.java)
* [MaximumMinimumWindow](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java)
* [NextGraterElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/NextGraterElement.java)
* [NextSmallerElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/NextSmallerElement.java)
* [NodeStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java)
+ * [PostfixToInfix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java)
* [ReverseStack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java)
* [StackArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java)
* [StackArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackArrayList.java)
* [StackOfLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java)
* trees
+ * [AVLSimple](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java)
* [AVLTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java)
* [BinaryTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java)
* [BSTIterative](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java)
@@ -160,12 +163,12 @@
* [BruteForceKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java)
* [CatalanNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java)
* [CoinChange](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java)
+ * [CountFriendsPairing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java)
* [DiceThrow](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java)
* [DyanamicProgrammingKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java)
* [EditDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java)
* [EggDropping](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java)
* [Fibonacci](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java)
- * [FloodFill](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/FloodFill.java)
* [FordFulkerson](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/FordFulkerson.java)
* [KadaneAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java)
* [Knapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java)
@@ -182,12 +185,14 @@
* [MemoizationTechniqueKnapsack](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/MemoizationTechniqueKnapsack.java)
* [MinimumPathSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java)
* [MinimumSumPartition](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java)
+ * [NewManShanksPrime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java)
* [PalindromicPartitioning](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java)
* [RegexMatching](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java)
* [RodCutting](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java)
* [ShortestCommonSupersequenceLength](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java)
* [SubsetSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java)
* [Sum Of Subset](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/Sum_Of_Subset.java)
+ * [UniquePaths](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java)
* [WineProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java)
* maths
* [AbsoluteMax](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/AbsoluteMax.java)
@@ -217,6 +222,7 @@
* [FFTBluestein](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FFTBluestein.java)
* [FibonacciJavaStreams](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java)
* [FibonacciNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FibonacciNumber.java)
+ * [FindKthNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindKthNumber.java)
* [FindMax](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindMax.java)
* [FindMaxRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java)
* [FindMin](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindMin.java)
@@ -407,29 +413,35 @@
* [Upper](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Upper.java)
* [WordLadder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/WordLadder.java)
* test
- * backtracking
- * [CombinationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/CombinationTest.java)
- * [FloodFillTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java)
- * [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java)
- * maths
- * [FFTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FFTTest.java)
- * [GaussianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GaussianTest.java)
- * [KaprekarNumbersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java)
- * [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java)
- * [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java)
- * [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java)
- * others
- * [ArrayLeftRotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java)
- * [BestFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/BestFitCPUTest.java)
- * [FirstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java)
- * [KadaneAlogrithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java)
- * [LinkList Sort test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkList_Sort_test.java)
- * [NewManShanksPrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java)
- * [NextFitTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NextFitTest.java)
- * [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/UniquePathsTests.java)
- * [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java)
- * searches
- * [QuickSelectTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/QuickSelectTest.java)
- * strings
- * [AlphabeticalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java)
- * [PangramTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PangramTest.java)
+ * backtracking
+ * [CombinationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/CombinationTest.java)
+ * [FloodFillTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java)
+ * [PermutationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/PermutationTest.java)
+ * maths
+ * [ArmstrongTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/ArmstrongTest.java)
+ * [FFTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FFTTest.java)
+ * [GaussianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GaussianTest.java)
+ * [KaprekarNumbersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java)
+ * [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java)
+ * [PronicNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PronicNumberTest.java)
+ * [SquareRootwithBabylonianMethodTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/SquareRootwithBabylonianMethodTest.java)
+ * others
+ * [ArrayLeftRotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java)
+ * [BestFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/BestFitCPUTest.java)
+ * [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
+ * [FirstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java)
+ * [KadaneAlogrithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java)
+ * [LinkList Sort test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkList_Sort_test.java)
+ * [NewManShanksPrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java)
+ * [NextFitTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/NextFitTest.java)
+ * [UniquePathsTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/UniquePathsTests.java)
+ * [WorstFitCPUTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java)
+ * searches
+ * [QuickSelectTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/QuickSelectTest.java)
+ * strings
+ * [AlphabeticalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java)
+ * [AnagramsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AnagramsTest.java)
+ * [CharacterSameTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/CharacterSameTest.java)
+ * [PalindromeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PalindromeTest.java)
+ * [PangramTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/PangramTest.java)
+ * [UpperTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/UpperTest.java)
diff --git a/pom.xml b/pom.xml
index 571c14060f33..56af5539986b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,10 +7,12 @@
Java1.0-SNAPSHOTjar
+
UTF-81717
+ 3.22.0
@@ -31,6 +33,11 @@
junit-jupitertest
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+
diff --git a/src/main/java/com/thealgorithms/maths/Armstrong.java b/src/main/java/com/thealgorithms/maths/Armstrong.java
index df65ba750b01..fa1198ceaea3 100644
--- a/src/main/java/com/thealgorithms/maths/Armstrong.java
+++ b/src/main/java/com/thealgorithms/maths/Armstrong.java
@@ -4,18 +4,11 @@
* An Armstrong number is equal to the sum of the cubes of its digits. For
* example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An
* Armstrong number is often called Narcissistic number.
+ *
+ * @author Vivek
*/
public class Armstrong {
- public static void main(String[] args) {
- assert (isArmStrong(0));
- assert (isArmStrong(1));
- assert (isArmStrong(153));
- assert (isArmStrong(1634));
- assert (isArmStrong(371));
- assert (!isArmStrong(200));
- }
-
/**
* Checks whether a given number is an armstrong number or not.
*
@@ -23,24 +16,14 @@ public static void main(String[] args) {
* @return {@code true} if given number is armstrong number, {@code false}
* otherwise
*/
- private static boolean isArmStrong(int number) {
- int sum = 0;
- int temp = number;
- int numberOfDigits = 0;
- while (temp != 0) {
- numberOfDigits++;
- temp /= 10;
- }
- temp = number;
- /* copy number again */
- while (number > 0) {
- int remainder = number % 10;
- int power = 1;
- for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
- ;
- sum = sum + power;
- number /= 10;
+ public boolean isArmstrong(int number) {
+ long sum = 0;
+ long number2 = number;
+ while (number2 > 0) {
+ long mod = number2 % 10;
+ sum += Math.pow(mod, 3);
+ number2 /= 10;
}
- return sum == temp;
+ return sum == number;
}
-}
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/maths/ArmstrongTest.java b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java
new file mode 100644
index 000000000000..a833e41044f7
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/ArmstrongTest.java
@@ -0,0 +1,23 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Vivek
+ * @since 15/03/22
+ */
+class ArmstrongTest {
+
+ @Test
+ void testIsArmstrong() {
+ Armstrong armstrong = new Armstrong();
+ assertThat(armstrong.isArmstrong(0)).isTrue();
+ assertThat(armstrong.isArmstrong(1)).isTrue();
+ assertThat(armstrong.isArmstrong(153)).isTrue();
+ assertThat(armstrong.isArmstrong(371)).isTrue();
+ assertThat(armstrong.isArmstrong(1634)).isFalse();
+ assertThat(armstrong.isArmstrong(200)).isFalse();
+ }
+}
From 02375e0683b7f7ba28feae686fa7d4aece5a2095 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Wed, 20 Apr 2022 09:12:55 +0100
Subject: [PATCH 0010/1577] Code refactor for AbsoluteMin improvements (#3022)
Fix #3021
---
.../com/thealgorithms/maths/AbsoluteMin.java | 44 +++++++++----------
.../thealgorithms/maths/AbsoluteMinTest.java | 21 +++++++++
2 files changed, 41 insertions(+), 24 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
index bdb8eb1a9740..9b6f0e747d5f 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
@@ -2,35 +2,31 @@
import java.util.Arrays;
-/**
- * description:
- *
- *
- * absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
- */
public class AbsoluteMin {
- public static void main(String[] args) {
- int[] testnums = {4, 0, 16};
- assert absMin(testnums) == 0;
-
- int[] numbers = {3, -10, -2};
- System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
- }
-
/**
- * get the value, returns the absolute min value min
+ * Compares the numbers given as arguments to get the absolute min value.
*
- * @param numbers contains elements
- * @return the absolute min value
+ * @param numbers The numbers to compare
+ * @return The absolute min value
*/
- public static int absMin(int[] numbers) {
- int absMinValue = numbers[0];
- for (int i = 1, length = numbers.length; i < length; ++i) {
- if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
- absMinValue = numbers[i];
- }
+ public static int getMinValue(int... numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Numbers array cannot be empty");
}
- return absMinValue;
+
+ var absMinWrapper = new Object() {
+ int value = numbers[0];
+ };
+
+ Arrays.stream(numbers)
+ .skip(1)
+ .forEach(number -> {
+ if (Math.abs(number) < Math.abs(absMinWrapper.value)) {
+ absMinWrapper.value = number;
+ }
+ });
+
+ return absMinWrapper.value;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java
new file mode 100644
index 000000000000..571b080cd866
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java
@@ -0,0 +1,21 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class AbsoluteMinTest {
+
+ @Test
+ void testGetMinValue() {
+ assertEquals(0, AbsoluteMin.getMinValue(4, 0, 16));
+ assertEquals(-2, AbsoluteMin.getMinValue(3, -10, -2));
+ }
+
+ @Test
+ void testGetMinValueWithNoArguments() {
+ Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMin.getMinValue());
+ assertEquals("Numbers array cannot be empty", exception.getMessage());
+ }
+}
From 64b624efb204b641d300307d595049f7120ed7a0 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Wed, 20 Apr 2022 09:15:30 +0100
Subject: [PATCH 0011/1577] Code refactor for AbsoluteMax improvements (#3020)
Fix #3019
Co-authored-by: Yang Libin
---
.../com/thealgorithms/maths/AbsoluteMax.java | 44 +++++++++----------
.../thealgorithms/maths/AbsoluteMaxTest.java | 21 +++++++++
2 files changed, 41 insertions(+), 24 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
index b67b5991ce0a..76430db77195 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
@@ -2,35 +2,31 @@
import java.util.Arrays;
-/**
- * description:
- *
- *
- * absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
- */
public class AbsoluteMax {
- public static void main(String[] args) {
- int[] testnums = {-2, 0, 16};
- assert absMax(testnums) == 16;
-
- int[] numbers = {3, -10, -2};
- System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
- }
-
/**
- * get the value, return the absolute max value
+ * Compares the numbers given as arguments to get the absolute max value.
*
- * @param numbers contains elements
- * @return the absolute max value
+ * @param numbers The numbers to compare
+ * @return The absolute max value
*/
- public static int absMax(int[] numbers) {
- int absMaxValue = numbers[0];
- for (int i = 1, length = numbers.length; i < length; ++i) {
- if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
- absMaxValue = numbers[i];
- }
+ public static int getMaxValue(int... numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Numbers array cannot be empty");
}
- return absMaxValue;
+
+ var absMaxWrapper = new Object() {
+ int value = numbers[0];
+ };
+
+ Arrays.stream(numbers)
+ .skip(1)
+ .forEach(number -> {
+ if (Math.abs(number) > Math.abs(absMaxWrapper.value)) {
+ absMaxWrapper.value = number;
+ }
+ });
+
+ return absMaxWrapper.value;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
new file mode 100644
index 000000000000..a68c1a81bd3c
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
@@ -0,0 +1,21 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class AbsoluteMaxTest {
+
+ @Test
+ void testGetMaxValue() {
+ assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
+ assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
+ }
+
+ @Test
+ void testGetMaxValueWithNoArguments() {
+ Exception exception = assertThrows(IllegalArgumentException.class, () -> AbsoluteMax.getMaxValue());
+ assertEquals("Numbers array cannot be empty", exception.getMessage());
+ }
+}
From 5eed0849ef4734e3faec8fa21d798c2927ec3b4e Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Wed, 20 Apr 2022 09:17:44 +0100
Subject: [PATCH 0012/1577] Code refactor for AbsoluteValue improvements
(#3018)
Fix #3017
Co-authored-by: Yang Libin
---
.../thealgorithms/maths/AbsoluteValue.java | 22 +++++--------------
.../maths/AbsoluteValueTest.java | 18 +++++++++++++++
2 files changed, 23 insertions(+), 17 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteValue.java b/src/main/java/com/thealgorithms/maths/AbsoluteValue.java
index dfd00f862900..607413641392 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteValue.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteValue.java
@@ -1,26 +1,14 @@
package com.thealgorithms.maths;
-import java.util.Random;
-
public class AbsoluteValue {
- public static void main(String[] args) {
- Random random = new Random();
-
- /* test 1000 random numbers */
- for (int i = 1; i <= 1000; ++i) {
- int randomNumber = random.nextInt();
- assert absVal(randomNumber) == Math.abs(randomNumber);
- }
- }
-
/**
- * If value is less than zero, make value positive.
+ * Returns the absolute value of a number.
*
- * @param value a number
- * @return the absolute value of a number
+ * @param number The number to be transformed
+ * @return The absolute value of the {@code number}
*/
- public static int absVal(int value) {
- return value < 0 ? -value : value;
+ public static int getAbsValue(int number) {
+ return number < 0 ? -number : number;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java
new file mode 100644
index 000000000000..8b95eaec26fa
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/AbsoluteValueTest.java
@@ -0,0 +1,18 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class AbsoluteValueTest {
+
+ @Test
+ void testGetAbsValue() {
+ Stream.generate(() -> ThreadLocalRandom.current().nextInt())
+ .limit(1000)
+ .forEach(number -> assertEquals(Math.abs(number), AbsoluteValue.getAbsValue(number)));
+ }
+}
From 4b15b2c021c32868cdc74e144fa6dc3c92324f52 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Wed, 20 Apr 2022 09:20:47 +0100
Subject: [PATCH 0013/1577] Code refactor for ADTFraction improvements (#3016)
Fix #3015
Co-authored-by: Yang Libin
---
.../com/thealgorithms/maths/ADTFraction.java | 141 ++++++++----------
.../thealgorithms/maths/ADTFractionTest.java | 52 +++++++
2 files changed, 113 insertions(+), 80 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/ADTFractionTest.java
diff --git a/src/main/java/com/thealgorithms/maths/ADTFraction.java b/src/main/java/com/thealgorithms/maths/ADTFraction.java
index ca70ba0e0291..612dfaeca641 100644
--- a/src/main/java/com/thealgorithms/maths/ADTFraction.java
+++ b/src/main/java/com/thealgorithms/maths/ADTFraction.java
@@ -1,100 +1,81 @@
package com.thealgorithms.maths;
-public class ADTFraction {
-
- public static void main(String[] args) {
- // TODO code application logic here
-
- ADTFraction f1 = new ADTFraction(3, 5);
- f1.display();
- ADTFraction f2 = new ADTFraction(7, 8);
- f2.display();
- ADTFraction f3 = f1.plus(f2);
- f3.display();
- ADTFraction f4 = f1.times(f2);
- f4.display();
- ADTFraction f5 = f1.times(4);
- f5.display();
-
- }
-
- private int n; //numerator
- private int d; //denomenator
-
- public ADTFraction() {
- this.n = 0;
- this.d = 1;
- }
-
- public ADTFraction(int a, int b) {//parameter constructor
-
- if (b != 0) {
- this.n = a;
- this.d = b;
- } else {
- this.n = 0;
- this.d = 1;
- System.out.println("denomerator cannot be 0,default values assinged");
+public record ADTFraction(int numerator, int denominator) {
+
+ /**
+ * Initializes a newly created {@code ADTFraction} object so that it represents
+ * a fraction with the {@code numerator} and {@code denominator} provided as arguments.
+ *
+ * @param numerator The fraction numerator
+ * @param denominator The fraction denominator
+ */
+ public ADTFraction {
+ if (denominator == 0) {
+ throw new IllegalArgumentException("Denominator cannot be 0");
}
}
- public void set(int a, int b) {//set numerator and denomenator
-
- if (b != 0) {
- this.n = a;
- this.d = b;
- } else {
- this.n = 0;
- this.d = 1;
- System.out.println("denomerator cannot be 0,default values assinged");
- }
+ /**
+ * Add two fractions.
+ *
+ * @param fraction the {@code ADTFraction} to add
+ * @return A new {@code ADTFraction} containing the result of the operation
+ */
+ public ADTFraction plus(ADTFraction fraction) {
+ var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
+ var denominator = this.denominator * fraction.denominator;
+ return new ADTFraction(numerator, denominator);
}
- //add two fractions
- public ADTFraction plus(ADTFraction x) {
-
- int num, den;
- num = this.d * x.n + this.n * x.d;
- den = this.d * x.d;
- ADTFraction f = new ADTFraction(num, den);
- return f;
-
+ /**
+ * Multiply fraction by a number.
+ *
+ * @param number the number to multiply
+ * @return A new {@code ADTFraction} containing the result of the operation
+ */
+ public ADTFraction times(int number) {
+ return times(new ADTFraction(number, 1));
}
- public ADTFraction times(int a) {//multiply fraction by a number
-
- int num, den;
- num = this.n * a;
- den = this.d;
- ADTFraction f1 = new ADTFraction(num, den);
- return f1;
-
- }
-
- public ADTFraction times(ADTFraction x) {//multiply two fractions
-
- int num, dem;
- num = this.n * x.n;
- dem = this.d * x.d;
- ADTFraction f3 = new ADTFraction(num, dem);
- return f3;
-
+ /**
+ * Multiply two fractions.
+ *
+ * @param fraction the {@code ADTFraction} to multiply
+ * @return A new {@code ADTFraction} containing the result of the operation
+ */
+ public ADTFraction times(ADTFraction fraction) {
+ var numerator = this.numerator * fraction.numerator;
+ var denominator = this.denominator * fraction.denominator;
+ return new ADTFraction(numerator, denominator);
}
- //reciprocal of a fraction
+ /**
+ * Generates the reciprocal of the fraction.
+ *
+ * @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched
+ */
public ADTFraction reciprocal() {
- ADTFraction f1 = new ADTFraction(this.d, this.n);
- return f1;
+ return new ADTFraction(this.denominator, this.numerator);
}
- //numerical value of a fraction
+ /**
+ * Calculates the result of the fraction.
+ *
+ * @return The numerical result of the division between {@code numerator} and {@code denominator}
+ */
public float value() {
- return (float) this.n / this.d;
+ return (float) this.numerator / this.denominator;
}
- //display the fraction in the format n/d
- public void display() {
- System.out.println(this.n + "/" + this.d);
+ /**
+ * Returns a string representation of this {@code ADTFraction} in the format
+ * {@code numerator}/{@code denominator}.
+ *
+ * @return A string representation of this {@code ADTFraction}
+ */
+ @Override
+ public String toString() {
+ return String.format("%d/%d", this.numerator, this.denominator);
}
}
diff --git a/src/test/java/com/thealgorithms/maths/ADTFractionTest.java b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java
new file mode 100644
index 000000000000..611df73bcffc
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/ADTFractionTest.java
@@ -0,0 +1,52 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ADTFractionTest {
+
+ private final ADTFraction fraction1 = new ADTFraction(3, 5);
+ private final ADTFraction fraction2 = new ADTFraction(7, 8);
+
+ @Test
+ void testConstructorWithDenominatorEqualToZero() {
+ Exception exception = assertThrows(IllegalArgumentException.class, () -> new ADTFraction(1, 0));
+ assertEquals("Denominator cannot be 0", exception.getMessage());
+ }
+
+ @Test
+ public void testPlus() {
+ assertEquals(new ADTFraction(59, 40), fraction1.plus(fraction2));
+ }
+
+ @Test
+ public void testTimes() {
+ assertEquals(new ADTFraction(12, 5), fraction1.times(4));
+ assertEquals(new ADTFraction(21, 40), fraction1.times(fraction2));
+ }
+
+ @Test
+ public void testReciprocal() {
+ assertEquals(new ADTFraction(5, 3), fraction1.reciprocal());
+ }
+
+ @Test
+ public void testValue() {
+ assertEquals(0.6F, fraction1.value());
+ }
+
+ @Test
+ public void testEqualsAndHashCode() {
+ ADTFraction fraction3 = new ADTFraction(3, 5);
+ assertTrue(fraction1.equals(fraction3) && fraction3.equals(fraction1));
+ assertEquals(fraction1.hashCode(), fraction3.hashCode());
+ }
+
+ @Test
+ public void testToString() {
+ assertEquals("3/5", fraction1.toString());
+ }
+}
From 9f7613b467bda734cdea196013c8fdfe19af81a2 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Thu, 21 Apr 2022 02:31:55 +0100
Subject: [PATCH 0014/1577] Code refactor for AliquotSum improvements (#3027)
Fix #3026
---
.../com/thealgorithms/maths/AliquotSum.java | 30 +++++++++----------
.../thealgorithms/maths/AliquotSumTest.java | 16 ++++++++++
2 files changed, 30 insertions(+), 16 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/AliquotSumTest.java
diff --git a/src/main/java/com/thealgorithms/maths/AliquotSum.java b/src/main/java/com/thealgorithms/maths/AliquotSum.java
index 329bcf2f9984..7565d49c8acf 100644
--- a/src/main/java/com/thealgorithms/maths/AliquotSum.java
+++ b/src/main/java/com/thealgorithms/maths/AliquotSum.java
@@ -1,5 +1,7 @@
package com.thealgorithms.maths;
+import java.util.stream.IntStream;
+
/**
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of
* all proper divisors of n, that is, all divisors of n other than n itself. For
@@ -9,26 +11,22 @@
*/
public class AliquotSum {
- public static void main(String[] args) {
- assert aliquotSum(1) == 0;
- assert aliquotSum(6) == 6;
- assert aliquotSum(15) == 9;
- assert aliquotSum(19) == 1;
- }
-
/**
- * Finds the aliquot sum of an integer number
+ * Finds the aliquot sum of an integer number.
*
* @param number a positive integer
* @return aliquot sum of given {@code number}
*/
- public static int aliquotSum(int number) {
- int sum = 0;
- for (int i = 1, limit = number / 2; i <= limit; ++i) {
- if (number % i == 0) {
- sum += i;
- }
- }
- return sum;
+ public static int getAliquotValue(int number) {
+ var sumWrapper = new Object() {
+ int value = 0;
+ };
+
+ IntStream.iterate(1, i -> ++i)
+ .limit(number / 2)
+ .filter(i -> number % i == 0)
+ .forEach(i -> sumWrapper.value += i);
+
+ return sumWrapper.value;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/AliquotSumTest.java b/src/test/java/com/thealgorithms/maths/AliquotSumTest.java
new file mode 100644
index 000000000000..eca726ae271c
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/AliquotSumTest.java
@@ -0,0 +1,16 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class AliquotSumTest {
+
+ @Test
+ void testGetMaxValue() {
+ assertEquals(0, AliquotSum.getAliquotValue(1));
+ assertEquals(6, AliquotSum.getAliquotValue(6));
+ assertEquals(9, AliquotSum.getAliquotValue(15));
+ assertEquals(1, AliquotSum.getAliquotValue(19));
+ }
+}
From c8b0a201da9579a0c83063685d478284414f3630 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Thu, 21 Apr 2022 02:33:29 +0100
Subject: [PATCH 0015/1577] Code refactor for AbsoluteMax improvements (#3029)
Fix #3028
Co-authored-by: Yang Libin
---
src/main/java/com/thealgorithms/maths/AbsoluteMax.java | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
index 76430db77195..0852fe85be7e 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
@@ -21,11 +21,8 @@ public static int getMaxValue(int... numbers) {
Arrays.stream(numbers)
.skip(1)
- .forEach(number -> {
- if (Math.abs(number) > Math.abs(absMaxWrapper.value)) {
- absMaxWrapper.value = number;
- }
- });
+ .filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
+ .forEach(number -> absMaxWrapper.value = number);
return absMaxWrapper.value;
}
From 1320748c8884e832d82ca273fb5bdcae5279aca1 Mon Sep 17 00:00:00 2001
From: Cristiano Jesus
Date: Thu, 21 Apr 2022 02:34:40 +0100
Subject: [PATCH 0016/1577] Code refactor for AbsoluteMin improvements (#3031)
Fix #3030
Co-authored-by: Yang Libin
---
src/main/java/com/thealgorithms/maths/AbsoluteMin.java | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
index 9b6f0e747d5f..9dc8b0111098 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
@@ -21,11 +21,8 @@ public static int getMinValue(int... numbers) {
Arrays.stream(numbers)
.skip(1)
- .forEach(number -> {
- if (Math.abs(number) < Math.abs(absMinWrapper.value)) {
- absMinWrapper.value = number;
- }
- });
+ .filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
+ .forEach(number -> absMinWrapper.value = number);
return absMinWrapper.value;
}
From 64f1e51df47fb613c19dd877dcca0ed54af8d0d8 Mon Sep 17 00:00:00 2001
From: Yadunandan Bhat <54680617+yadunandanbhat@users.noreply.github.com>
Date: Thu, 21 Apr 2022 18:05:27 +0530
Subject: [PATCH 0017/1577] Add pigeonhole sort (fixes #2992) (#3013)
---
.../thealgorithms/sorts/PigeonholeSort.java | 54 +++++++++++++++++++
1 file changed, 54 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
new file mode 100644
index 000000000000..5025b7f6b62b
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
@@ -0,0 +1,54 @@
+package com.thealgorithms.sorts;
+
+import java.util.*;
+import static com.thealgorithms.sorts.SortUtils.*;
+
+public class PigeonholeSort {
+ /*
+ This code implements the pigeonhole sort algorithm for the integer array,
+ but we can also implement this for string arrays too.
+ See https://www.geeksforgeeks.org/pigeonhole-sort/
+ */
+ void sort(Integer[] array){
+ int maxElement = array[0];
+ for (int element: array) {
+ if (element > maxElement) maxElement = element;
+ }
+
+ int numOfPigeonholes = 1 + maxElement;
+ ArrayList[] pigeonHole = new ArrayList[numOfPigeonholes];
+
+ for (int k=0; k();
+ }
+
+ for (int t: array) {
+ pigeonHole[t].add(t);
+ }
+
+ int k=0;
+ for (ArrayList ph: pigeonHole) {
+ for (int elements: ph) {
+ array[k]=elements;
+ k=k+1;
+ }
+ }
+ }
+
+ public static void main(String[] args)
+ {
+ PigeonholeSort pigeonholeSort = new PigeonholeSort();
+ Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 };
+
+ System.out.print("Unsorted order is : ");
+ print(arr);
+
+ pigeonholeSort.sort(arr);
+
+ System.out.print("Sorted order is : ");
+ for (int i = 0; i < arr.length; i++) {
+ assert (arr[i]) <= (arr[i+1]);
+ }
+ print(arr);
+ }
+}
From 7c31c5badaf65aa7ef52bc9b475a0bf75385f931 Mon Sep 17 00:00:00 2001
From: Samir M'Sallem <49750910+samirmsallem@users.noreply.github.com>
Date: Fri, 22 Apr 2022 18:50:04 +0200
Subject: [PATCH 0018/1577] Add else clause for node (#3014)
Co-authored-by: Samir M'Sallem
Co-authored-by: Andrii Siriak
---
.../thealgorithms/datastructures/hashmap/hashing/HashMap.java | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
index 247244da5316..3225c437d237 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java
@@ -105,6 +105,8 @@ private void delete(Node n, int key) {
} else {
n.setNext(n.getNext().getNext());
}
+ } else {
+ delete(n.getNext(), key);
}
}
From 99ff5163e3cd88c7a384349b92238463a8b201b8 Mon Sep 17 00:00:00 2001
From: BranAndSceolan <98578040+BranAndSceolan@users.noreply.github.com>
Date: Mon, 25 Apr 2022 15:54:33 +0200
Subject: [PATCH 0019/1577] Add Wigglesort (#3032)
Co-authored-by: Antonia Strack
Co-authored-by: Andrii Siriak
---
.../com/thealgorithms/sorts/WiggleSort.java | 82 +++++++++++++++++++
.../thealgorithms/sorts/WiggleSortTest.java | 75 +++++++++++++++++
2 files changed, 157 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/sorts/WiggleSort.java
create mode 100644 src/test/java/com/thealgorithms/sorts/WiggleSortTest.java
diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java
new file mode 100644
index 000000000000..b368c74422a9
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java
@@ -0,0 +1,82 @@
+package com.thealgorithms.sorts;
+
+import java.util.Arrays;
+
+import static com.thealgorithms.maths.Ceil.ceil;
+import static com.thealgorithms.maths.Floor.floor;
+import static com.thealgorithms.searches.QuickSelect.select;
+
+/**
+ * A wiggle sort implementation based on John L.s' answer in
+ * https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity
+ * Also have a look at: https://cs.stackexchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-complexity?noredirect=1&lq=1
+ * Not all arrays are wiggle-sortable. This algorithm will find some obviously not wiggle-sortable arrays and throw an error,
+ * but there are some exceptions that won't be caught, for example [1, 2, 2].
+ */
+public class WiggleSort implements SortAlgorithm {
+ @Override
+ public > T[] sort(T[] unsorted) {
+ return wiggleSort(unsorted);
+ }
+
+ private int mapIndex(int index, int n) {
+ return ((2 * index + 1) % (n | 1));
+ }
+
+ /**
+ * Modified Dutch National Flag Sort. See also: sorts/DutchNationalFlagSort
+ *
+ * @param sortThis array to sort into group "greater", "equal" and "smaller" than median
+ * @param median defines the groups
+ * @param extends interface Comparable
+ */
+ private > void triColorSort(T[] sortThis, T median) {
+ int n = sortThis.length;
+ int i = 0;
+ int j = 0;
+ int k = n - 1;
+ while (j <= k) {
+ if (0 < sortThis[mapIndex(j, n)].compareTo(median)) {
+ SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(i, n));
+ i++;
+ j++;
+ } else if (0 > sortThis[mapIndex(j, n)].compareTo(median)) {
+ SortUtils.swap(sortThis, mapIndex(j, n), mapIndex(k, n));
+ k--;
+ } else {
+ j++;
+ }
+ }
+ }
+
+ private > T[] wiggleSort(T[] sortThis) {
+ // find the median using quickSelect (if the result isn't in the array, use the next greater value)
+ T median;
+
+ median = select(Arrays.asList(sortThis), (int) floor(sortThis.length / 2.0));
+
+ int numMedians = 0;
+
+ for (T sortThi : sortThis) {
+ if (0 == sortThi.compareTo(median)) {
+ numMedians++;
+ }
+ }
+ // added condition preventing off-by-one errors for odd arrays.
+ // https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-arrays-did-i-misunderstand-john-l-s-answer?noredirect=1&lq=1
+ if (sortThis.length % 2 == 1 && numMedians == ceil(sortThis.length / 2.0)) {
+ T smallestValue = select(Arrays.asList(sortThis), 0);
+ if (!(0 == smallestValue.compareTo(median))) {
+ throw new IllegalArgumentException("For odd Arrays if the median appears ceil(n/2) times, " +
+ "the median has to be the smallest values in the array.");
+ }
+ }
+ if (numMedians > ceil(sortThis.length / 2.0)) {
+ throw new IllegalArgumentException("No more than half the number of values may be the same.");
+
+ }
+
+ triColorSort(sortThis, median);
+ return sortThis;
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java
new file mode 100644
index 000000000000..336170a33535
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java
@@ -0,0 +1,75 @@
+package com.thealgorithms.sorts;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+
+public class WiggleSortTest {
+ @Test
+ void WiggleTestNumbersEven(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {1, 2, 3, 4};
+ Integer[] result = {1, 4, 2, 3};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+ }
+
+ @Test
+ void WiggleTestNumbersOdd(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {1, 2, 3, 4, 5};
+ Integer[] result = {3, 5, 1, 4, 2};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+
+ }
+
+ @Test
+ void WiggleTestNumbersOddDuplicates(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {7, 2, 2, 2, 5};
+ Integer[] result = {2, 7, 2, 5, 2};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+ }
+
+ @Test
+ void WiggleTestNumbersOddMultipleDuplicates(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {1, 1, 2, 2, 5};
+ Integer[] result = {2, 5, 1, 2, 1};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+ }
+
+ @Test
+ void WiggleTestNumbersEvenMultipleDuplicates(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {1, 1, 2, 2, 2, 5};
+ Integer[] result = {2, 5, 1, 2, 1, 2};
+ wiggleSort.sort(values);
+ System.out.println(Arrays.toString(values));
+ assertArrayEquals(values, result);
+ }
+
+ @Test
+ void WiggleTestNumbersEvenDuplicates(){
+ WiggleSort wiggleSort = new WiggleSort();
+ Integer[] values = {1, 2, 4, 4};
+ Integer[] result = {1, 4, 2, 4};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+ }
+
+ @Test
+ void WiggleTestStrings(){
+ WiggleSort wiggleSort = new WiggleSort();
+ String[] values = {"a", "b", "d", "c"};
+ String[] result = {"a", "d", "b", "c"};
+ wiggleSort.sort(values);
+ assertArrayEquals(values, result);
+ }
+}
From dfdce96c6e715c1229384568473ec2251e6eb72e Mon Sep 17 00:00:00 2001
From: BranAndSceolan <98578040+BranAndSceolan@users.noreply.github.com>
Date: Mon, 25 Apr 2022 16:02:15 +0200
Subject: [PATCH 0020/1577] Add Dutch National Flag Sort (#3025)
Co-authored-by: Antonia Strack
Co-authored-by: Andrii Siriak
---
.../sorts/DutchNationalFlagSort.java | 44 +++++++
.../sorts/DutchNationalFlagSortTest.java | 112 ++++++++++++++++++
2 files changed, 156 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
create mode 100644 src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java
diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
new file mode 100644
index 000000000000..a2e32c2f0ecc
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
@@ -0,0 +1,44 @@
+package com.thealgorithms.sorts;
+
+/**
+ * The Dutch National Flag Sort sorts a sequence of values into three permutations which are defined by a value given
+ * as the indented middle.
+ * First permutation: values less than middle.
+ * Second permutation: values equal middle.
+ * Third permutation: values greater than middle.
+ * If no indented middle is given, this implementation will use a value from the given Array.
+ * This value is the one positioned in the arrays' middle if the arrays' length is odd.
+ * If the arrays' length is even, the value left to the middle will be used.
+ * More information and Pseudocode: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
+ */
+public class DutchNationalFlagSort implements SortAlgorithm {
+
+ @Override
+ public > T[] sort(T[] unsorted) {
+ return dutch_national_flag_sort(unsorted, unsorted[(int) Math.ceil((unsorted.length)/2.0) -1]);
+ }
+
+ public > T[] sort(T[] unsorted, T intendedMiddle) {
+ return dutch_national_flag_sort(unsorted, intendedMiddle);
+ }
+
+ private > T[] dutch_national_flag_sort(T[] arr, T intendedMiddle){
+ int i = 0;
+ int j = 0;
+ int k = arr.length - 1;
+
+ while( j <= k){
+ if ( 0 > arr[j].compareTo(intendedMiddle)){
+ SortUtils.swap(arr, i, j);
+ j++;
+ i++;
+ } else if (0 < arr[j].compareTo(intendedMiddle)){
+ SortUtils.swap(arr, j, k);
+ k--;
+ } else {
+ j++;
+ }
+ }
+ return arr;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java
new file mode 100644
index 000000000000..56df1b3598fa
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java
@@ -0,0 +1,112 @@
+package com.thealgorithms.sorts;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class DutchNationalFlagSortTest {
+ @Test
+ /*
+ 1 will be used as intended middle.
+ Partitions on the result array: [ smaller than 1 , equal 1, greater than 1]
+ */
+ void DNFSTestOdd() {
+ Integer[] integers = {1, 3, 1, 4, 0};
+ Integer[] integersResult = {0, 1, 1, 4, 3};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(integers);
+ assertArrayEquals(integers, integersResult);
+ }
+
+ @Test
+ /*
+ 3 will be used as intended middle.
+ Partitions on the result array: [ smaller than 3 , equal 3, greater than 3]
+ */
+ void DNFSTestEven() {
+ Integer[] integers = {8, 1, 3, 1, 4, 0};
+ Integer[] integersResult = {0, 1, 1, 3, 4, 8};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(integers);
+ assertArrayEquals(integers, integersResult);
+ }
+
+ @Test
+ /*
+ "b" will be used as intended middle.
+ Partitions on the result array: [ smaller than b , equal b, greater than b]
+ */
+ void DNFSTestEvenStrings() {
+ String[] strings = {"a", "d", "b", "s", "e", "e"};
+ String[] stringsResult = {"a", "b", "s", "e", "e", "d"};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(strings);
+ assertArrayEquals(strings, stringsResult);
+ }
+
+ @Test
+ /*
+ "b" will be used as intended middle.
+ Partitions on the result array: [ smaller than b , equal b, greater than b]
+ */
+ void DNFSTestOddStrings() {
+ String[] strings = {"a", "d", "b", "s", "e"};
+ String[] stringsResult = {"a", "b", "s", "e", "d"};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(strings);
+ assertArrayEquals(strings, stringsResult);
+ }
+
+ @Test
+ /*
+ 0 will be used as intended middle.
+ Partitions on the result array: [ smaller than 0 , equal 0, greater than 0]
+ */
+ void DNFSTestOddMidGiven() {
+ Integer[] integers = {1, 3, 1, 4, 0};
+ Integer[] integersResult = {0, 1, 4, 3, 1};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(integers, 0);
+ assertArrayEquals(integers, integersResult);
+ }
+
+ @Test
+ /*
+ 4 will be used as intended middle.
+ Partitions on the result array: [ smaller than 4 , equal 4, greater than 4]
+ */
+ void DNFSTestEvenMidGiven() {
+ Integer[] integers = {8, 1, 3, 1, 4, 0};
+ Integer[] integersResult = {0, 1, 3, 1, 4, 8};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(integers, 4);
+ assertArrayEquals(integers, integersResult);
+ }
+
+ @Test
+ /*
+ "s" will be used as intended middle.
+ Partitions on the result array: [ smaller than s , equal s, greater than s]
+ */
+ void DNFSTestEvenStringsMidGiven() {
+ String[] strings = {"a", "d", "b", "s", "e", "e"};
+ String[] stringsResult = {"a", "d", "b", "e", "e", "s"};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(strings, "s");
+ assertArrayEquals(strings, stringsResult);
+ }
+
+ @Test
+ /*
+ "e" will be used as intended middle.
+ Partitions on the result array: [ smaller than e , equal e, greater than e]
+ */
+ void DNFSTestOddStringsMidGiven() {
+ String[] strings = {"a", "d", "b", "s", "e"};
+ String[] stringsResult = {"a", "d", "b", "e", "s"};
+ DutchNationalFlagSort dutchNationalFlagSort = new DutchNationalFlagSort();
+ dutchNationalFlagSort.sort(strings, "e");
+ assertArrayEquals(strings, stringsResult);
+ }
+}
From 41be089f6a918aece04e6c951359c699e755206e Mon Sep 17 00:00:00 2001
From: RaghavTaneja <97575679+RaghavTaneja@users.noreply.github.com>
Date: Thu, 28 Apr 2022 02:40:13 -0500
Subject: [PATCH 0021/1577] Add Tests for Heron's Formula (#3035)
---
.../thealgorithms/maths/HeronsFormula.java | 19 +++++++++++++
.../maths/HeronsFormulaTest.java | 27 +++++++++++++++++++
2 files changed, 46 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/maths/HeronsFormula.java
create mode 100644 src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java
diff --git a/src/main/java/com/thealgorithms/maths/HeronsFormula.java b/src/main/java/com/thealgorithms/maths/HeronsFormula.java
new file mode 100644
index 000000000000..b3da87017829
--- /dev/null
+++ b/src/main/java/com/thealgorithms/maths/HeronsFormula.java
@@ -0,0 +1,19 @@
+package com.thealgorithms.maths;
+
+/**
+ * Find the area of a triangle using only side lengths
+ */
+
+public class HeronsFormula {
+
+ public static double Herons(int s1, int s2, int s3)
+ {
+ double a = s1;
+ double b = s2;
+ double c = s3;
+ double s = (a + b + c)/2.0;
+ double area = 0;
+ area = Math.sqrt((s)*(s-a)*(s-b)*(s-c));
+ return area;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java
new file mode 100644
index 000000000000..44328399f8b9
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/HeronsFormulaTest.java
@@ -0,0 +1,27 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class HeronsFormulaTest {
+ @Test
+ void test1()
+ {
+ Assertions.assertEquals(HeronsFormula.Herons(3,4,5), 6.0);
+ }
+ @Test
+ void test2()
+ {
+ Assertions.assertEquals(HeronsFormula.Herons(24,30,18), 216.0);
+ }
+ @Test
+ void test3()
+ {
+ Assertions.assertEquals(HeronsFormula.Herons(1,1,1), 0.4330127018922193);
+ }
+ @Test
+ void test4()
+ {
+ Assertions.assertEquals(HeronsFormula.Herons(4,5,8), 8.181534085976786);
+ }
+}
From 3ebba74e04be3162d5e9d6a64f9a95652ce7a9d4 Mon Sep 17 00:00:00 2001
From: Shuangchi He <34329208+Yulv-git@users.noreply.github.com>
Date: Thu, 28 Apr 2022 21:09:25 +0800
Subject: [PATCH 0022/1577] Fix some typos (#3038)
---
.../thealgorithms/datastructures/lists/CircleLinkedList.java | 2 +-
.../java/com/thealgorithms/dynamicprogramming/CoinChange.java | 2 +-
src/main/java/com/thealgorithms/maths/VectorCrossProduct.java | 2 +-
src/main/java/com/thealgorithms/misc/RangeInSortedArray.java | 2 +-
.../Implementing_auto_completing_features_using_trie.java | 2 +-
5 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
index c5dd7f91ac3a..ed797480664d 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java
@@ -90,7 +90,7 @@ public E remove(int pos) {
}
Node destroy = before.next;
E saved = destroy.value;
- // assigning the next reference to the the element following the element we want to remove...
+ // assigning the next reference to the element following the element we want to remove...
// the last element will be assigned to the head.
before.next = before.next.next;
// scrubbing
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
index 40aba3d9ea7c..51f615dff1fa 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
@@ -49,7 +49,7 @@ public static int change(int[] coins, int amount) {
*
* @param coins The list of coins
* @param amount The amount for which we need to find the minimum number of
- * coins. Finds the the minimum number of coins that make a given value.
+ * coins. Finds the minimum number of coins that make a given value.
*/
public static int minimumCoins(int[] coins, int amount) {
// minimumCoins[i] will store the minimum coins needed for amount i
diff --git a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
index 533cfc94d738..1b194a55d54a 100644
--- a/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
+++ b/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
@@ -28,7 +28,7 @@
* following Java Program calculates the direction ratios of the cross products
* of two vector. The program uses a function, cross() for doing so. The
* direction ratios for the first and the second vector has to be passed one by
- * one seperated by a space character.
+ * one separated by a space character.
*
* Magnitude of a vector is the square root of the sum of the squares of the
* direction ratios.
diff --git a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
index dabd278b2e62..eb88f814805c 100644
--- a/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
+++ b/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
@@ -90,7 +90,7 @@ public static int getLessThan(int[] nums, int key, int left, int right) {
if (nums[mid] > key) {
right = mid - 1;
} else if (nums[mid] <= key) {
- count = mid + 1; // Atleast mid+1 elements exist which are <= key
+ count = mid + 1; // At least mid+1 elements exist which are <= key
left = mid + 1;
}
}
diff --git a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java
index b40c175f1481..f3fe7a25c3e0 100644
--- a/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java
+++ b/src/main/java/com/thealgorithms/others/Implementing_auto_completing_features_using_trie.java
@@ -135,7 +135,7 @@ static int printAutoSuggestions(TrieNode root,
return -1;
}
- // If there are are nodes below last
+ // If there are nodes below the last
// matching character.
if (!isLast) {
String prefix = query;
From 1a230bd61e640bb70290402fac95d03da870a0b3 Mon Sep 17 00:00:00 2001
From: Omar <59146036+omarmahamid@users.noreply.github.com>
Date: Fri, 29 Apr 2022 16:30:05 +0300
Subject: [PATCH 0023/1577] Add New Prime Check (#3036)
---
.../com/thealgorithms/maths/PrimeCheck.java | 47 ++++++++++++++++++-
1 file changed, 45 insertions(+), 2 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/PrimeCheck.java b/src/main/java/com/thealgorithms/maths/PrimeCheck.java
index f2587f7026b2..fd06cb7f2bc6 100644
--- a/src/main/java/com/thealgorithms/maths/PrimeCheck.java
+++ b/src/main/java/com/thealgorithms/maths/PrimeCheck.java
@@ -10,9 +10,15 @@ public static void main(String[] args) {
System.out.print("Enter a number: ");
int n = scanner.nextInt();
if (isPrime(n)) {
- System.out.println(n + " is a prime number");
+ System.out.println("algo1 verify that " + n + " is a prime number");
} else {
- System.out.println(n + " is not a prime number");
+ System.out.println("algo1 verify that " + n + " is not a prime number");
+ }
+
+ if (fermatPrimeChecking(n, 20)) {
+ System.out.println("algo2 verify that " + n + " is a prime number");
+ } else {
+ System.out.println("algo2 verify that " + n + " is not a prime number");
}
scanner.close();
}
@@ -38,4 +44,41 @@ public static boolean isPrime(int n) {
}
return true;
}
+
+ /**
+ * *
+ * Checks if a number is prime or not
+ *
+ * @param n the number
+ * @return {@code true} if {@code n} is prime
+ */
+ public static boolean fermatPrimeChecking(int n, int iteration){
+ long a;
+ int up = n - 2, down = 2;
+ for(int i=0;i
Date: Sun, 1 May 2022 02:32:03 -0500
Subject: [PATCH 0024/1577] Add Standard Deviation (#3039)
---
.../maths/StandardDeviation.java | 22 +++++++++++++
.../maths/StandardDeviationTest.java | 32 +++++++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/maths/StandardDeviation.java
create mode 100644 src/test/java/com/thealgorithms/maths/StandardDeviationTest.java
diff --git a/src/main/java/com/thealgorithms/maths/StandardDeviation.java b/src/main/java/com/thealgorithms/maths/StandardDeviation.java
new file mode 100644
index 000000000000..70885eee1b50
--- /dev/null
+++ b/src/main/java/com/thealgorithms/maths/StandardDeviation.java
@@ -0,0 +1,22 @@
+package com.thealgorithms.maths;
+
+public class StandardDeviation {
+
+ public static double stdDev(double[] data)
+ {
+ double var = 0;
+ double avg = 0;
+ for (int i = 0; i < data.length; i++)
+ {
+ avg += data[i];
+ }
+ avg /= data.length;
+ for (int j = 0; j < data.length; j++)
+ {
+ var += Math.pow((data[j] - avg), 2);
+ }
+ var /= data.length;
+ return Math.sqrt(var);
+ }
+
+}
diff --git a/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java
new file mode 100644
index 000000000000..5a77376028b5
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/StandardDeviationTest.java
@@ -0,0 +1,32 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class StandardDeviationTest{
+ @Test
+ void test1()
+ {
+ double[] t1 = new double[]{1,1,1,1,1};
+ Assertions.assertEquals(StandardDeviation.stdDev(t1), 0.0);
+ }
+ @Test
+ void test2()
+ {
+ double[] t2 = new double[]{1,2,3,4,5,6,7,8,9,10};
+ Assertions.assertEquals(StandardDeviation.stdDev(t2), 2.8722813232690143);
+ }
+ @Test
+ void test3()
+ {
+ double[] t3= new double[]{1.1, 8.5, 20.3, 2.4, 6.2};
+ Assertions.assertEquals(StandardDeviation.stdDev(t3), 6.8308125431752265);
+ }
+ @Test
+ void test4()
+ {
+ double[] t4 = new double[]{3.14, 2.22222, 9.89898989, 100.00045, 56.7};
+ Assertions.assertEquals(StandardDeviation.stdDev(t4), 38.506117353865775);
+ }
+}
+
From 00c758a299bd78664515785ec858b21b6cd79b6f Mon Sep 17 00:00:00 2001
From: Omar <59146036+omarmahamid@users.noreply.github.com>
Date: Mon, 2 May 2022 18:56:05 +0300
Subject: [PATCH 0025/1577] Add Fibonacci Heap (#3037)
---
.../datastructures/heaps/FibonacciHeap.java | 431 ++++++++++++++++++
.../datastructures/FibonacciHeapTest.java | 21 +
2 files changed, 452 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
new file mode 100644
index 000000000000..2236f6741fd1
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -0,0 +1,431 @@
+package com.thealgorithms.datastructures.heaps;
+
+
+public class FibonacciHeap {
+
+ private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
+ private HeapNode min;
+ private static int totalLinks = 0;
+ private static int totalCuts = 0;
+ private int numOfTrees = 0;
+ private int numOfHeapNodes = 0;
+ private int markedHeapNoodesCounter = 0;
+
+ /*
+ * a constructor for an empty Heap
+ * set the min to be null
+ */
+ public FibonacciHeap() {
+ this.min = null;
+ }
+
+ /*
+ * a constructor for a Heap with one element
+ * set the min to be the HeapNode with the given key
+ * @pre key>=0
+ * @post empty == false
+ */
+ public FibonacciHeap(int key) {
+ this.min = new HeapNode(key);
+ this.numOfTrees++;
+ this.numOfHeapNodes++;
+ }
+
+ /*
+ * check if the heap is empty
+ * $ret == true - if the tree is empty
+ */
+ public boolean empty() {
+ return (this.min == null);
+ }
+
+ /**
+ * Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap.
+ *
+ * @pre key>=0
+ * @post (numOfnodes = = $prev numOfnodes + 1)
+ * @post empty == false
+ * $ret = the HeapNode we inserted
+ */
+ public HeapNode insert(int key) {
+ HeapNode toInsert = new HeapNode(key); //creates the node
+ if (this.empty()) {
+ this.min = toInsert;
+ } else { //tree is not empty
+ min.setNext(toInsert);
+ this.updateMin(toInsert);
+ }
+ this.numOfHeapNodes++;
+ this.numOfTrees++;
+ return toInsert;
+ }
+
+ /**
+ * Delete the node containing the minimum key in the heap
+ * updates new min
+ *
+ * @post (numOfnodes = = $prev numOfnodes - 1)
+ */
+ public void deleteMin() {
+ if (this.empty()) {
+ return;
+ }
+ if (this.numOfHeapNodes == 1) { //if there is only one tree
+ this.min = null;
+ this.numOfTrees--;
+ this.numOfHeapNodes--;
+ return;
+ }
+ //change all children's parent to null//
+ if (this.min.child != null) { //min has a child
+ HeapNode child = this.min.child;
+ HeapNode tmpChild = child;
+ child.parent = null;
+ while (child.next != tmpChild) {
+ child = child.next;
+ child.parent = null;
+ }
+ }
+ //delete the node//
+ if (this.numOfTrees > 1) {
+ (this.min.prev).next = this.min.next;
+ (this.min.next).prev = this.min.prev;
+ if (this.min.child != null) {
+ (this.min.prev).setNext(this.min.child);
+ }
+ } else { //this.numOfTrees = 1
+ this.min = this.min.child;
+ }
+ this.numOfHeapNodes--;
+ this.successiveLink(this.min.getNext());
+ }
+
+ /**
+ * Return the node of the heap whose key is minimal.
+ * $ret == null if (empty==true)
+ */
+ public HeapNode findMin() {
+ return this.min;
+ }
+
+ /**
+ * Meld the heap with heap2
+ *
+ * @pre heap2 != null
+ * @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes)
+ */
+ public void meld(FibonacciHeap heap2) {
+ if (heap2.empty()) {
+ return;
+ }
+ if (this.empty()) {
+ this.min = heap2.min;
+ } else {
+ this.min.setNext(heap2.min);
+ this.updateMin(heap2.min);
+ }
+ this.numOfTrees += heap2.numOfTrees;
+ this.numOfHeapNodes += heap2.numOfHeapNodes;
+ }
+
+ /**
+ * Return the number of elements in the heap
+ * $ret == 0 if heap is empty
+ */
+ public int size() {
+ return this.numOfHeapNodes;
+ }
+
+ /**
+ * Return a counters array, where the value of the i-th index is the number of trees with rank i in the heap.
+ * returns an empty array for an empty heap
+ */
+ public int[] countersRep() {
+ if (this.empty()) {
+ return new int[0]; ///return an empty array
+ }
+ int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; //creates the array
+ rankArray[this.min.rank]++;
+ HeapNode curr = this.min.next;
+ while (curr != this.min) {
+ rankArray[curr.rank]++;
+ curr = curr.next;
+ }
+ return rankArray;
+ }
+
+ /**
+ * Deletes the node x from the heap (using decreaseKey(x) to -1)
+ *
+ * @pre heap contains x
+ * @post (numOfnodes = = $prev numOfnodes - 1)
+ */
+ public void delete(HeapNode x) {
+ this.decreaseKey(x, x.getKey() + 1); //change key to be the minimal (-1)
+ this.deleteMin(); //delete it
+ }
+
+ /**
+ * The function decreases the key of the node x by delta.
+ *
+ * @pre x.key >= delta (we don't realize it when calling from delete())
+ * @pre heap contains x
+ */
+ private void decreaseKey(HeapNode x, int delta) {
+ int newKey = x.getKey() - delta;
+ x.key = newKey;
+ if (x.isRoot()) {//no parent to x
+ this.updateMin(x);
+ return;
+ }
+ if (x.getKey() >= x.parent.getKey()) {
+ return;
+ } //we don't need to cut
+ HeapNode prevParent = x.parent;
+ this.cut(x);
+ this.cascadingCuts(prevParent);
+ }
+
+ /**
+ * returns the current potential of the heap, which is:
+ * Potential = #trees + 2*#markedNodes
+ */
+ public int potential() {
+ return numOfTrees + (2 * markedHeapNoodesCounter);
+ }
+
+ /**
+ * This static function returns the total number of link operations made during the run-time of the program.
+ * A link operation is the operation which gets as input two trees of the same rank, and generates a tree of
+ * rank bigger by one.
+ */
+ public static int totalLinks() {
+ return totalLinks;
+ }
+
+ /**
+ * This static function returns the total number of cut operations made during the run-time of the program.
+ * A cut operation is the operation which disconnects a subtree from its parent (during decreaseKey/delete methods).
+ */
+ public static int totalCuts() {
+ return totalCuts;
+ }
+
+ /*
+ * updates the min of the heap (if needed)
+ * @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key)
+ */
+ private void updateMin(HeapNode posMin) {
+ if (posMin.getKey() < this.min.getKey()) {
+ this.min = posMin;
+ }
+ }
+
+ /*
+ * Recursively "runs" all the way up from @param (curr) and mark the nodes.
+ * stop the recursion if we had arrived to a marked node or to a root.
+ * if we arrived to a marked node, we cut it and continue recursively.
+ * called after a node was cut.
+ * @post (numOfnodes == $prev numOfnodes)
+ */
+ private void cascadingCuts(HeapNode curr) {
+ if (!curr.isMarked()) { //stop the recursion
+ curr.mark();
+ if (!curr.isRoot()) this.markedHeapNoodesCounter++;
+ return;
+ } else {
+ if (curr.isRoot()) {
+ return;
+ }
+ HeapNode prevParent = curr.parent;
+ this.cut(curr);
+ this.cascadingCuts(prevParent);
+ }
+ }
+
+ /*
+ * cut a node (and his "subtree") from his origin tree and connect it to the heap as a new tree.
+ * called after a node was cut.
+ * @post (numOfnodes == $prev numOfnodes)
+ */
+ private void cut(HeapNode curr) {
+ curr.parent.rank--;
+ if (curr.marked) {
+ this.markedHeapNoodesCounter--;
+ curr.marked = false;
+ }
+ if (curr.parent.child == curr) { //we should change the parent's child
+ if (curr.next == curr) { //curr do not have brothers
+ curr.parent.child = null;
+ } else {//curr have brothers
+ curr.parent.child = curr.next;
+ }
+ }
+ curr.prev.next = curr.next;
+ curr.next.prev = curr.prev;
+ curr.next = curr;
+ curr.prev = curr;
+ curr.parent = null;
+ this.min.setNext(curr);
+ this.updateMin(curr);
+ this.numOfTrees++;
+ totalCuts++;
+ }
+
+
+ /*
+ *
+ */
+ private void successiveLink(HeapNode curr) {
+ HeapNode[] buckets = this.toBuckets(curr);
+ this.min = this.fromBuckets(buckets);
+ }
+
+ /*
+ *
+ */
+ private HeapNode[] toBuckets(HeapNode curr) {
+ HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
+ curr.prev.next = null;
+ HeapNode tmpCurr;
+ while (curr != null) {
+ tmpCurr = curr;
+ curr = curr.next;
+ tmpCurr.next = tmpCurr;
+ tmpCurr.prev = tmpCurr;
+ while (buckets[tmpCurr.rank] != null) {
+ tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]);
+ buckets[tmpCurr.rank - 1] = null;
+ }
+ buckets[tmpCurr.rank] = tmpCurr;
+ }
+ return buckets;
+ }
+
+ /*
+ *
+ */
+ private HeapNode fromBuckets(HeapNode[] buckets) {
+ HeapNode tmpMin = null;
+ this.numOfTrees = 0;
+ for (int i = 0; i < buckets.length; i++) {
+ if (buckets[i] != null) {
+ this.numOfTrees++;
+ if (tmpMin == null) {
+ tmpMin = buckets[i];
+ tmpMin.next = tmpMin;
+ tmpMin.prev = tmpMin;
+ } else {
+ tmpMin.setNext(buckets[i]);
+ if (buckets[i].getKey() < tmpMin.getKey()) {
+ tmpMin = buckets[i];
+ }
+ }
+ }
+ }
+ return tmpMin;
+ }
+
+ /*
+ * link between two nodes (and their trees)
+ * defines the smaller node to be the parent
+ */
+ private HeapNode link(HeapNode c1, HeapNode c2) {
+ if (c1.getKey() > c2.getKey()) {
+ HeapNode c3 = c1;
+ c1 = c2;
+ c2 = c3;
+ }
+ if (c1.child == null) {
+ c1.child = c2;
+ } else {
+ c1.child.setNext(c2);
+ }
+ c2.parent = c1;
+ c1.rank++;
+ totalLinks++;
+ return c1;
+ }
+
+
+ /**
+ * public class HeapNode
+ * each HeapNode belongs to a heap (Inner class)
+ */
+ public class HeapNode {
+
+ public int key;
+ private int rank;
+ private boolean marked;
+ private HeapNode child;
+ private HeapNode next;
+ private HeapNode prev;
+ private HeapNode parent;
+
+ /*
+ * a constructor for a heapNode withe key @param (key)
+ * prev == next == this
+ * parent == child == null
+ */
+ public HeapNode(int key) {
+ this.key = key;
+ this.marked = false;
+ this.next = this;
+ this.prev = this;
+ }
+
+ /*
+ * returns the key of the node.
+ */
+ public int getKey() {
+ return this.key;
+ }
+
+
+ /*
+ * checks whether the node is marked
+ * $ret = true if one child has been cut
+ */
+ private boolean isMarked() {
+ return this.marked;
+ }
+
+ /*
+ * mark a node (after a child was cut)
+ * @inv root.mark() == false.
+ */
+ private void mark() {
+ if (this.isRoot()) {
+ return;
+ } //check if the node is a root
+ this.marked = true;
+ }
+
+ /*
+ * add the node @param (newNext) to be between this and this.next
+ * works fine also if @param (newNext) does not "stands" alone
+ */
+ private void setNext(HeapNode newNext) {
+ HeapNode tmpNext = this.next;
+ this.next = newNext;
+ this.next.prev.next = tmpNext;
+ tmpNext.prev = newNext.prev;
+ this.next.prev = this;
+ }
+
+ /*
+ * returns the next node to this node
+ */
+ private HeapNode getNext() {
+ return this.next;
+ }
+
+ /*
+ * check if the node is a root
+ * root definition - this.parent == null (uppest in his tree)
+ */
+ private boolean isRoot() {
+ return (this.parent == null);
+ }
+ }
+}
diff --git a/src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java b/src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java
new file mode 100644
index 000000000000..be72e28a132a
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java
@@ -0,0 +1,21 @@
+package com.thealgorithms.datastructures.heaps;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class FibonacciHeapTest{
+
+ @Test
+ void testHeap(){
+ FibonacciHeap fibonacciHeap = new FibonacciHeap();
+ fibonacciHeap.insert(5);
+ fibonacciHeap.insert(3);
+ fibonacciHeap.insert(1);
+ fibonacciHeap.insert(18);
+ fibonacciHeap.insert(33);
+
+ Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 1);
+ fibonacciHeap.deleteMin();
+ Assertions.assertEquals(fibonacciHeap.findMin().getKey(), 3);
+ }
+}
From f272d8a949d47a1b23474fb418a505c335f139cc Mon Sep 17 00:00:00 2001
From: Omar <59146036+omarmahamid@users.noreply.github.com>
Date: Wed, 4 May 2022 09:24:19 +0300
Subject: [PATCH 0026/1577] Add Bloom Filter (#3042)
---
.../bloomfilter/BloomFilter.java | 59 +++++++++++++++++++
.../datastructures/BloomFilterTest.java | 28 +++++++++
2 files changed, 87 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/BloomFilterTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
new file mode 100644
index 000000000000..ed77bb3c64a7
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
@@ -0,0 +1,59 @@
+package com.thealgorithms.datastructures.bloomfilter;
+
+
+public class BloomFilter {
+
+ private int numberOfHashFunctions;
+ private int [] bitArray;
+ private Hash[] hashFunctions;
+
+ public BloomFilter(int numberOfHashFunctions, int n) {
+ this.numberOfHashFunctions = numberOfHashFunctions;
+ hashFunctions = new Hash[numberOfHashFunctions];
+ bitArray = new int[n];
+ insertHash();
+ }
+
+ private void insertHash() {
+ for (int i = 0; i < numberOfHashFunctions; i++) {
+ hashFunctions[i] = new Hash(i);
+ }
+ }
+
+ public void insert(T key) {
+ for (Hash hash : hashFunctions){
+ bitArray[hash.compute(key) % bitArray.length] = 1;
+ }
+ }
+
+ public boolean contains(T key) {
+ for (Hash hash : hashFunctions){
+ if (bitArray[hash.compute(key) % bitArray.length] == 0){
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private class Hash {
+
+ int index;
+
+ public Hash(int index){
+ this.index = index;
+ }
+
+ public int compute(T key){
+ return index * asciiString(String.valueOf(key));
+ }
+
+ private int asciiString(String word){
+ int number = 0;
+ for (int i=0;i bloomFilter = new BloomFilter<>(3,10);
+ bloomFilter.insert(3);
+ bloomFilter.insert(17);
+
+ Assertions.assertTrue(bloomFilter.contains(3));
+ Assertions.assertTrue(bloomFilter.contains(17));
+ }
+
+ @Test
+ public void test2(){
+ BloomFilter bloomFilter = new BloomFilter<>(4,20);
+ bloomFilter.insert("omar");
+ bloomFilter.insert("mahamid");
+
+ Assertions.assertTrue(bloomFilter.contains("omar"));
+ Assertions.assertTrue(bloomFilter.contains("mahamid"));
+ }
+}
From 9b5dca55349272641b0f3c9c514eef25f2f9cc5b Mon Sep 17 00:00:00 2001
From: Omar <59146036+omarmahamid@users.noreply.github.com>
Date: Thu, 5 May 2022 19:29:20 +0300
Subject: [PATCH 0027/1577] Add directories (#3043)
---
DIRECTORY.md | 3 +++
1 file changed, 3 insertions(+)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 5b3ee19d0eee..a77889d51973 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -6,6 +6,8 @@
* thealgorithms
* audiofilters
* [IIRFilter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java)
+ * bloomfilter
+ * [BloomFilter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java)
* backtracking
* [Combination](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/Combination.java)
* [FloodFill](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/FloodFill.java)
@@ -84,6 +86,7 @@
* [MaxHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java)
* [MinHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java)
* [MinPriorityQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java)
+ * [FibonacciHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java)
* lists
* [CircleLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java)
* [CountSinglyLinkedListRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java)
From 10f41eeee9f75f34adfca7f1444ef5c2641f6ce4 Mon Sep 17 00:00:00 2001
From: Siddhant Swarup Mallick <78552027+siddhant2002@users.noreply.github.com>
Date: Sun, 8 May 2022 14:35:05 +0530
Subject: [PATCH 0028/1577] Add max of mins algorithm (#3044)
---
.../stacks/CalculateMaxOfMin.java | 37 ++++++++++++
.../others/CalculateMaxOfMinTest.java | 56 +++++++++++++++++++
2 files changed, 93 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
create mode 100644 src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
new file mode 100644
index 000000000000..7af1192ad581
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/CalculateMaxOfMin.java
@@ -0,0 +1,37 @@
+/** Author : Siddhant Swarup Mallick
+ * Github : https://github.com/siddhant2002
+ */
+
+/** Program description - Given an integer array. The task is to find the maximum of the minimum of the array */
+package com.thealgorithms.datastructures.stacks;
+
+import java.util.*;
+
+public class CalculateMaxOfMin {
+ public static int calculateMaxOfMin(int[] a) {
+ int n = a.length;
+ int[] ans = new int[n];
+ int[] arr2 = Arrays.copyOf(a, n);
+ Arrays.sort(arr2);
+ int maxNum = arr2[arr2.length - 1];
+ ans[0] = maxNum;
+ int index = 1;
+ while (index != ans.length) {
+ int[] minimums = new int[n - index];
+ for (int i = 0; i < n - index; i++) {
+ int[] windowArray = Arrays.copyOfRange(a, i, i + index + 1);
+ Arrays.sort(windowArray);
+ int minNum = windowArray[0];
+ minimums[i] = minNum;
+ }
+ Arrays.sort(minimums);
+ ans[index] = minimums[minimums.length - 1];
+ index += 1;
+ }
+ return ans[0];
+ }
+}
+/**
+ * Given an integer array. The task is to find the maximum of the minimum of the
+ * given array
+ */
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
new file mode 100644
index 000000000000..c5a02822605e
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
@@ -0,0 +1,56 @@
+package com.thealgorithms.others;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import com.thealgorithms.datastructures.stacks.CalculateMaxOfMin;
+
+public class CalculateMaxOfMinTest {
+ @Test
+ void testForOneElement() {
+ int a[] = { 10, 20, 30, 50, 10, 70, 30 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 70);
+ }
+
+ @Test
+ void testForTwoElements() {
+ int a[] = { 5, 3, 2, 6, 3, 2, 6 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 6);
+ }
+
+ @Test
+ void testForThreeElements() {
+ int a[] = { 10, 10, 10, 10, 10, 10, 10 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 10);
+ }
+
+ @Test
+ void testForFourElements() {
+ int a[] = { 70, 60, 50, 40, 30, 20 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 70);
+ }
+
+ @Test
+ void testForFiveElements() {
+ int a[] = { 50 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 50);
+ }
+
+ @Test
+ void testForSixElements() {
+ int a[] = { 1, 4, 7, 9, 2, 4, 6 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == 9);
+ }
+
+ @Test
+ void testForSevenElements() {
+ int a[] = { -1, -5, -7, -9, -12, -14 };
+ int k = CalculateMaxOfMin.calculateMaxOfMin(a);
+ assertTrue(k == -1);
+ }
+}
\ No newline at end of file
From 239b27406997029745e08cd338de7956b9724a06 Mon Sep 17 00:00:00 2001
From: Raghav Taneja <97575679+RaghavTaneja@users.noreply.github.com>
Date: Wed, 11 May 2022 14:23:56 -0500
Subject: [PATCH 0029/1577] Add Euclidean Distance Formula (#3047)
---
.../thealgorithms/maths/DistanceFormula.java | 11 ++++++++
.../maths/DistanceFormulaTest.java | 28 +++++++++++++++++++
2 files changed, 39 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/maths/DistanceFormula.java
create mode 100644 src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java
diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
new file mode 100644
index 000000000000..cc6ebc9ecaa7
--- /dev/null
+++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
@@ -0,0 +1,11 @@
+package com.thealgorithms.maths;
+
+public class DistanceFormula {
+ public static double distance(double x1, double y1, double x2, double y2)
+ {
+ double dX = Math.pow(x2-x1, 2);
+ double dY = Math.pow(y2-x1, 2);
+ double d = Math.sqrt(dX+dY);
+ return d;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java
new file mode 100644
index 000000000000..e54f12635302
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java
@@ -0,0 +1,28 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class DistanceFormulaTest
+{
+ @Test
+ void test1()
+ {
+ Assertions.assertEquals(DistanceFormula.distance(1,1,2,2), 1.4142135623730951);
+ }
+ @Test
+ void test2()
+ {
+ Assertions.assertEquals(DistanceFormula.distance(1,3,8,0), 7.0710678118654755);
+ }
+ @Test
+ void test3()
+ {
+ Assertions.assertEquals(DistanceFormula.distance(2.4,9.1,55.1,100), 110.91911467371168);
+ }
+ @Test
+ void test4()
+ {
+ Assertions.assertEquals(DistanceFormula.distance(1000,13,20000,84), 19022.067605809836);
+ }
+}
From f9b788f7f46c0432e95f7116987d14937953729c Mon Sep 17 00:00:00 2001
From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com>
Date: Wed, 18 May 2022 22:59:31 +0530
Subject: [PATCH 0030/1577] Add Blowfish Algorithm (#3052)
---
.../com/thealgorithms/ciphers/Blowfish.java | 416 ++++++++++++++++++
.../thealgorithms/ciphers/BlowfishTest.java | 43 ++
2 files changed, 459 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/ciphers/Blowfish.java
create mode 100644 src/test/java/com/thealgorithms/ciphers/BlowfishTest.java
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
new file mode 100644
index 000000000000..f855956f35cd
--- /dev/null
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -0,0 +1,416 @@
+package com.thealgorithms.ciphers;
+
+/*
+ * Java program for Blowfish Algorithm
+ * Wikipedia: https://en.wikipedia.org/wiki/Blowfish_(cipher)
+ *
+ * Author: Akshay Dubey (https://github.com/itsAkshayDubey)
+ *
+ * */
+
+public class Blowfish {
+
+ //Initializing substitution boxes
+ String S[][]
+ = { { "d1310ba6", "98dfb5ac", "2ffd72db", "d01adfb7", "b8e1afed",
+ "6a267e96", "ba7c9045", "f12c7f99", "24a19947", "b3916cf7",
+ "0801f2e2", "858efc16", "636920d8", "71574e69", "a458fea3",
+ "f4933d7e", "0d95748f", "728eb658", "718bcd58", "82154aee",
+ "7b54a41d", "c25a59b5", "9c30d539", "2af26013", "c5d1b023",
+ "286085f0", "ca417918", "b8db38ef", "8e79dcb0", "603a180e",
+ "6c9e0e8b", "b01e8a3e", "d71577c1", "bd314b27", "78af2fda",
+ "55605c60", "e65525f3", "aa55ab94", "57489862", "63e81440",
+ "55ca396a", "2aab10b6", "b4cc5c34", "1141e8ce", "a15486af",
+ "7c72e993", "b3ee1411", "636fbc2a", "2ba9c55d", "741831f6",
+ "ce5c3e16", "9b87931e", "afd6ba33", "6c24cf5c", "7a325381",
+ "28958677", "3b8f4898", "6b4bb9af", "c4bfe81b", "66282193",
+ "61d809cc", "fb21a991", "487cac60", "5dec8032", "ef845d5d",
+ "e98575b1", "dc262302", "eb651b88", "23893e81", "d396acc5",
+ "0f6d6ff3", "83f44239", "2e0b4482", "a4842004", "69c8f04a",
+ "9e1f9b5e", "21c66842", "f6e96c9a", "670c9c61", "abd388f0",
+ "6a51a0d2", "d8542f68", "960fa728", "ab5133a3", "6eef0b6c",
+ "137a3be4", "ba3bf050", "7efb2a98", "a1f1651d", "39af0176",
+ "66ca593e", "82430e88", "8cee8619", "456f9fb4", "7d84a5c3",
+ "3b8b5ebe", "e06f75d8", "85c12073", "401a449f", "56c16aa6",
+ "4ed3aa62", "363f7706", "1bfedf72", "429b023d", "37d0d724",
+ "d00a1248", "db0fead3", "49f1c09b", "075372c9", "80991b7b",
+ "25d479d8", "f6e8def7", "e3fe501a", "b6794c3b", "976ce0bd",
+ "04c006ba", "c1a94fb6", "409f60c4", "5e5c9ec2", "196a2463",
+ "68fb6faf", "3e6c53b5", "1339b2eb", "3b52ec6f", "6dfc511f",
+ "9b30952c", "cc814544", "af5ebd09", "bee3d004", "de334afd",
+ "660f2807", "192e4bb3", "c0cba857", "45c8740f", "d20b5f39",
+ "b9d3fbdb", "5579c0bd", "1a60320a", "d6a100c6", "402c7279",
+ "679f25fe", "fb1fa3cc", "8ea5e9f8", "db3222f8", "3c7516df",
+ "fd616b15", "2f501ec8", "ad0552ab", "323db5fa", "fd238760",
+ "53317b48", "3e00df82", "9e5c57bb", "ca6f8ca0", "1a87562e",
+ "df1769db", "d542a8f6", "287effc3", "ac6732c6", "8c4f5573",
+ "695b27b0", "bbca58c8", "e1ffa35d", "b8f011a0", "10fa3d98",
+ "fd2183b8", "4afcb56c", "2dd1d35b", "9a53e479", "b6f84565",
+ "d28e49bc", "4bfb9790", "e1ddf2da", "a4cb7e33", "62fb1341",
+ "cee4c6e8", "ef20cada", "36774c01", "d07e9efe", "2bf11fb4",
+ "95dbda4d", "ae909198", "eaad8e71", "6b93d5a0", "d08ed1d0",
+ "afc725e0", "8e3c5b2f", "8e7594b7", "8ff6e2fb", "f2122b64",
+ "8888b812", "900df01c", "4fad5ea0", "688fc31c", "d1cff191",
+ "b3a8c1ad", "2f2f2218", "be0e1777", "ea752dfe", "8b021fa1",
+ "e5a0cc0f", "b56f74e8", "18acf3d6", "ce89e299", "b4a84fe0",
+ "fd13e0b7", "7cc43b81", "d2ada8d9", "165fa266", "80957705",
+ "93cc7314", "211a1477", "e6ad2065", "77b5fa86", "c75442f5",
+ "fb9d35cf", "ebcdaf0c", "7b3e89a0", "d6411bd3", "ae1e7e49",
+ "00250e2d", "2071b35e", "226800bb", "57b8e0af", "2464369b",
+ "f009b91e", "5563911d", "59dfa6aa", "78c14389", "d95a537f",
+ "207d5ba2", "02e5b9c5", "83260376", "6295cfa9", "11c81968",
+ "4e734a41", "b3472dca", "7b14a94a", "1b510052", "9a532915",
+ "d60f573f", "bc9bc6e4", "2b60a476", "81e67400", "08ba6fb5",
+ "571be91f", "f296ec6b", "2a0dd915", "b6636521", "e7b9f9b6",
+ "ff34052e", "c5855664", "53b02d5d", "a99f8fa1", "08ba4799",
+ "6e85076a" },
+ { "4b7a70e9", "b5b32944", "db75092e", "c4192623", "ad6ea6b0",
+ "49a7df7d", "9cee60b8", "8fedb266", "ecaa8c71", "699a17ff",
+ "5664526c", "c2b19ee1", "193602a5", "75094c29", "a0591340",
+ "e4183a3e", "3f54989a", "5b429d65", "6b8fe4d6", "99f73fd6",
+ "a1d29c07", "efe830f5", "4d2d38e6", "f0255dc1", "4cdd2086",
+ "8470eb26", "6382e9c6", "021ecc5e", "09686b3f", "3ebaefc9",
+ "3c971814", "6b6a70a1", "687f3584", "52a0e286", "b79c5305",
+ "aa500737", "3e07841c", "7fdeae5c", "8e7d44ec", "5716f2b8",
+ "b03ada37", "f0500c0d", "f01c1f04", "0200b3ff", "ae0cf51a",
+ "3cb574b2", "25837a58", "dc0921bd", "d19113f9", "7ca92ff6",
+ "94324773", "22f54701", "3ae5e581", "37c2dadc", "c8b57634",
+ "9af3dda7", "a9446146", "0fd0030e", "ecc8c73e", "a4751e41",
+ "e238cd99", "3bea0e2f", "3280bba1", "183eb331", "4e548b38",
+ "4f6db908", "6f420d03", "f60a04bf", "2cb81290", "24977c79",
+ "5679b072", "bcaf89af", "de9a771f", "d9930810", "b38bae12",
+ "dccf3f2e", "5512721f", "2e6b7124", "501adde6", "9f84cd87",
+ "7a584718", "7408da17", "bc9f9abc", "e94b7d8c", "ec7aec3a",
+ "db851dfa", "63094366", "c464c3d2", "ef1c1847", "3215d908",
+ "dd433b37", "24c2ba16", "12a14d43", "2a65c451", "50940002",
+ "133ae4dd", "71dff89e", "10314e55", "81ac77d6", "5f11199b",
+ "043556f1", "d7a3c76b", "3c11183b", "5924a509", "f28fe6ed",
+ "97f1fbfa", "9ebabf2c", "1e153c6e", "86e34570", "eae96fb1",
+ "860e5e0a", "5a3e2ab3", "771fe71c", "4e3d06fa", "2965dcb9",
+ "99e71d0f", "803e89d6", "5266c825", "2e4cc978", "9c10b36a",
+ "c6150eba", "94e2ea78", "a5fc3c53", "1e0a2df4", "f2f74ea7",
+ "361d2b3d", "1939260f", "19c27960", "5223a708", "f71312b6",
+ "ebadfe6e", "eac31f66", "e3bc4595", "a67bc883", "b17f37d1",
+ "018cff28", "c332ddef", "be6c5aa5", "65582185", "68ab9802",
+ "eecea50f", "db2f953b", "2aef7dad", "5b6e2f84", "1521b628",
+ "29076170", "ecdd4775", "619f1510", "13cca830", "eb61bd96",
+ "0334fe1e", "aa0363cf", "b5735c90", "4c70a239", "d59e9e0b",
+ "cbaade14", "eecc86bc", "60622ca7", "9cab5cab", "b2f3846e",
+ "648b1eaf", "19bdf0ca", "a02369b9", "655abb50", "40685a32",
+ "3c2ab4b3", "319ee9d5", "c021b8f7", "9b540b19", "875fa099",
+ "95f7997e", "623d7da8", "f837889a", "97e32d77", "11ed935f",
+ "16681281", "0e358829", "c7e61fd6", "96dedfa1", "7858ba99",
+ "57f584a5", "1b227263", "9b83c3ff", "1ac24696", "cdb30aeb",
+ "532e3054", "8fd948e4", "6dbc3128", "58ebf2ef", "34c6ffea",
+ "fe28ed61", "ee7c3c73", "5d4a14d9", "e864b7e3", "42105d14",
+ "203e13e0", "45eee2b6", "a3aaabea", "db6c4f15", "facb4fd0",
+ "c742f442", "ef6abbb5", "654f3b1d", "41cd2105", "d81e799e",
+ "86854dc7", "e44b476a", "3d816250", "cf62a1f2", "5b8d2646",
+ "fc8883a0", "c1c7b6a3", "7f1524c3", "69cb7492", "47848a0b",
+ "5692b285", "095bbf00", "ad19489d", "1462b174", "23820e00",
+ "58428d2a", "0c55f5ea", "1dadf43e", "233f7061", "3372f092",
+ "8d937e41", "d65fecf1", "6c223bdb", "7cde3759", "cbee7460",
+ "4085f2a7", "ce77326e", "a6078084", "19f8509e", "e8efd855",
+ "61d99735", "a969a7aa", "c50c06c2", "5a04abfc", "800bcadc",
+ "9e447a2e", "c3453484", "fdd56705", "0e1e9ec9", "db73dbd3",
+ "105588cd", "675fda79", "e3674340", "c5c43465", "713e38d8",
+ "3d28f89e", "f16dff20", "153e21e7", "8fb03d4a", "e6e39f2b",
+ "db83adf7" },
+ { "e93d5a68", "948140f7", "f64c261c", "94692934", "411520f7",
+ "7602d4f7", "bcf46b2e", "d4a20068", "d4082471", "3320f46a",
+ "43b7d4b7", "500061af", "1e39f62e", "97244546", "14214f74",
+ "bf8b8840", "4d95fc1d", "96b591af", "70f4ddd3", "66a02f45",
+ "bfbc09ec", "03bd9785", "7fac6dd0", "31cb8504", "96eb27b3",
+ "55fd3941", "da2547e6", "abca0a9a", "28507825", "530429f4",
+ "0a2c86da", "e9b66dfb", "68dc1462", "d7486900", "680ec0a4",
+ "27a18dee", "4f3ffea2", "e887ad8c", "b58ce006", "7af4d6b6",
+ "aace1e7c", "d3375fec", "ce78a399", "406b2a42", "20fe9e35",
+ "d9f385b9", "ee39d7ab", "3b124e8b", "1dc9faf7", "4b6d1856",
+ "26a36631", "eae397b2", "3a6efa74", "dd5b4332", "6841e7f7",
+ "ca7820fb", "fb0af54e", "d8feb397", "454056ac", "ba489527",
+ "55533a3a", "20838d87", "fe6ba9b7", "d096954b", "55a867bc",
+ "a1159a58", "cca92963", "99e1db33", "a62a4a56", "3f3125f9",
+ "5ef47e1c", "9029317c", "fdf8e802", "04272f70", "80bb155c",
+ "05282ce3", "95c11548", "e4c66d22", "48c1133f", "c70f86dc",
+ "07f9c9ee", "41041f0f", "404779a4", "5d886e17", "325f51eb",
+ "d59bc0d1", "f2bcc18f", "41113564", "257b7834", "602a9c60",
+ "dff8e8a3", "1f636c1b", "0e12b4c2", "02e1329e", "af664fd1",
+ "cad18115", "6b2395e0", "333e92e1", "3b240b62", "eebeb922",
+ "85b2a20e", "e6ba0d99", "de720c8c", "2da2f728", "d0127845",
+ "95b794fd", "647d0862", "e7ccf5f0", "5449a36f", "877d48fa",
+ "c39dfd27", "f33e8d1e", "0a476341", "992eff74", "3a6f6eab",
+ "f4f8fd37", "a812dc60", "a1ebddf8", "991be14c", "db6e6b0d",
+ "c67b5510", "6d672c37", "2765d43b", "dcd0e804", "f1290dc7",
+ "cc00ffa3", "b5390f92", "690fed0b", "667b9ffb", "cedb7d9c",
+ "a091cf0b", "d9155ea3", "bb132f88", "515bad24", "7b9479bf",
+ "763bd6eb", "37392eb3", "cc115979", "8026e297", "f42e312d",
+ "6842ada7", "c66a2b3b", "12754ccc", "782ef11c", "6a124237",
+ "b79251e7", "06a1bbe6", "4bfb6350", "1a6b1018", "11caedfa",
+ "3d25bdd8", "e2e1c3c9", "44421659", "0a121386", "d90cec6e",
+ "d5abea2a", "64af674e", "da86a85f", "bebfe988", "64e4c3fe",
+ "9dbc8057", "f0f7c086", "60787bf8", "6003604d", "d1fd8346",
+ "f6381fb0", "7745ae04", "d736fccc", "83426b33", "f01eab71",
+ "b0804187", "3c005e5f", "77a057be", "bde8ae24", "55464299",
+ "bf582e61", "4e58f48f", "f2ddfda2", "f474ef38", "8789bdc2",
+ "5366f9c3", "c8b38e74", "b475f255", "46fcd9b9", "7aeb2661",
+ "8b1ddf84", "846a0e79", "915f95e2", "466e598e", "20b45770",
+ "8cd55591", "c902de4c", "b90bace1", "bb8205d0", "11a86248",
+ "7574a99e", "b77f19b6", "e0a9dc09", "662d09a1", "c4324633",
+ "e85a1f02", "09f0be8c", "4a99a025", "1d6efe10", "1ab93d1d",
+ "0ba5a4df", "a186f20f", "2868f169", "dcb7da83", "573906fe",
+ "a1e2ce9b", "4fcd7f52", "50115e01", "a70683fa", "a002b5c4",
+ "0de6d027", "9af88c27", "773f8641", "c3604c06", "61a806b5",
+ "f0177a28", "c0f586e0", "006058aa", "30dc7d62", "11e69ed7",
+ "2338ea63", "53c2dd94", "c2c21634", "bbcbee56", "90bcb6de",
+ "ebfc7da1", "ce591d76", "6f05e409", "4b7c0188", "39720a3d",
+ "7c927c24", "86e3725f", "724d9db9", "1ac15bb4", "d39eb8fc",
+ "ed545578", "08fca5b5", "d83d7cd3", "4dad0fc4", "1e50ef5e",
+ "b161e6f8", "a28514d9", "6c51133c", "6fd5c7e7", "56e14ec4",
+ "362abfce", "ddc6c837", "d79a3234", "92638212", "670efa8e",
+ "406000e0" },
+ { "3a39ce37", "d3faf5cf", "abc27737", "5ac52d1b", "5cb0679e",
+ "4fa33742", "d3822740", "99bc9bbe", "d5118e9d", "bf0f7315",
+ "d62d1c7e", "c700c47b", "b78c1b6b", "21a19045", "b26eb1be",
+ "6a366eb4", "5748ab2f", "bc946e79", "c6a376d2", "6549c2c8",
+ "530ff8ee", "468dde7d", "d5730a1d", "4cd04dc6", "2939bbdb",
+ "a9ba4650", "ac9526e8", "be5ee304", "a1fad5f0", "6a2d519a",
+ "63ef8ce2", "9a86ee22", "c089c2b8", "43242ef6", "a51e03aa",
+ "9cf2d0a4", "83c061ba", "9be96a4d", "8fe51550", "ba645bd6",
+ "2826a2f9", "a73a3ae1", "4ba99586", "ef5562e9", "c72fefd3",
+ "f752f7da", "3f046f69", "77fa0a59", "80e4a915", "87b08601",
+ "9b09e6ad", "3b3ee593", "e990fd5a", "9e34d797", "2cf0b7d9",
+ "022b8b51", "96d5ac3a", "017da67d", "d1cf3ed6", "7c7d2d28",
+ "1f9f25cf", "adf2b89b", "5ad6b472", "5a88f54c", "e029ac71",
+ "e019a5e6", "47b0acfd", "ed93fa9b", "e8d3c48d", "283b57cc",
+ "f8d56629", "79132e28", "785f0191", "ed756055", "f7960e44",
+ "e3d35e8c", "15056dd4", "88f46dba", "03a16125", "0564f0bd",
+ "c3eb9e15", "3c9057a2", "97271aec", "a93a072a", "1b3f6d9b",
+ "1e6321f5", "f59c66fb", "26dcf319", "7533d928", "b155fdf5",
+ "03563482", "8aba3cbb", "28517711", "c20ad9f8", "abcc5167",
+ "ccad925f", "4de81751", "3830dc8e", "379d5862", "9320f991",
+ "ea7a90c2", "fb3e7bce", "5121ce64", "774fbe32", "a8b6e37e",
+ "c3293d46", "48de5369", "6413e680", "a2ae0810", "dd6db224",
+ "69852dfd", "09072166", "b39a460a", "6445c0dd", "586cdecf",
+ "1c20c8ae", "5bbef7dd", "1b588d40", "ccd2017f", "6bb4e3bb",
+ "dda26a7e", "3a59ff45", "3e350a44", "bcb4cdd5", "72eacea8",
+ "fa6484bb", "8d6612ae", "bf3c6f47", "d29be463", "542f5d9e",
+ "aec2771b", "f64e6370", "740e0d8d", "e75b1357", "f8721671",
+ "af537d5d", "4040cb08", "4eb4e2cc", "34d2466a", "0115af84",
+ "e1b00428", "95983a1d", "06b89fb4", "ce6ea048", "6f3f3b82",
+ "3520ab82", "011a1d4b", "277227f8", "611560b1", "e7933fdc",
+ "bb3a792b", "344525bd", "a08839e1", "51ce794b", "2f32c9b7",
+ "a01fbac9", "e01cc87e", "bcc7d1f6", "cf0111c3", "a1e8aac7",
+ "1a908749", "d44fbd9a", "d0dadecb", "d50ada38", "0339c32a",
+ "c6913667", "8df9317c", "e0b12b4f", "f79e59b7", "43f5bb3a",
+ "f2d519ff", "27d9459c", "bf97222c", "15e6fc2a", "0f91fc71",
+ "9b941525", "fae59361", "ceb69ceb", "c2a86459", "12baa8d1",
+ "b6c1075e", "e3056a0c", "10d25065", "cb03a442", "e0ec6e0e",
+ "1698db3b", "4c98a0be", "3278e964", "9f1f9532", "e0d392df",
+ "d3a0342b", "8971f21e", "1b0a7441", "4ba3348c", "c5be7120",
+ "c37632d8", "df359f8d", "9b992f2e", "e60b6f47", "0fe3f11d",
+ "e54cda54", "1edad891", "ce6279cf", "cd3e7e6f", "1618b166",
+ "fd2c1d05", "848fd2c5", "f6fb2299", "f523f357", "a6327623",
+ "93a83531", "56cccd02", "acf08162", "5a75ebb5", "6e163697",
+ "88d273cc", "de966292", "81b949d0", "4c50901b", "71c65614",
+ "e6c6c7bd", "327a140a", "45e1d006", "c3f27b9a", "c9aa53fd",
+ "62a80f00", "bb25bfe2", "35bdd2f6", "71126905", "b2040222",
+ "b6cbcf7c", "cd769c2b", "53113ec0", "1640e3d3", "38abbd60",
+ "2547adf0", "ba38209c", "f746ce76", "77afa1c5", "20756060",
+ "85cbfe4e", "8ae88dd8", "7aaaf9b0", "4cf9aa7e", "1948c25c",
+ "02fb8a8c", "01c36ae4", "d6ebe1f9", "90d4f869", "a65cdea0",
+ "3f09252d", "c208e69f", "b74e6132", "ce77e25b", "578fdfe3",
+ "3ac372e6" } };
+
+ //Initializing subkeys with digits of pi
+ String P[] = { "243f6a88", "85a308d3", "13198a2e", "03707344", "a4093822",
+ "299f31d0", "082efa98", "ec4e6c89", "452821e6", "38d01377",
+ "be5466cf", "34e90c6c", "c0ac29b7", "c97c50dd", "3f84d5b5",
+ "b5470917", "9216d5d9", "8979fb1b" };
+
+ //Initializing modVal to 2^32
+ long modVal = 4294967296L;
+
+
+ /**
+ * This method returns binary representation of the hexadecimal number passed as parameter
+ *
+ * @param hex Number for which binary representation is required
+ * @return String object which is a binary representation of the hex number passed as parameter
+ */
+ private String hexToBin(String hex)
+ {
+ String binary = "";
+ Long num;
+ String binary4B;
+ int n = hex.length();
+ for (int i = 0; i < n; i++) {
+
+ num = Long.parseUnsignedLong(
+ hex.charAt(i) + "", 16);
+ binary4B = Long.toBinaryString(num);
+
+ binary4B = "0000" + binary4B;
+
+ binary4B = binary4B.substring(binary4B.length() - 4);
+ binary += binary4B;
+ }
+ return binary;
+ }
+
+ /**
+ * This method returns hexadecimal representation of the binary number passed as parameter
+ *
+ * @param binary Number for which hexadecimal representation is required
+ * @return String object which is a hexadecimal representation of the binary number passed as parameter
+ */
+ private String binToHex(String binary)
+ {
+
+ long num = Long.parseUnsignedLong(binary, 2);
+ String hex = Long.toHexString(num);
+ while (hex.length() < (binary.length() / 4))
+ hex = "0" + hex;
+
+ return hex;
+ }
+
+ /**
+ * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters
+ *
+ * @param String a and b are string objects which will be XORed and are to be of same length
+ * @return String object obtained by XOR operation on String a and String b
+ * */
+ private String xor(String a, String b)
+ {
+ a = hexToBin(a);
+ b = hexToBin(b);
+ String ans = "";
+ for (int i = 0; i < a.length(); i++)
+ ans += (char)(((a.charAt(i) - '0')
+ ^ (b.charAt(i) - '0'))
+ + '0');
+ ans = binToHex(ans);
+ return ans;
+ }
+
+ /**
+ * This method returns addition of two hexadecimal numbers passed as parameters and moded with 2^32
+ *
+ * @param String a and b are hexadecimal numbers
+ * @return String object which is a is addition that is then moded with 2^32 of hex numbers passed as parameters
+ */
+ private String addBin(String a, String b)
+ {
+ String ans = "";
+ long n1 = Long.parseUnsignedLong(a, 16);
+ long n2 = Long.parseUnsignedLong(b, 16);
+ n1 = (n1 + n2) % modVal;
+ ans = Long.toHexString(n1);
+ ans = "00000000" + ans;
+ return ans.substring(ans.length() - 8);
+ }
+
+ /*F-function splits the 32-bit input into four 8-bit quarters
+ and uses the quarters as input to the S-boxes.
+ The S-boxes accept 8-bit input and produce 32-bit output.
+ The outputs are added modulo 232 and XORed to produce the final 32-bit output
+ */
+ private String f(String plainText)
+ {
+ String a[] = new String[4];
+ String ans = "";
+ for (int i = 0; i < 8; i += 2) {
+ //column number for S-box is a 8-bit value
+ long col
+ = Long.parseUnsignedLong(
+ hexToBin(
+ plainText
+ .substring(i, i + 2)),
+ 2);
+ a[i / 2] = S[i / 2][(int)col];
+ }
+ ans = addBin(a[0], a[1]);
+ ans = xor(ans, a[2]);
+ ans = addBin(ans, a[3]);
+ return ans;
+ }
+
+ //generate subkeys
+ private void keyGenerate(String key)
+ {
+ int j = 0;
+ for (int i = 0; i < P.length; i++) {
+
+ //XOR-ing 32-bit parts of the key with initial subkeys
+ P[i] = xor(P[i], key.substring(j, j + 8));
+
+ j = (j + 8) % key.length();
+ }
+ }
+
+ //round function
+ private String round(int time, String plainText)
+ {
+ String left, right;
+ left = plainText.substring(0, 8);
+ right = plainText.substring(8, 16);
+ left = xor(left, P[time]);
+
+ //output from F function
+ String fOut = f(left);
+
+ right = xor(fOut, right);
+
+ //swap left and right
+ return right + left;
+ }
+
+ /**
+ * This method returns cipher text for the plaintext passed as the first parameter generated
+ * using the key passed as the second parameter
+ *
+ * @param String plainText is the text which is to be encrypted
+ * @param String key is the key which is to be used for generating cipher text
+ * @return String cipherText is the encrypted value
+ */
+ String encrypt(String plainText, String key)
+ {
+ //generating key
+ keyGenerate(key);
+
+ for (int i = 0; i < 16; i++)
+ plainText = round(i, plainText);
+
+ //postprocessing
+ String right = plainText.substring(0, 8);
+ String left = plainText.substring(8, 16);
+ right = xor(right, P[16]);
+ left = xor(left, P[17]);
+ return left + right;
+ }
+
+ /**
+ * This method returns plaintext for the ciphertext passed as the first parameter decoded
+ * using the key passed as the second parameter
+ *
+ * @param String ciphertext is the text which is to be decrypted
+ * @param String key is the key which is to be used for generating cipher text
+ * @return String plainText is the decrypted text
+ */
+ String decrypt(String cipherText,String key)
+ {
+ //generating key
+ keyGenerate(key);
+
+ for (int i = 17; i > 1; i--)
+ cipherText = round(i, cipherText);
+
+ //postprocessing
+ String right = cipherText.substring(0, 8);
+ String left = cipherText.substring(8, 16);
+ right = xor(right, P[1]);
+ left = xor(left, P[0]);
+ return left + right;
+ }
+
+}
diff --git a/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java
new file mode 100644
index 000000000000..6af37f18bb4b
--- /dev/null
+++ b/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java
@@ -0,0 +1,43 @@
+package com.thealgorithms.ciphers;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class BlowfishTest {
+
+ Blowfish blowfish = new Blowfish();
+
+ @Test
+ void testEncrypt() {
+
+ //given
+ String plainText = "123456abcd132536";
+ String key = "aabb09182736ccdd";
+ String expectedOutput = "d748ec383d3405f7";
+
+ //when
+ String cipherText = blowfish.encrypt(plainText, key);
+
+ //then
+ assertEquals(expectedOutput, cipherText);
+
+ }
+
+ @Test
+ void testDecrypt() {
+
+ //given
+ String cipherText = "d748ec383d3405f7";
+ String key = "aabb09182736ccdd";
+ String expectedOutput = "123456abcd132536";
+
+ //when
+ String plainText = blowfish.decrypt(cipherText, key);
+
+ //then
+ assertEquals(expectedOutput, plainText);
+
+ }
+
+}
From 550adb22870647524516e404ceae974d98e1c764 Mon Sep 17 00:00:00 2001
From: Sahil Parekh <35810976+Sahil3198@users.noreply.github.com>
Date: Fri, 20 May 2022 14:19:18 -0300
Subject: [PATCH 0031/1577] Fix Bug in Tim Sort (#3050)
Co-authored-by: Sahil Prafulkumar Parekh
Co-authored-by: Andrii Siriak
---
src/main/java/com/thealgorithms/sorts/TimSort.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/TimSort.java b/src/main/java/com/thealgorithms/sorts/TimSort.java
index 6f9a3a10a785..bd824a614193 100644
--- a/src/main/java/com/thealgorithms/sorts/TimSort.java
+++ b/src/main/java/com/thealgorithms/sorts/TimSort.java
@@ -71,10 +71,10 @@ public TimSort() {
* sorting.
*/
public void insertion_sort(int[] array, int start_idx, int end_idx) {
- for (int i = 0; i < array.length; i++) {
+ for (int i = start_idx; i <= end_idx; i++) {
int current_element = array[i];
int j = i - 1;
- while (j >= 0 && array[j] > current_element) {
+ while (j >= start_idx && array[j] > current_element) {
array[j + 1] = array[j];
j--;
}
From f35eef285a2c39c28d2bded6ba5f2065f8d4ea79 Mon Sep 17 00:00:00 2001
From: Anh Pham <62592224+anhpham197@users.noreply.github.com>
Date: Wed, 25 May 2022 17:46:20 +0700
Subject: [PATCH 0032/1577] Add tests for GCD and PrimeCheck (#3062)
---
.../java/com/thealgorithms/maths/GCDTest.java | 41 +++++++++++++++++++
.../thealgorithms/maths/PrimeCheckTest.java | 41 +++++++++++++++++++
2 files changed, 82 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/GCDTest.java
create mode 100644 src/test/java/com/thealgorithms/maths/PrimeCheckTest.java
diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java
new file mode 100644
index 000000000000..3f4d9393465d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/GCDTest.java
@@ -0,0 +1,41 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class GCDTest {
+ @Test
+ void test1() {
+ Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-1,0));
+ }
+
+ @Test
+ void test2() {
+ Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(10, -2));
+ }
+
+ @Test
+ void test3() {
+ Assertions.assertThrows(ArithmeticException.class, () -> GCD.gcd(-5, -3));
+ }
+
+ @Test
+ void test4() {
+ Assertions.assertEquals(GCD.gcd(0, 2), 2);
+ }
+
+ @Test
+ void test5() {
+ Assertions.assertEquals(GCD.gcd(10, 0), 10);
+ }
+
+ @Test
+ void test6() {
+ Assertions.assertEquals(GCD.gcd(1, 0), 1);
+ }
+
+ @Test
+ void test7() {
+ Assertions.assertEquals(GCD.gcd(9, 6), 3);
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java b/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java
new file mode 100644
index 000000000000..59fe78525346
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/PrimeCheckTest.java
@@ -0,0 +1,41 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class PrimeCheckTest {
+ @Test
+ void test1() {
+ Assertions.assertTrue(PrimeCheck.isPrime(2));
+ }
+
+ @Test
+ void test2() {
+ Assertions.assertFalse(PrimeCheck.isPrime(-1));
+ }
+
+ @Test
+ void test3() {
+ Assertions.assertFalse(PrimeCheck.isPrime(4));
+ }
+
+ @Test
+ void test4() {
+ Assertions.assertTrue(PrimeCheck.isPrime(5));
+ }
+
+ @Test
+ void test5() {
+ Assertions.assertFalse(PrimeCheck.isPrime(15));
+ }
+
+ @Test
+ void test6() {
+ Assertions.assertTrue(PrimeCheck.isPrime(11));
+ }
+
+ @Test
+ void test7() {
+ Assertions.assertFalse(PrimeCheck.isPrime(49));
+ }
+}
From 2e09e44a38d9184f312d69f1ae046f5addb6ef1f Mon Sep 17 00:00:00 2001
From: SanOtaku
Date: Thu, 26 May 2022 15:17:23 +0530
Subject: [PATCH 0033/1577] Add ZigZag Encoding and Longest Nonrepetitive
Substring Algorithms (#3058)
---
.../strings/longestNonRepeativeSubstring.java | 47 +++++++++++++++++++
.../strings/zigZagPattern/README.md | 36 ++++++++++++++
.../strings/zigZagPattern/zigZagPattern.java | 30 ++++++++++++
.../longestNonRepeativeSubstringTest.java | 14 ++++++
.../zigZagPattern/zigZagPatternTest.java | 14 ++++++
5 files changed, 141 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java
create mode 100644 src/main/java/com/thealgorithms/strings/zigZagPattern/README.md
create mode 100644 src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
create mode 100644 src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java
create mode 100644 src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java
diff --git a/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java
new file mode 100644
index 000000000000..8cb456ae5538
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/longestNonRepeativeSubstring.java
@@ -0,0 +1,47 @@
+package com.thealgorithms.strings ;
+import java.util.HashMap ;
+class longestNonRepeativeSubstring {
+
+ public static int lengthOfLongestSubstring(String s) {
+
+ int max = 0 , start = 0 , i = 0 ;
+ HashMap< Character , Integer > map = new HashMap<>() ;
+
+ while ( i < s.length() ) {
+
+ char temp = s.charAt( i ) ;
+
+ // adding key to map if not present
+ if ( ! map.containsKey( temp ) )
+ map.put( temp , 0 ) ;
+
+ // checking if the first value is the dublicate value
+ else if ( s.charAt( start ) == temp )
+ start++ ;
+
+ // checking if the previous value is dublicate value
+ else if ( s.charAt( i - 1 ) == temp ) {
+ if ( max < map.size() ) max = map.size() ;
+ map = new HashMap<>() ;
+ start = i ;
+ i-- ;
+ }
+
+ // last possible place where dublicate value can be is between start and i
+ else {
+ if ( max < map.size() ) max = map.size() ;
+ while ( s.charAt( start ) != temp ) {
+ map.remove( s.charAt( start ) ) ;
+ start++ ;
+ }
+ start++ ;
+ }
+
+ i++ ;
+
+ }
+ if ( max < map.size() ) max = map.size() ;
+ return max ;
+ }
+
+}
diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/README.md b/src/main/java/com/thealgorithms/strings/zigZagPattern/README.md
new file mode 100644
index 000000000000..17e5ba6e26d8
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/README.md
@@ -0,0 +1,36 @@
+# About
+
+convert string into a zig-zagged string
+
+for example :
+
+ string = "123456789" , numRows = 3
+ ans = "159246837"
+ explanation
+ 1 5 9
+ 2 4 6 8
+ 3 7
+
+ string = "HelloWorldKotlin" , k = 4
+ ans = "HoteWrollolKildn"
+ explanation
+ H o t
+ e W r o l
+ l o l K i
+ l d n
+
+# working
+
+ if string size is smaller than numRows or numRows is smaller than 2
+ than we can return string because it will make no changes to string.
+ If not than
+ we initiate three variable depth which is equalvalent to numRows ,
+ height which starts with 1 and start with starting index of string.
+ than we generate spaces to skip using formula 2 + (( n - 1 ) * 2 )
+ for both height and depth
+ with each iteration we decrement depth and increate height and start
+ by one also we keep contantating character on to new string with first
+ depth spaces and later height spaces that we generated using formula
+ if not zero
+
+# beats 80% of submission on leetcode
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
new file mode 100644
index 000000000000..e0e019706de8
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java
@@ -0,0 +1,30 @@
+package com.thealgorithms.strings.zigZagPattern;
+class zigZagPattern {
+
+ public static String encode(String s, int numRows) {
+ if ( numRows < 2 || s.length() < numRows ) return s ;
+ int start = 0 , index = 0 , height = 1 , depth = numRows ;
+ char[] zigZagedArray = new char[ s.length() ] ;
+ while ( depth != 0 ) {
+ int pointer = start , height_space = 2 + ( ( height - 2 ) * 2 ) , depth_space = 2 + ( ( depth - 2 ) * 2 ) ;
+ boolean bool = true ;
+ while ( pointer < s.length() ) {
+ zigZagedArray[index++] = s.charAt( pointer ) ;
+ if ( height_space == 0 ) pointer += depth_space ;
+ else if ( depth_space == 0 ) pointer += height_space ;
+ else if ( bool ) {
+ pointer += depth_space ;
+ bool = false ;
+ } else {
+ pointer += height_space ;
+ bool = true ;
+ }
+ }
+ height++ ;
+ depth-- ;
+ start++ ;
+ }
+ return new String( zigZagedArray ) ;
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java
new file mode 100644
index 000000000000..f8bc63562487
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java
@@ -0,0 +1,14 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class longestNonRepeativeSubstringTest {
+ @Test
+ public void palindrome() {
+ String input1 = "HelloWorld";
+ String input2 = "javaIsAProgrammingLanguage";
+ Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input1 ) , 5 ) ;
+ Assertions.assertEquals( longestNonRepeativeSubstring.lengthOfLongestSubstring( input2 ) , 9 ) ;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java
new file mode 100644
index 000000000000..6c0e0333b338
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/zigZagPattern/zigZagPatternTest.java
@@ -0,0 +1,14 @@
+package com.thealgorithms.strings.zigZagPattern;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class zigZagPatternTest {
+ @Test
+ public void palindrome() {
+ String input1 = "HelloWorldFromJava";
+ String input2 = "javaIsAProgrammingLanguage";
+ Assertions.assertEquals( zigZagPattern.encode( input1 , 4 ) , "HooeWrrmalolFJvlda" ) ;
+ Assertions.assertEquals( zigZagPattern.encode( input2 , 4 ) , "jAaLgasPrmgaaevIrgmnnuaoig" ) ;
+ }
+}
From bb5b50dea2a6781c1eb8a0c003d0d1839d1319e0 Mon Sep 17 00:00:00 2001
From: Raghav Taneja <97575679+RaghavTaneja@users.noreply.github.com>
Date: Sun, 29 May 2022 03:16:04 -0500
Subject: [PATCH 0034/1577] Add Z-Score Algorithm (#3065)
Co-authored-by: Andrii Siriak
---
.../thealgorithms/maths/StandardScore.java | 9 +++++++
.../maths/StandardScoreTest.java | 27 +++++++++++++++++++
2 files changed, 36 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/maths/StandardScore.java
create mode 100644 src/test/java/com/thealgorithms/maths/StandardScoreTest.java
diff --git a/src/main/java/com/thealgorithms/maths/StandardScore.java b/src/main/java/com/thealgorithms/maths/StandardScore.java
new file mode 100644
index 000000000000..fc794e1ec508
--- /dev/null
+++ b/src/main/java/com/thealgorithms/maths/StandardScore.java
@@ -0,0 +1,9 @@
+package com.thealgorithms.maths;
+
+public class StandardScore {
+ public static double zScore(double num, double mean, double stdDev)
+ {
+ double z = (num - mean)/stdDev;
+ return z;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/StandardScoreTest.java b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java
new file mode 100644
index 000000000000..3ff05007fc66
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/StandardScoreTest.java
@@ -0,0 +1,27 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class StandardScoreTest{
+ @Test
+ void test1()
+ {
+ Assertions.assertEquals(StandardScore.zScore(2, 0, 5), 0.4);
+ }
+ @Test
+ void test2()
+ {
+ Assertions.assertEquals(StandardScore.zScore(1, 1, 1), 0.0);
+ }
+ @Test
+ void test3()
+ {
+ Assertions.assertEquals(StandardScore.zScore(2.5, 1.8, 0.7), 1.0);
+ }
+ @Test
+ void test4()
+ {
+ Assertions.assertEquals(StandardScore.zScore(8.9, 3, 4.2), 1.4047619047619049);
+ }
+}
From e5057defa7c157368b34bf5ba7a0a1cda18bb3ac Mon Sep 17 00:00:00 2001
From: Hai Nguyen <88832724+ntquanghai@users.noreply.github.com>
Date: Mon, 30 May 2022 18:11:30 +0700
Subject: [PATCH 0035/1577] Add tests for findMax (#3067)
---
.../java/com/thealgorithms/maths/FindMaxTest.java | 12 ++++++++++++
1 file changed, 12 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/FindMaxTest.java
diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
new file mode 100644
index 000000000000..cc6577f0aa3d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
@@ -0,0 +1,12 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class FindMaxTest {
+
+ @Test
+ public void testFindMaxValue(){
+ assertEquals(10, FindMax.findMax(new int[] {1,2,3,4,5,6,7,8,9,10}));
+ }
+}
From 2bcae52dce46dab3496fd6dc0b31cbe3716e891c Mon Sep 17 00:00:00 2001
From: Utkarsh Yadav
Date: Tue, 31 May 2022 18:42:59 +0530
Subject: [PATCH 0036/1577] Rename CPUalgorithms to MemoryManagmentAlgorithms
(#3071)
---
...algorithms.java => MemoryManagementAlgorithms.java} | 10 +++++-----
.../java/com/thealgorithms/others/BestFitCPUTest.java | 4 ++--
.../java/com/thealgorithms/others/FirstFitCPUTest.java | 4 ++--
.../java/com/thealgorithms/others/NextFitTest.java | 4 ++--
.../java/com/thealgorithms/others/WorstFitCPUTest.java | 4 ++--
5 files changed, 13 insertions(+), 13 deletions(-)
rename src/main/java/com/thealgorithms/others/{CPUalgorithms.java => MemoryManagementAlgorithms.java} (97%)
diff --git a/src/main/java/com/thealgorithms/others/CPUalgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
similarity index 97%
rename from src/main/java/com/thealgorithms/others/CPUalgorithms.java
rename to src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
index 89205f98169f..a5b5d44ea4d1 100644
--- a/src/main/java/com/thealgorithms/others/CPUalgorithms.java
+++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
@@ -5,7 +5,7 @@
import java.util.ArrayList;
-public abstract class CPUalgorithms {
+public abstract class MemoryManagementAlgorithms {
/**
* Method to allocate memory to blocks according to CPU algorithms.
@@ -26,7 +26,7 @@ public abstract class CPUalgorithms {
/**
* @author Dekas Dimitrios
*/
-class BestFitCPU extends CPUalgorithms{
+class BestFitCPU extends MemoryManagementAlgorithms {
private static final int NO_ALLOCATION
= -255; // if a process has been allocated in position -255,
@@ -110,7 +110,7 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses)
/**
* @author Dekas Dimitrios
*/
-class WorstFitCPU extends CPUalgorithms{
+class WorstFitCPU extends MemoryManagementAlgorithms {
private static final int NO_ALLOCATION
= -255; // if a process has been allocated in position -255,
@@ -177,7 +177,7 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses)
/**
* @author Dekas Dimitrios
*/
-class FirstFitCPU extends CPUalgorithms{
+class FirstFitCPU extends MemoryManagementAlgorithms {
private static final int NO_ALLOCATION
= -255; // if a process has been allocated in position -255,
@@ -236,7 +236,7 @@ public ArrayList fitProcess(int[] sizeOfBlocks, int[] sizeOfProcesses)
/**
* @author Alexandros Lemonaris
*/
-class NextFit extends CPUalgorithms{
+class NextFit extends MemoryManagementAlgorithms {
private static final int NO_ALLOCATION
= -255; // if a process has been allocated in position -255,
diff --git a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java
index d1ab591655d3..ecc66da69c33 100644
--- a/src/test/java/com/thealgorithms/others/BestFitCPUTest.java
+++ b/src/test/java/com/thealgorithms/others/BestFitCPUTest.java
@@ -16,7 +16,7 @@ class BestFitCPUTest {
int [] sizeOfProcesses;
ArrayList memAllocation = new ArrayList<>();
ArrayList testMemAllocation ;
- CPUalgorithms bestFit = new BestFitCPU();
+ MemoryManagementAlgorithms bestFit = new BestFitCPU();
@Test
void testFitForUseOfOneBlock() {
@@ -73,4 +73,4 @@ void testFitForMoreBlocksNoFit() {
);
assertEquals(testMemAllocation, memAllocation);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java
index 45a501c268b0..18dae6807c0e 100644
--- a/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java
+++ b/src/test/java/com/thealgorithms/others/FirstFitCPUTest.java
@@ -16,7 +16,7 @@ class FirstFitCPUTest {
int [] sizeOfProcesses;
ArrayList memAllocation = new ArrayList<>();
ArrayList testMemAllocation ;
- CPUalgorithms firstFit = new FirstFitCPU();
+ MemoryManagementAlgorithms firstFit = new FirstFitCPU();
@Test
void testFitForUseOfOneBlock() {
@@ -73,4 +73,4 @@ void testFitForMoreBlocksNoFit() {
);
assertEquals(testMemAllocation, memAllocation);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/com/thealgorithms/others/NextFitTest.java b/src/test/java/com/thealgorithms/others/NextFitTest.java
index 27c17eaf0369..5a9206df7b3b 100644
--- a/src/test/java/com/thealgorithms/others/NextFitTest.java
+++ b/src/test/java/com/thealgorithms/others/NextFitTest.java
@@ -16,7 +16,7 @@ class NextFitCPUTest {
int [] sizeOfProcesses;
ArrayList memAllocation = new ArrayList<>();
ArrayList testMemAllocation ;
- CPUalgorithms nextFit = new NextFit();
+ MemoryManagementAlgorithms nextFit = new NextFit();
@Test
void testFitForUseOfOneBlock() {
@@ -73,4 +73,4 @@ void testFitForMoreBlocksNoFit() {
);
assertEquals(testMemAllocation, memAllocation);
}
-}
\ No newline at end of file
+}
diff --git a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java
index cb3f58a4c49a..5e9e2a78347e 100644
--- a/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java
+++ b/src/test/java/com/thealgorithms/others/WorstFitCPUTest.java
@@ -16,7 +16,7 @@ class WorstFitCPUTest {
int [] sizeOfProcesses;
ArrayList memAllocation = new ArrayList<>();
ArrayList testMemAllocation ;
- CPUalgorithms worstFit = new WorstFitCPU();
+ MemoryManagementAlgorithms worstFit = new WorstFitCPU();
@Test
void testFitForUseOfOneBlock() {
@@ -84,4 +84,4 @@ void testFitBadCase() {
);
assertEquals(testMemAllocation, memAllocation);
}
-}
\ No newline at end of file
+}
From 2fb87c37fca552eef19db9bb57877257adccb468 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ph=E1=BA=A1m=20Minh=20Hi=E1=BA=BFu?=
<84634830+Ph1eu@users.noreply.github.com>
Date: Thu, 2 Jun 2022 21:21:40 +0700
Subject: [PATCH 0037/1577] Add tests for PythagoreanTriple (#3070)
---
.../maths/PythagoreanTripleTest.java | 20 +++++++++++++++++++
1 file changed, 20 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java
diff --git a/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java b/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java
new file mode 100644
index 000000000000..b0d88da66223
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/PythagoreanTripleTest.java
@@ -0,0 +1,20 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class PythagoreanTripleTest {
+ @Test
+ public void Testpythagoreantriple(){
+
+ assertEquals(true, PythagoreanTriple.isPythagTriple(3,4,5));
+ assertEquals(true, PythagoreanTriple.isPythagTriple(6,8,10));
+ assertEquals(true, PythagoreanTriple.isPythagTriple(9,12,15));
+ assertEquals(true, PythagoreanTriple.isPythagTriple(12,16,20));
+ assertEquals(true, PythagoreanTriple.isPythagTriple(15,20,25));
+ assertEquals(true, PythagoreanTriple.isPythagTriple(18,24,30));
+ assertEquals(false, PythagoreanTriple.isPythagTriple(5,20,30));
+ assertEquals(false, PythagoreanTriple.isPythagTriple(6,8,100));
+ assertEquals(false, PythagoreanTriple.isPythagTriple(-2,-2,2));
+ }
+}
From 8e8d11a63c523202c95b39c7da6e44984db22a30 Mon Sep 17 00:00:00 2001
From: nguyenviettrung-bi11276
<101244039+nguyenviettrung-bi11276@users.noreply.github.com>
Date: Sat, 4 Jun 2022 23:49:37 +0700
Subject: [PATCH 0038/1577] Add Tests for FindMin (#3079)
---
.../com/thealgorithms/maths/FindMinTest.java | 17 +++++++++++++++++
1 file changed, 17 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/FindMinTest.java
diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java
new file mode 100644
index 000000000000..d6724c778d2f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java
@@ -0,0 +1,17 @@
+package com.thealgorithms.maths;
+
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class FindMinTest {
+ @Test
+ public void test1(){
+ assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9}));
+ }
+
+ @Test
+ public void test2(){
+ assertEquals(0, FindMin.findMin(new int[] {0, 192, 384, 576}));
+ }
+}
From 9b4ac70403dd2816309ab9b9cfb31de44ee36615 Mon Sep 17 00:00:00 2001
From: TaiNguyen2001 <102779475+TaiNguyen2001@users.noreply.github.com>
Date: Tue, 7 Jun 2022 12:21:46 +0700
Subject: [PATCH 0039/1577] Add more tests for findMin (#3102)
Co-authored-by: Andrii Siriak
---
src/test/java/com/thealgorithms/maths/FindMinTest.java | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java
index d6724c778d2f..d125151613fd 100644
--- a/src/test/java/com/thealgorithms/maths/FindMinTest.java
+++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java
@@ -1,10 +1,14 @@
package com.thealgorithms.maths;
-
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class FindMinTest {
+ @Test
+ public void testFindMinValue(){
+ assertEquals(1, FindMin.findMin(new int[] {1,2,3,4,5,6,7,8,9,10}));
+ }
+
@Test
public void test1(){
assertEquals(1, FindMin.findMin(new int[] {1, 3, 5, 7, 9}));
From 77e481336ef147033811ea7f3d2e763089ace18c Mon Sep 17 00:00:00 2001
From: de <88503943+HuyQHoang@users.noreply.github.com>
Date: Wed, 8 Jun 2022 22:15:01 +0700
Subject: [PATCH 0040/1577] Add test for Armstrong (#3104)
Co-authored-by: Andrii Siriak
---
.../com/thealgorithms/maths/TestArmstrong.java | 15 +++++++++++++++
1 file changed, 15 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/TestArmstrong.java
diff --git a/src/test/java/com/thealgorithms/maths/TestArmstrong.java b/src/test/java/com/thealgorithms/maths/TestArmstrong.java
new file mode 100644
index 000000000000..afc1ff8a4b61
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/TestArmstrong.java
@@ -0,0 +1,15 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class TestArmstrong {
+
+ @Test
+ public void testArmstrong() {
+ Armstrong armstrong = new Armstrong();
+ assertThat(armstrong.isArmstrong(371)).isTrue();
+ assertThat(armstrong.isArmstrong(200)).isFalse();
+ }
+}
From 45f3e5b6def330827088751026e18527b838673d Mon Sep 17 00:00:00 2001
From: thanhtri122002 <93241140+thanhtri122002@users.noreply.github.com>
Date: Wed, 8 Jun 2022 22:19:42 +0700
Subject: [PATCH 0041/1577] Add a test for average (#3084)
Co-authored-by: thanhtri122002
Co-authored-by: Andrii Siriak
---
.../java/com/thealgorithms/maths/AverageTest.java | 14 ++++++++++++++
1 file changed, 14 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/AverageTest.java
diff --git a/src/test/java/com/thealgorithms/maths/AverageTest.java b/src/test/java/com/thealgorithms/maths/AverageTest.java
new file mode 100644
index 000000000000..04d27ab4bcd1
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/AverageTest.java
@@ -0,0 +1,14 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+
+public class AverageTest {
+ double [] numbers = {3, 6, 9, 12, 15, 18, 21};
+ @Test
+ public void testAverage() {
+
+ Assertions.assertEquals(12, Average.average(numbers));
+ }
+}
From 8982692ca69ce5edad9d319b68fc6ff2cc46cbdb Mon Sep 17 00:00:00 2001
From: Squirrellllllllllll
<90439584+Squirrellllllllllll@users.noreply.github.com>
Date: Thu, 9 Jun 2022 13:47:31 +0700
Subject: [PATCH 0042/1577] Add tests for factorial (#3107)
---
.../com/thealgorithms/maths/FactorialTest.java | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/FactorialTest.java
diff --git a/src/test/java/com/thealgorithms/maths/FactorialTest.java b/src/test/java/com/thealgorithms/maths/FactorialTest.java
new file mode 100644
index 000000000000..0eee66c371bd
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/FactorialTest.java
@@ -0,0 +1,16 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+
+
+public class FactorialTest {
+
+ @Test
+ public void test() {
+ Factorial fact = new Factorial();
+ assertEquals(120,fact.factorial(5));
+ }
+
+}
\ No newline at end of file
From ba3c0319ed3ef6edfb6df4b6a496c639aa6d19f2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Qu=E1=BB=91c=20Th=C3=A1i=20V=C5=A9?=
Date: Thu, 9 Jun 2022 13:50:16 +0700
Subject: [PATCH 0043/1577] Add tests for sum of digits (#3083)
---
.../thealgorithms/maths/SumOfDigitsTest.java | 25 +++++++++++++++++++
1 file changed, 25 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java
diff --git a/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java
new file mode 100644
index 000000000000..116a87f5e623
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/SumOfDigitsTest.java
@@ -0,0 +1,25 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * @author SirFixalot16
+ * @since 01/06/22
+ */
+public class SumOfDigitsTest {
+ @Test
+ void isSumOf2Digits() {
+ SumOfDigits sum = new SumOfDigits();
+ assertEquals(11, sum.sumOfDigits(56));
+ }
+ void isSumOf3Digits() {
+ SumOfDigits sum = new SumOfDigits();
+ assertEquals(12, sum.sumOfDigits(192));
+ }
+ void isSumOf4Digits() {
+ SumOfDigits sum = new SumOfDigits();
+ assertEquals(25, sum.sumOfDigits(8962));
+ }
+}
From ec1ab53eeacbd9913206bb5ab98c1dd7dfe2ebbe Mon Sep 17 00:00:00 2001
From: Artem Boiarshinov <54187376+Boiarshinov@users.noreply.github.com>
Date: Fri, 10 Jun 2022 20:44:23 +0300
Subject: [PATCH 0044/1577] Reduce memory usage of bloom filter (#3115)
---
.../datastructures/bloomfilter/BloomFilter.java | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
index ed77bb3c64a7..71ad0e42ff0c 100644
--- a/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
+++ b/src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
@@ -1,16 +1,18 @@
package com.thealgorithms.datastructures.bloomfilter;
+import java.util.BitSet;
+
public class BloomFilter {
private int numberOfHashFunctions;
- private int [] bitArray;
+ private BitSet bitArray;
private Hash[] hashFunctions;
public BloomFilter(int numberOfHashFunctions, int n) {
this.numberOfHashFunctions = numberOfHashFunctions;
hashFunctions = new Hash[numberOfHashFunctions];
- bitArray = new int[n];
+ bitArray = new BitSet(n);
insertHash();
}
@@ -22,13 +24,15 @@ private void insertHash() {
public void insert(T key) {
for (Hash hash : hashFunctions){
- bitArray[hash.compute(key) % bitArray.length] = 1;
+ int position = hash.compute(key) % bitArray.size();
+ bitArray.set(position);
}
}
public boolean contains(T key) {
for (Hash hash : hashFunctions){
- if (bitArray[hash.compute(key) % bitArray.length] == 0){
+ int position = hash.compute(key) % bitArray.size();
+ if (!bitArray.get(position)) {
return false;
}
}
From 6c4092a46b9c313b543955d3d2c091889262937d Mon Sep 17 00:00:00 2001
From: Jonathan Taylor
Date: Sat, 11 Jun 2022 13:53:33 -0500
Subject: [PATCH 0045/1577] Add Topological Sorting Algorithm (#3060)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-authored-by: thanhtri122002
Co-authored-by: Andrii Siriak
Co-authored-by: Anh Pham <62592224+anhpham197@users.noreply.github.com>
Co-authored-by: SanOtaku
Co-authored-by: Raghav Taneja <97575679+RaghavTaneja@users.noreply.github.com>
Co-authored-by: Andrii Siriak
Co-authored-by: Hai Nguyen <88832724+ntquanghai@users.noreply.github.com>
Co-authored-by: Utkarsh Yadav
Co-authored-by: Phạm Minh Hiếu <84634830+Ph1eu@users.noreply.github.com>
Co-authored-by: nguyenviettrung-bi11276 <101244039+nguyenviettrung-bi11276@users.noreply.github.com>
Co-authored-by: TaiNguyen2001 <102779475+TaiNguyen2001@users.noreply.github.com>
Co-authored-by: de <88503943+HuyQHoang@users.noreply.github.com>
Co-authored-by: thanhtri122002 <93241140+thanhtri122002@users.noreply.github.com>
Co-authored-by: thanhtri122002
---
.../thealgorithms/sorts/TopologicalSort.java | 160 ++++++++++++++++++
.../sorts/TopologicalSortTest.java | 61 +++++++
2 files changed, 221 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/sorts/TopologicalSort.java
create mode 100644 src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java
diff --git a/src/main/java/com/thealgorithms/sorts/TopologicalSort.java b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
new file mode 100644
index 000000000000..40f4b856c7c8
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/TopologicalSort.java
@@ -0,0 +1,160 @@
+package com.thealgorithms.sorts;
+
+import java.util.*;
+
+/**
+ * The Topological Sorting algorithm linearly orders a DAG or Directed Acyclic Graph into
+ * a linked list. A Directed Graph is proven to be acyclic when a DFS or Depth First Search is
+ * performed, yielding no back-edges.
+ *
+ * https://en.wikipedia.org/wiki/Topological_sorting
+ *
+ * @author Jonathan Taylor (https://github.com/Jtmonument)
+ * Based on Introduction to Algorithms 3rd Edition
+ */
+public class TopologicalSort {
+
+ /*
+ * Enum to represent the colors for the depth first search
+ * */
+ private enum Color {
+ WHITE, GRAY, BLACK
+ }
+
+ /*
+ * Class to represent vertices
+ * */
+ private static class Vertex {
+ /*
+ * Name of vertex
+ * */
+ public final String label;
+
+ /*
+ * Weight of vertex
+ * (more accurately defined as the time that a vertex has begun a visit in DFS)
+ * */
+ public int weight;
+
+ /*
+ * The time that the vertex has finished a visit in DFS
+ * */
+ public int finished;
+
+ /*
+ * π parent of the vertex
+ * */
+ public Vertex predecessor;
+
+ /*
+ * Represents the category of visit in DFS
+ * */
+ public Color color = Color.WHITE;
+
+ /*
+ * The array of names of descendant vertices
+ * */
+ public final ArrayList next = new ArrayList<>();
+
+ public Vertex(String label) {
+ this.label = label;
+ }
+ }
+
+ /*
+ * Graph class uses the adjacency list representation
+ * */
+ static class Graph {
+
+ /*
+ * Adjacency list representation
+ * */
+ private final HashMap adj = new LinkedHashMap<>();
+
+ /*
+ * Function to add an edge to the graph
+ * */
+ public void addEdge(String label, String... next) {
+ adj.put(label, new Vertex(label));
+ if (!next[0].isEmpty())
+ Collections.addAll(adj.get(label).next, next);
+ }
+ }
+
+ static class BackEdgeException extends RuntimeException {
+
+ public BackEdgeException(String backEdge) {
+ super("This graph contains a cycle. No linear ordering is possible. " + backEdge);
+ }
+
+ }
+
+ /*
+ * Time variable in DFS
+ * */
+ private static int time;
+
+ /*
+ * Depth First Search
+ *
+ * DFS(G)
+ * for each vertex u ∈ G.V
+ * u.color = WHITE
+ * u.π = NIL
+ * time = 0
+ * for each vertex u ∈ G.V
+ * if u.color == WHITE
+ * DFS-VISIT(G, u)
+ *
+ * Performed in Θ(V + E) time
+ * */
+ public static LinkedList sort(Graph graph) {
+ LinkedList list = new LinkedList<>();
+ graph.adj.forEach((name, vertex) -> {
+ if (vertex.color == Color.WHITE) {
+ list.addFirst(sort(graph, vertex, list));
+ }
+ });
+ return list;
+ }
+
+ /*
+ * Depth First Search Visit
+ *
+ * DFS-Visit(G, u)
+ * time = time + 1
+ * u.d = time
+ * u.color = GRAY
+ * for each v ∈ G.Adj[u]
+ * if v.color == WHITE
+ * v.π = u
+ * DFS-Visit(G, u)
+ * u.color = BLACK
+ * time = time + 1
+ * u.f = time
+ * */
+ private static String sort(Graph graph, Vertex u, LinkedList list) {
+ time++;
+ u.weight = time;
+ u.color = Color.GRAY;
+ graph.adj.get(u.label).next.forEach(label -> {
+ if (graph.adj.get(label).color == Color.WHITE) {
+ graph.adj.get(label).predecessor = u;
+ list.addFirst(sort(graph, graph.adj.get(label), list));
+ } else if (graph.adj.get(label).color == Color.GRAY) {
+ /*
+ * A back edge exists if an edge (u, v) connects a vertex u to its ancestor vertex v
+ * in a depth first tree. If v.d ≤ u.d < u.f ≤ v.f
+ *
+ * In many cases, we will not know u.f, but v.color denotes the type of edge
+ * */
+ throw new BackEdgeException("Back edge: " + u.label + " -> " + label);
+ }
+ });
+ u.color = Color.BLACK;
+ time++;
+ u.finished = time;
+ return u.label;
+ }
+}
+
diff --git a/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java
new file mode 100644
index 000000000000..6bec2a1bbc01
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java
@@ -0,0 +1,61 @@
+package com.thealgorithms.sorts;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import com.thealgorithms.sorts.TopologicalSort.Graph;
+import com.thealgorithms.sorts.TopologicalSort.BackEdgeException;
+
+import java.util.LinkedList;
+
+class TopologicalSortTest {
+ @Test
+ void successTest() {
+ /*
+ * Professor Bumstead example DAG. Each directed edge means that garment u must be put on
+ * before garment v.
+ * */
+ Graph graph = new Graph();
+ graph.addEdge("shirt", "tie", "belt");
+ graph.addEdge("tie", "jacket");
+ graph.addEdge("belt", "jacket");
+ graph.addEdge("watch", "");
+ graph.addEdge("undershorts", "pants", "shoes");
+ graph.addEdge("shoes", "");
+ graph.addEdge("socks", "shoes");
+ graph.addEdge("jacket","");
+ graph.addEdge("pants", "belt", "shoes");
+ LinkedList expected = new LinkedList<>();
+ expected.add("socks");
+ expected.add("undershorts");
+ expected.add("pants");
+ expected.add("shoes");
+ expected.add("watch");
+ expected.add("shirt");
+ expected.add("belt");
+ expected.add("tie");
+ expected.add("jacket");
+ assertIterableEquals(expected, TopologicalSort.sort(graph));
+ }
+
+ @Test
+ public void failureTest() {
+
+ /*
+ * Graph example from Geeks For Geeks
+ * https://www.geeksforgeeks.org/tree-back-edge-and-cross-edges-in-dfs-of-graph/
+ * */
+ Graph graph = new Graph();
+ graph.addEdge("1", "2", "3", "8");
+ graph.addEdge("2", "4");
+ graph.addEdge("3", "5");
+ graph.addEdge("4", "6");
+ graph.addEdge("5", "4", "7", "8");
+ graph.addEdge("6", "2");
+ graph.addEdge("7", "");
+ graph.addEdge("8", "");
+ Exception exception = assertThrows(BackEdgeException.class, () -> TopologicalSort.sort(graph));
+ String expected = "This graph contains a cycle. No linear ordering is possible. " +
+ "Back edge: 6 -> 2";
+ assertEquals(exception.getMessage(), expected);
+ }
+}
From a33a26a9d13612e55291b9991ff1dbeb043409f7 Mon Sep 17 00:00:00 2001
From: Hai Nguyen <88832724+ntquanghai@users.noreply.github.com>
Date: Tue, 14 Jun 2022 14:50:50 +0700
Subject: [PATCH 0046/1577] Cover CheckAnagrams with tests (#3124)
---
.../strings/CheckAnagramsTest.java | 35 +++++++++++++++++++
1 file changed, 35 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java
diff --git a/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java b/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java
new file mode 100644
index 000000000000..8afe864114fd
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java
@@ -0,0 +1,35 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+
+public class CheckAnagramsTest {
+ @Test
+ public void CheckAnagrams() {
+ String testString1 = "STUDY";
+ String testString2 = "DUSTY";
+ assertTrue(CheckAnagrams.isAnagrams(testString1,testString2));
+ }
+
+ @Test
+ public void CheckFalseAnagrams() {
+ String testString1 = "STUDY";
+ String testString2 = "random";
+ assertFalse(CheckAnagrams.isAnagrams(testString1,testString2));
+ }
+
+ @Test
+ public void CheckSameWordAnagrams() {
+ String testString1 = "STUDY";
+ assertTrue(CheckAnagrams.isAnagrams(testString1,testString1));
+ }
+
+ @Test
+ public void CheckDifferentCasesAnagram() {
+ String testString1 = "STUDY";
+ String testString2 = "dusty";
+ assertTrue(CheckAnagrams.isAnagrams(testString1,testString2));
+ }
+}
From 4ccb9f460fde1fc75dbce590f48cde9814eb22b3 Mon Sep 17 00:00:00 2001
From: Ankush263 <86042508+Ankush263@users.noreply.github.com>
Date: Tue, 14 Jun 2022 19:01:50 +0530
Subject: [PATCH 0047/1577] Fix the folder structure (#3141)
---
.../datastructures/{ => bloomfilter}/BloomFilterTest.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename src/test/java/com/thealgorithms/datastructures/{ => bloomfilter}/BloomFilterTest.java (100%)
diff --git a/src/test/java/com/thealgorithms/datastructures/BloomFilterTest.java b/src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java
similarity index 100%
rename from src/test/java/com/thealgorithms/datastructures/BloomFilterTest.java
rename to src/test/java/com/thealgorithms/datastructures/bloomfilter/BloomFilterTest.java
From 678ec396fc62fbe570604af8d2b2e66c82918b14 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?BI11-061=20Ho=C3=A0ng=20Anh=20=C4=90=E1=BB=A9c?=
<89365021+Anhduc2k2@users.noreply.github.com>
Date: Wed, 15 Jun 2022 23:19:27 +0700
Subject: [PATCH 0048/1577] Add tests for isPerfectSquare (#3131)
---
.../maths/PerfectSquareTest.java | 37 +++++++++++++++++++
1 file changed, 37 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/maths/PerfectSquareTest.java
diff --git a/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java
new file mode 100644
index 000000000000..70f637363984
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/PerfectSquareTest.java
@@ -0,0 +1,37 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+
+
+public class PerfectSquareTest{
+
+ @Test
+ public void TestPerfectSquareifiscorrect(){
+ //Valid Partition
+ int number = 9;
+
+ boolean result = PerfectSquare.isPerfectSquare(number);
+
+ assertTrue(result);
+ }
+
+ @Test
+ public void TestPerfectSquareifisnotcorrect(){
+ //Invalid Partition 1
+ int number = 3;
+
+ boolean result = PerfectSquare.isPerfectSquare(number);
+
+ assertFalse(result);
+ }
+ @Test
+ public void TestPerfectSquareifisNegativeNumber(){
+ //Invalid Partition 2
+ int number = -10;
+
+ boolean result = PerfectSquare.isPerfectSquare(number);
+
+ assertFalse(result);
+ }
+}
From 6472d330920933671155da2a0c2ff1588cb702aa Mon Sep 17 00:00:00 2001
From: Ankush263 <86042508+Ankush263@users.noreply.github.com>
Date: Mon, 20 Jun 2022 23:34:13 +0530
Subject: [PATCH 0049/1577] Add heaps folder (#3150)
Co-authored-by: Yang Libin
---
.../datastructures/{ => heaps}/FibonacciHeapTest.java | 0
1 file changed, 0 insertions(+), 0 deletions(-)
rename src/test/java/com/thealgorithms/datastructures/{ => heaps}/FibonacciHeapTest.java (100%)
diff --git a/src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java
similarity index 100%
rename from src/test/java/com/thealgorithms/datastructures/FibonacciHeapTest.java
rename to src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java
From 22be348c546fe517c12f96575191aa6413952db5 Mon Sep 17 00:00:00 2001
From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com>
Date: Mon, 20 Jun 2022 23:37:41 +0530
Subject: [PATCH 0050/1577] Add algorithm to find Hamiltonian cycle (#3151)
---
.../graphs/HamiltonianCycle.java | 100 ++++++++++++++++++
.../graphs/HamiltonianCycleTest.java | 39 +++++++
2 files changed, 139 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
new file mode 100644
index 000000000000..e0f373bf0610
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -0,0 +1,100 @@
+package com.thealgorithms.datastructures.graphs;
+
+/**
+ * Java program for Hamiltonian Cycle (https://en.wikipedia.org/wiki/Hamiltonian_path)
+ * @author Akshay Dubey (https://github.com/itsAkshayDubey)
+ */
+public class HamiltonianCycle {
+
+ private int V, pathCount;
+ private int[] cycle;
+ private int[][] graph;
+
+ /**
+ * Find hamiltonian cycle for given graph G(V,E)
+ * @param graph Adjacency matrix of a graph G(V, E)
+ * for which hamiltonian path is to be found
+ * @return Array containing hamiltonian cycle
+ * else returns 1D array with value -1.
+ */
+ public int[] findHamiltonianCycle(int[][] graph){
+ this.V = graph.length;
+ this.cycle = new int[this.V+1];
+
+ //Initialize path array with -1 value
+ for(int i=0 ; i
Date: Tue, 21 Jun 2022 10:41:22 +0300
Subject: [PATCH 0051/1577] Add Skip List (#3154)
---
.../datastructures/lists/SkipList.java | 324 ++++++++++++++++++
.../datastructures/lists/SkipListTest.java | 85 +++++
2 files changed, 409 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
new file mode 100644
index 000000000000..5cd14f9dd00c
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
@@ -0,0 +1,324 @@
+package com.thealgorithms.datastructures.lists;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * Skip list is a data structure that allows {@code O(log n)} search complexity
+ * as well as {@code O(log n)} insertion complexity within an ordered sequence
+ * of {@code n} elements. Thus it can get the best features of a sorted array
+ * (for searching) while maintaining a linked list-like structure that allows
+ * insertion, which is not possible with a static array.
+ *
+ * A skip list is built in layers. The bottom layer is an ordinary ordered
+ * linked list. Each higher layer acts as an "express lane" for the lists
+ * below.
+ *
+ *
+ * @param type of elements
+ * @see Wiki. Skip list
+ */
+public class SkipList> {
+
+ /**
+ * Node before first node.
+ */
+ private final Node head;
+
+ /**
+ * Maximum layers count.
+ * Calculated by {@link #heightStrategy}.
+ */
+ private final int height;
+
+ /**
+ * Function for determining height of new nodes.
+ * @see HeightStrategy
+ */
+ private final HeightStrategy heightStrategy;
+
+ /**
+ * Current count of elements in list.
+ */
+ private int size;
+
+ private static final int DEFAULT_CAPACITY = 100;
+
+ public SkipList() {
+ this(DEFAULT_CAPACITY, new BernoulliHeightStrategy());
+ }
+
+ public SkipList(int expectedCapacity, HeightStrategy heightStrategy) {
+ this.heightStrategy = heightStrategy;
+ this.height = heightStrategy.height(expectedCapacity);
+ this.head = new Node<>(null, this.height);
+ this.size = 0;
+ }
+
+ public void add(E e) {
+ Objects.requireNonNull(e);
+ Node current = head;
+ int layer = height;
+ Node[] toFix = new Node[height + 1];
+
+ while (layer >= 0) {
+ Node next = current.next(layer);
+ if (next == null || next.getValue().compareTo(e) > 0) {
+ toFix[layer] = current;
+ layer--;
+ } else {
+ current = next;
+ }
+ }
+ int nodeHeight = heightStrategy.nodeHeight(height);
+ Node node = new Node<>(e, nodeHeight);
+ for (int i = 0; i <= nodeHeight; i++) {
+ if (toFix[i].next(i) != null) {
+ node.setNext(i, toFix[i].next(i));
+ toFix[i].next(i).setPrevious(i, node);
+ }
+
+ toFix[i].setNext(i, node);
+ node.setPrevious(i, toFix[i]);
+ }
+ size++;
+ }
+
+ public E get(int index) {
+ int counter = -1; // head index
+ Node current = head;
+ while (counter != index) {
+ current = current.next(0);
+ counter++;
+ }
+ return current.value;
+ }
+
+ public void remove(E e) {
+ Objects.requireNonNull(e);
+ Node current = head;
+ int layer = height;
+
+ while (layer >= 0) {
+ Node next = current.next(layer);
+ if (e.equals(current.getValue())) {
+ break;
+ } else if (next == null || next.getValue().compareTo(e) > 0) {
+ layer--;
+ } else {
+ current = next;
+ }
+ }
+ for (int i = 0; i <= layer; i++) {
+ current.previous(i).setNext(i, current.next(i));
+ current.next(i).setPrevious(i, current.previous(i));
+ }
+ size--;
+ }
+
+ /**
+ * A search for a target element begins at the head element in the top
+ * list, and proceeds horizontally until the current element is greater
+ * than or equal to the target. If the current element is equal to the
+ * target, it has been found. If the current element is greater than the
+ * target, or the search reaches the end of the linked list, the procedure
+ * is repeated after returning to the previous element and dropping down
+ * vertically to the next lower list.
+ *
+ * @param e element whose presence in this list is to be tested
+ * @return true if this list contains the specified element
+ */
+ public boolean contains(E e) {
+ Objects.requireNonNull(e);
+ Node current = head;
+ int layer = height;
+
+ while (layer >= 0) {
+ Node next = current.next(layer);
+ if (e.equals(current.getValue())) {
+ return true;
+ } else if (next == null || next.getValue().compareTo(e) > 0) {
+ layer--;
+ } else {
+ current = next;
+ }
+ }
+ return false;
+ }
+
+ public int size() {
+ return size;
+ }
+
+ /**
+ * Print height distribution of the nodes in a manner:
+ *