From b6563cf37ae7db33e3f3c8ad513acd905353c147 Mon Sep 17 00:00:00 2001
From: Kumaraswamy B G <71964026+XomaDev@users.noreply.github.com>
Date: Tue, 7 Mar 2023 13:43:46 +0530
Subject: [PATCH 0001/1457] Add Buffered Reader (#3910)
---
.../com/thealgorithms/io/BufferedReader.java | 193 ++++++++++++++++++
.../thealgorithms/io/BufferedReaderTest.java | 133 ++++++++++++
2 files changed, 326 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/io/BufferedReader.java
create mode 100644 src/test/java/com/thealgorithms/io/BufferedReaderTest.java
diff --git a/src/main/java/com/thealgorithms/io/BufferedReader.java b/src/main/java/com/thealgorithms/io/BufferedReader.java
new file mode 100644
index 000000000000..1012ce79690f
--- /dev/null
+++ b/src/main/java/com/thealgorithms/io/BufferedReader.java
@@ -0,0 +1,193 @@
+package com.thealgorithms.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Mimics the actions of the Original buffered reader
+ * implements other actions, such as peek(n) to lookahead,
+ * block() to read a chunk of size {BUFFER SIZE}
+ *
+ * Author: Kumaraswamy B.G (Xoma Dev)
+ */
+public class BufferedReader {
+
+ private static final int DEFAULT_BUFFER_SIZE = 5;
+
+ /**
+ * Maximum number of bytes the buffer can hold.
+ * Value is changed when encountered Eof to not
+ * cause overflow read of 0 bytes
+ */
+
+ private int bufferSize;
+ private final byte[] buffer;
+
+ /**
+ * posRead -> indicates the next byte to read
+ */
+ private int posRead = 0, bufferPos = 0;
+
+ private boolean foundEof = false;
+
+ private InputStream input;
+
+ public BufferedReader(byte[] input) throws IOException {
+ this(new ByteArrayInputStream(input));
+ }
+
+ public BufferedReader(InputStream input) throws IOException {
+ this(input, DEFAULT_BUFFER_SIZE);
+ }
+
+ public BufferedReader(InputStream input, int bufferSize) throws IOException {
+ this.input = input;
+ if (input.available() == -1)
+ throw new IOException("Empty or already closed stream provided");
+
+ this.bufferSize = bufferSize;
+ buffer = new byte[bufferSize];
+ }
+
+ /**
+ * Reads a single byte from the stream
+ */
+ public int read() throws IOException {
+ if (needsRefill()) {
+ if (foundEof)
+ return -1;
+ // the buffer is empty, or the buffer has
+ // been completely read and needs to be refilled
+ refill();
+ }
+ return buffer[posRead++] & 0xff; // read and un-sign it
+ }
+
+ /**
+ * Number of bytes not yet been read
+ */
+
+ public int available() throws IOException {
+ int available = input.available();
+ if (needsRefill())
+ // since the block is already empty,
+ // we have no responsibility yet
+ return available;
+ return bufferPos - posRead + available;
+ }
+
+ /**
+ * Returns the next character
+ */
+
+ public int peek() throws IOException {
+ return peek(1);
+ }
+
+ /**
+ * Peeks and returns a value located at next {n}
+ */
+
+ public int peek(int n) throws IOException {
+ int available = available();
+ if (n >= available)
+ throw new IOException("Out of range, available %d, but trying with %d"
+ .formatted(available, n));
+ pushRefreshData();
+
+ if (n >= bufferSize)
+ throw new IllegalAccessError("Cannot peek %s, maximum upto %s (Buffer Limit)"
+ .formatted(n, bufferSize));
+ return buffer[n];
+ }
+
+ /**
+ * Removes the already read bytes from the buffer
+ * in-order to make space for new bytes to be filled up.
+ *
+ * This may also do the job to read first time data (whole buffer is empty)
+ */
+
+ private void pushRefreshData() throws IOException {
+ for (int i = posRead, j = 0; i < bufferSize; i++, j++)
+ buffer[j] = buffer[i];
+
+ bufferPos -= posRead;
+ posRead = 0;
+
+ // fill out the spaces that we've
+ // emptied
+ justRefill();
+ }
+
+ /**
+ * Reads one complete block of size {bufferSize}
+ * if found eof, the total length of array will
+ * be that of what's available
+ *
+ * @return a completed block
+ */
+ public byte[] readBlock() throws IOException {
+ pushRefreshData();
+
+ byte[] cloned = new byte[bufferSize];
+ // arraycopy() function is better than clone()
+ if (bufferPos >= 0)
+ System.arraycopy(buffer,
+ 0,
+ cloned,
+ 0,
+ // important to note that, bufferSize does not stay constant
+ // once the class is defined. See justRefill() function
+ bufferSize);
+ // we assume that already a chunk
+ // has been read
+ refill();
+ return cloned;
+ }
+
+ private boolean needsRefill() {
+ return bufferPos == 0 || posRead == bufferSize;
+ }
+
+ private void refill() throws IOException {
+ posRead = 0;
+ bufferPos = 0;
+ justRefill();
+ }
+
+ private void justRefill() throws IOException {
+ assertStreamOpen();
+
+ // try to fill in the maximum we can until
+ // we reach EOF
+ while (bufferPos < bufferSize) {
+ int read = input.read();
+ if (read == -1) {
+ // reached end-of-file, no more data left
+ // to be read
+ foundEof = true;
+ // rewrite the BUFFER_SIZE, to know that we've reached
+ // EOF when requested refill
+ bufferSize = bufferPos;
+ }
+ buffer[bufferPos++] = (byte) read;
+ }
+ }
+
+ private void assertStreamOpen() {
+ if (input == null)
+ throw new IllegalStateException("Input Stream already closed!");
+ }
+
+ public void close() throws IOException {
+ if (input != null) {
+ try {
+ input.close();
+ } finally {
+ input = null;
+ }
+ }
+ }
+}
diff --git a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
new file mode 100644
index 000000000000..a183881743f8
--- /dev/null
+++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
@@ -0,0 +1,133 @@
+package com.thealgorithms.io;
+
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.*;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class BufferedReaderTest {
+ @Test
+ public void testPeeks() throws IOException {
+ String text = "Hello!\nWorld!";
+ int len = text.length();
+ byte[] bytes = text.getBytes();
+
+ ByteArrayInputStream input = new ByteArrayInputStream(bytes);
+ BufferedReader reader = new BufferedReader(input);
+
+ // read the first letter
+ assertEquals(reader.read(), 'H');
+ len--;
+ assertEquals(reader.available(), len);
+
+ // position: H[e]llo!\nWorld!
+ // reader.read() will be == 'e'
+ assertEquals(reader.peek(1), 'l');
+ assertEquals(reader.peek(2), 'l'); // second l
+ assertEquals(reader.peek(3), 'o');
+ }
+
+ @Test
+ public void testMixes() throws IOException {
+ String text = "Hello!\nWorld!";
+ int len = text.length();
+ byte[] bytes = text.getBytes();
+
+ ByteArrayInputStream input = new ByteArrayInputStream(bytes);
+ BufferedReader reader = new BufferedReader(input);
+
+ // read the first letter
+ assertEquals(reader.read(), 'H'); // first letter
+ len--;
+
+ assertEquals(reader.peek(1), 'l'); // third later (second letter after 'H')
+ assertEquals(reader.read(), 'e'); // second letter
+ len--;
+ assertEquals(reader.available(), len);
+
+ // position: H[e]llo!\nWorld!
+ assertEquals(reader.peek(2), 'o'); // second l
+ assertEquals(reader.peek(3), '!');
+ assertEquals(reader.peek(4), '\n');
+
+ assertEquals(reader.read(), 'l'); // third letter
+ assertEquals(reader.peek(1), 'o'); // fourth letter
+
+ for (int i = 0; i < 6; i++)
+ reader.read();
+ try {
+ System.out.println((char) reader.peek(4));
+ } catch (Exception ignored) {
+ System.out.println("[cached intentional error]");
+ // intentional, for testing purpose
+ }
+ }
+
+ @Test
+ public void testBlockPractical() throws IOException {
+ String text = "!Hello\nWorld!";
+ byte[] bytes = text.getBytes();
+ int len = bytes.length;
+
+ ByteArrayInputStream input = new ByteArrayInputStream(bytes);
+ BufferedReader reader = new BufferedReader(input);
+
+
+ assertEquals(reader.peek(), 'H');
+ assertEquals(reader.read(), '!'); // read the first letter
+ len--;
+
+ // this only reads the next 5 bytes (Hello) because
+ // the default buffer size = 5
+ assertEquals(new String(reader.readBlock()), "Hello");
+ len -= 5;
+ assertEquals(reader.available(), len);
+
+ // maybe kind of a practical demonstration / use case
+ if (reader.read() == '\n') {
+ assertEquals(reader.read(), 'W');
+ assertEquals(reader.read(), 'o');
+
+ // the rest of the blocks
+ assertEquals(new String(reader.readBlock()), "rld!");
+ } else {
+ // should not reach
+ throw new IOException("Something not right");
+ }
+ }
+
+ @Test
+ public void randomTest() throws IOException {
+ Random random = new Random();
+
+ int len = random.nextInt(9999);
+ int bound = 256;
+
+ ByteArrayOutputStream stream = new ByteArrayOutputStream(len);
+ while (len-- > 0)
+ stream.write(random.nextInt(bound));
+
+ byte[] bytes = stream.toByteArray();
+ ByteArrayInputStream comparer = new ByteArrayInputStream(bytes);
+
+ int blockSize = random.nextInt(7) + 5;
+ BufferedReader reader = new BufferedReader(
+ new ByteArrayInputStream(bytes), blockSize);
+
+ for (int i = 0; i < 50; i++) {
+ if ((i & 1) == 0) {
+ assertEquals(comparer.read(), reader.read());
+ continue;
+ }
+ byte[] block = new byte[blockSize];
+ comparer.read(block);
+ byte[] read = reader.readBlock();
+
+ assertArrayEquals(block, read);
+ }
+ }
+}
\ No newline at end of file
From a7e76c57a075a677dd024be6715bd15de3785074 Mon Sep 17 00:00:00 2001
From: Enrique Clerici <115318468+TheClerici@users.noreply.github.com>
Date: Fri, 10 Mar 2023 15:29:49 -0600
Subject: [PATCH 0002/1457] feat: Backtracking algorithms (All combinations)
#3912 (#3917)
* ArrayCombination function which uses Combination.java by creating an array of 1 to n
* modified tests
---
.../backtracking/ArrayCombination.java | 29 +++++++++++
.../backtracking/ArrayCombinationTest.java | 50 +++++++++++++++++++
2 files changed, 79 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
create mode 100644 src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java
diff --git a/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
new file mode 100644
index 000000000000..4238846786e4
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
@@ -0,0 +1,29 @@
+package com.thealgorithms.backtracking;
+
+import java.util.*;
+
+/**
+ * Finds all permutations of 1...n of length k
+ * @author TheClerici (https://github.com/TheClerici)
+ */
+public class ArrayCombination {
+ private static int length;
+
+ /**
+ * Find all combinations of 1..n by creating an array and using backtracking in Combination.java
+ * @param n max value of the array.
+ * @param k length of combination
+ * @return a list of all combinations of length k. If k == 0, return null.
+ */
+ public static List> combination(int n, int k) {
+ if (n <= 0) {
+ return null;
+ }
+ length = k;
+ Integer[] arr = new Integer[n];
+ for (int i = 1; i <= n; i++) {
+ arr[i-1] = i;
+ }
+ return Combination.combination(arr, length);
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java b/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java
new file mode 100644
index 000000000000..02527257ccc6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java
@@ -0,0 +1,50 @@
+package com.thealgorithms.backtracking;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+import java.util.TreeSet;
+import org.junit.jupiter.api.Test;
+
+public class ArrayCombinationTest {
+
+ @Test
+ void testNBeingZeroOrLess() {
+ List> zeroResult = ArrayCombination.combination(0, 1);
+ List> negativeResult = ArrayCombination.combination(-1, 1);
+ assertNull(zeroResult);
+ assertNull(negativeResult);
+ }
+
+ @Test
+ void testNoLengthElement() {
+ List> result = ArrayCombination.combination(2, 0);
+ assertNull(result);
+ }
+
+ @Test
+ void testLengthOne() {
+ List> result = ArrayCombination.combination(2, 1);
+ assert result != null;
+ assertEquals(1, result.get(0).iterator().next());
+ assertEquals(2, result.get(1).iterator().next());
+ }
+
+ @Test
+ void testLengthTwo() {
+ List> result = ArrayCombination.combination(2, 2);
+ assert result != null;
+ Integer[] arr = result.get(0).toArray(new Integer[2]);
+ assertEquals(1, arr[0]);
+ assertEquals(2, arr[1]);
+ }
+
+ @Test
+ void testLengthFive() {
+ List> result = ArrayCombination.combination(10, 5);
+ assert result != null;
+ Integer[] arr = result.get(0).toArray(new Integer[5]);
+ assertEquals(1, arr[0]);
+ assertEquals(5, arr[4]);
+ }
+}
From 2418604f7aa448edfdac18a258841ae3afcb462c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tr=E1=BA=A7n=20Quang=20D=E1=BB=B1?=
Date: Sun, 12 Mar 2023 18:49:17 +0700
Subject: [PATCH 0003/1457] Add tests for SinglyLinkedList (#3913)
---
.../lists/SinglyLinkedList.java | 18 ++++
.../lists/SinglyLinkedListTest.java | 102 ++++++++++++++++++
2 files changed, 120 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index acb17923c1ea..03ce735f2f5e 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -54,6 +54,24 @@ public boolean detectLoop() {
return false;
}
+ /**
+ * Return the node in the middle of the list
+ * If the length of the list is even then return item number length/2
+ * @return middle node of the list
+ */
+ public Node middle() {
+ if (head == null) {
+ return null;
+ }
+ Node firstCounter = head;
+ Node secondCounter = firstCounter.next;
+ while (secondCounter != null && secondCounter.next != null) {
+ firstCounter = firstCounter.next;
+ secondCounter = secondCounter.next.next;
+ }
+ return firstCounter;
+ }
+
/**
* Swaps nodes of two given values a and b.
*
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
new file mode 100644
index 000000000000..b02fb433ad4a
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
@@ -0,0 +1,102 @@
+package com.thealgorithms.datastructures.lists;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class SinglyLinkedListTest {
+
+ /**
+ * Initialize a list with natural order values with pre-defined length
+ * @param length
+ * @return linked list with pre-defined number of nodes
+ */
+ private SinglyLinkedList createSampleList(int length) {
+ List nodeList = new ArrayList<>();
+ for (int i = 1; i <= length; i++) {
+ Node node = new Node(i);
+ nodeList.add(node);
+ }
+
+ for (int i = 0; i < length - 1; i++) {
+ nodeList.get(i).next = nodeList.get(i+1);
+ }
+
+ return new SinglyLinkedList(nodeList.get(0), length);
+ }
+
+ @Test
+ void detectLoop() {
+ //List has cycle
+ Node firstNode = new Node(1);
+ Node secondNode = new Node(2);
+ Node thirdNode = new Node(3);
+ Node fourthNode = new Node(4);
+
+ firstNode.next = secondNode;
+ secondNode.next = thirdNode;
+ thirdNode.next = fourthNode;
+ fourthNode.next = firstNode;
+
+ SinglyLinkedList listHasLoop = new SinglyLinkedList(firstNode, 4);
+ assertTrue(listHasLoop.detectLoop());
+
+ SinglyLinkedList listHasNoLoop = createSampleList(5);
+ assertFalse(listHasNoLoop.detectLoop());
+ }
+
+ @Test
+ void middle() {
+ int oddNumberOfNode = 7;
+ SinglyLinkedList list = createSampleList(oddNumberOfNode);
+ assertEquals(oddNumberOfNode/2 + 1, list.middle().value);
+ int evenNumberOfNode = 8;
+ list = createSampleList(evenNumberOfNode);
+ assertEquals(evenNumberOfNode/2, list.middle().value);
+
+ //return null if empty
+ list = new SinglyLinkedList();
+ assertNull(list.middle());
+
+ //return head if there is only one node
+ list = createSampleList(1);
+ assertEquals(list.getHead(), list.middle());
+ }
+
+ @Test
+ void swap() {
+ SinglyLinkedList list = createSampleList(5);
+ assertEquals(1, list.getHead().value);
+ assertEquals(5, list.getNth(4));
+ list.swapNodes(1,5);
+ assertEquals(5, list.getHead().value);
+ assertEquals(1, list.getNth(4));
+ }
+
+ @Test
+ void clear() {
+ SinglyLinkedList list = createSampleList(5);
+ assertEquals(5, list.size());
+ list.clear();
+ assertEquals(0, list.size());
+ assertTrue(list.isEmpty());
+ }
+
+ @Test
+ void search() {
+ SinglyLinkedList list = createSampleList(10);
+ assertTrue(list.search(5));
+ assertFalse(list.search(20));
+ }
+
+ @Test
+ void deleteNth() {
+ SinglyLinkedList list = createSampleList(10);
+ assertTrue(list.search(7));
+ list.deleteNth(6); //Index 6 has value 7
+ assertFalse(list.search(7));
+ }
+}
\ No newline at end of file
From 3a56c963b3f1ad009db530388babf2497084f093 Mon Sep 17 00:00:00 2001
From: Christian Clauss
Date: Sat, 18 Mar 2023 09:03:32 +0100
Subject: [PATCH 0004/1457] Change Python version for directory workflow from
3.10 to 3.x to use newer and faster language versions (#3921)
---
.github/workflows/update_directory.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/workflows/update_directory.yml b/.github/workflows/update_directory.yml
index 4be3c2841871..7eec515580a2 100644
--- a/.github/workflows/update_directory.yml
+++ b/.github/workflows/update_directory.yml
@@ -20,7 +20,7 @@ jobs:
- uses: actions/checkout@master
- uses: actions/setup-python@v4
with:
- python-version: '3.10'
+ python-version: '3.x'
- name: Update Directory
shell: python
run: |
From 0b6fa5c3b8a5d1364e287888c280306d98120bdd Mon Sep 17 00:00:00 2001
From: Andrii Siriak
Date: Sat, 18 Mar 2023 10:09:06 +0200
Subject: [PATCH 0005/1457] Remove old Gitter chat
---
README.md | 3 ---
1 file changed, 3 deletions(-)
diff --git a/README.md b/README.md
index 59930fded1d3..16237a32f974 100644
--- a/README.md
+++ b/README.md
@@ -15,8 +15,5 @@ These implementations are intended for learning purposes. As such, they may be l
## Contribution Guidelines
Please read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute to this project.
-## Community Channel
-We're on [Gitter](https://gitter.im/TheAlgorithms)! Come join us.
-
## Algorithms
Our [directory](DIRECTORY.md) has the full list of applications.
From 86c93146d94e188b62696b4b429e68aa4c14416d Mon Sep 17 00:00:00 2001
From: SwargaRajDutta <72154312+Swarga-codes@users.noreply.github.com>
Date: Sun, 19 Mar 2023 13:21:48 +0530
Subject: [PATCH 0006/1457] Add Run-Length Encoding (fixes #3911) (#3916)
---
.../strings/StringCompression.java | 60 +++++++++++++++++++
.../strings/StringCompressionTest.java | 13 ++++
2 files changed, 73 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/strings/StringCompression.java
create mode 100644 src/test/java/com/thealgorithms/strings/StringCompressionTest.java
diff --git a/src/main/java/com/thealgorithms/strings/StringCompression.java b/src/main/java/com/thealgorithms/strings/StringCompression.java
new file mode 100644
index 000000000000..0d209f885f94
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/StringCompression.java
@@ -0,0 +1,60 @@
+package com.thealgorithms.strings;
+/* References : https://en.wikipedia.org/wiki/Run-length_encoding
+ * String compression algorithm deals with encoding the string, that is, shortening the size of the string
+ * @author Swarga-codes (https://github.com/Swarga-codes)
+*/
+public class StringCompression {
+ /**
+ * Returns the compressed or encoded string
+ *
+ * @param ch character array that contains the group of characters to be encoded
+ * @return the compressed character array as string
+ */
+ public static String compress(String input) {
+ // Keeping the count as 1 since every element present will have atleast a count
+ // of 1
+ int count = 1;
+ String compressedString = "";
+ // Base condition to check whether the array is of size 1, if it is then we
+ // return the array
+ if (input.length() == 1) {
+ return "" + input.charAt(0);
+ }
+ // If the array has a length greater than 1 we move into this loop
+ for (int i = 0; i < input.length() - 1; i++) {
+ // here we check for similarity of the adjacent elements and change the count
+ // accordingly
+ if (input.charAt(i) == input.charAt(i + 1)) {
+ count = count + 1;
+ }
+ if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) {
+ compressedString = appendCount(compressedString, count, input.charAt(i));
+ break;
+ } else if (input.charAt(i) != input.charAt(i+1)) {
+ if ((i + 1) == input.length() - 1) {
+ compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i+1);
+ break;
+ } else {
+ compressedString = appendCount(compressedString, count, input.charAt(i));
+ count = 1;
+ }
+ }
+ }
+ return compressedString;
+ }
+ /**
+ * @param res the resulting string
+ * @param count current count
+ * @param ch the character at a particular index
+ * @return the res string appended with the count
+ */
+ public static String appendCount(String res, int count, char ch) {
+ if (count > 1) {
+ res += ch + "" + count;
+ count = 1;
+ } else {
+ res += ch + "";
+ }
+ return res;
+ }
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/strings/StringCompressionTest.java b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java
new file mode 100644
index 000000000000..d02e83ce7e3b
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/StringCompressionTest.java
@@ -0,0 +1,13 @@
+package com.thealgorithms.strings;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+public class StringCompressionTest {
+ @ParameterizedTest
+ @CsvSource({"a,a","aabbb,a2b3","abbbc,ab3c","aabccd,a2bc2d"})
+ void stringCompressionTest(String input,String expectedOutput){
+ String output=StringCompression.compress(input);
+ assertEquals(expectedOutput, output);
+ }
+}
From 3b2ca8176525eb990c17616ad59a798b096aa0f2 Mon Sep 17 00:00:00 2001
From: Isak Einberg <45336755+einbergisak@users.noreply.github.com>
Date: Fri, 24 Mar 2023 20:22:56 +0100
Subject: [PATCH 0007/1457] Fix spelling in Volume (#3893)
---
.../java/com/thealgorithms/maths/Volume.java | 50 +++++++++----------
1 file changed, 25 insertions(+), 25 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/Volume.java b/src/main/java/com/thealgorithms/maths/Volume.java
index caa8f8bece57..edc3575dfda6 100644
--- a/src/main/java/com/thealgorithms/maths/Volume.java
+++ b/src/main/java/com/thealgorithms/maths/Volume.java
@@ -1,24 +1,24 @@
package com.thealgorithms.maths;
-/* Find volume of various shapes.*/
+/* Calculate the volume of various shapes.*/
public class Volume {
/**
* Calculate the volume of a cube.
*
- * @param sideLength side length of cube
- * @return volume of given cube
+ * @param sideLength length of the given cube's sides
+ * @return volume of the given cube
*/
- public static double volumeCube(double sidelength) {
- return sidelength * sidelength * sidelength;
+ public static double volumeCube(double sideLength) {
+ return sideLength * sideLength * sideLength;
}
/**
* Calculate the volume of a cuboid.
*
- * @param width of cuboid
- * @param height of cuboid
- * @param length of cuboid
+ * @param width width of given cuboid
+ * @param height height of given cuboid
+ * @param length length of given cuboid
* @return volume of given cuboid
*/
public static double volumeCuboid(double width, double height, double length) {
@@ -28,7 +28,7 @@ public static double volumeCuboid(double width, double height, double length) {
/**
* Calculate the volume of a sphere.
*
- * @param radius radius of sphere
+ * @param radius radius of given sphere
* @return volume of given sphere
*/
public static double volumeSphere(double radius) {
@@ -38,8 +38,8 @@ public static double volumeSphere(double radius) {
/**
* Calculate volume of a cylinder
*
- * @param radius radius of the floor
- * @param height height of the cylinder.
+ * @param radius radius of the given cylinder's floor
+ * @param height height of the given cylinder
* @return volume of given cylinder
*/
public static double volumeCylinder(double radius, double height) {
@@ -49,7 +49,7 @@ public static double volumeCylinder(double radius, double height) {
/**
* Calculate the volume of a hemisphere.
*
- * @param radius radius of hemisphere
+ * @param radius radius of given hemisphere
* @return volume of given hemisphere
*/
public static double volumeHemisphere(double radius) {
@@ -59,9 +59,9 @@ public static double volumeHemisphere(double radius) {
/**
* Calculate the volume of a cone.
*
- * @param radius radius of cone.
- * @param height of cone.
- * @return volume of given cone.
+ * @param radius radius of given cone
+ * @param height of given cone
+ * @return volume of given cone
*/
public static double volumeCone(double radius, double height) {
return (Math.PI * radius * radius * height) / 3;
@@ -70,22 +70,22 @@ public static double volumeCone(double radius, double height) {
/**
* Calculate the volume of a prism.
*
- * @param area of the base.
- * @param height of prism.
- * @return volume of given prism.
+ * @param baseArea area of the given prism's base
+ * @param height of given prism
+ * @return volume of given prism
*/
- public static double volumePrism(double basearea, double height) {
- return basearea * height;
+ public static double volumePrism(double baseArea, double height) {
+ return baseArea * height;
}
/**
* Calculate the volume of a pyramid.
*
- * @param area of the base.
- * @param height of pyramid.
- * @return volume of given pyramid.
+ * @param baseArea of the given pyramid's base
+ * @param height of given pyramid
+ * @return volume of given pyramid
*/
- public static double volumePyramid(double basearea, double height) {
- return (basearea * height) / 3;
+ public static double volumePyramid(double baseArea, double height) {
+ return (baseArea * height) / 3;
}
}
From acfa2890a4f1fba2f56e7aca0e863d0ecb6e9f84 Mon Sep 17 00:00:00 2001
From: JarZombie
Date: Sun, 2 Apr 2023 02:43:47 +0800
Subject: [PATCH 0008/1457] Fix DIRECTORY.md formatting (closes #3922) (#4124)
---
.github/workflows/update_directory.yml | 31 +++++++++++++++++---------
1 file changed, 21 insertions(+), 10 deletions(-)
diff --git a/.github/workflows/update_directory.yml b/.github/workflows/update_directory.yml
index 7eec515580a2..0530a0c267a9 100644
--- a/.github/workflows/update_directory.yml
+++ b/.github/workflows/update_directory.yml
@@ -1,18 +1,25 @@
-# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push
+# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push or pull_request
name: Update Directory
+permissions:
+ contents: write
on:
push:
paths:
- 'src/**'
- - '**.yml'
- - '**.xml'
- - '**.Dockerfile'
pull_request:
paths:
- 'src/**'
- - '**.yml'
- - '**.xml'
- - '**.Dockerfile'
+ workflow_dispatch:
+ inputs:
+ logLevel:
+ description: 'Log level'
+ required: true
+ default: 'info'
+ type: choice
+ options:
+ - info
+ - warning
+ - debug
jobs:
update_directory_md:
runs-on: ubuntu-latest
@@ -46,8 +53,12 @@ jobs:
def print_path(old_path: str, new_path: str) -> str:
global g_output
old_parts = old_path.split(os.sep)
- for i, new_part in enumerate(new_path.split(os.sep)):
- if i + 1 > len(old_parts) or old_parts[i] != new_part:
+ mid_diff = False
+ new_parts = new_path.split(os.sep)
+ for i, new_part in enumerate(new_parts):
+ if i + 1 > len(old_parts) or old_parts[i] != new_part or mid_diff:
+ if i + 1 < len(new_parts):
+ mid_diff = True
if new_part:
g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ')}")
return new_path
@@ -56,7 +67,7 @@ jobs:
def build_directory_md(top_dir: str = ".") -> str:
global g_output
old_path = ""
- for filepath in sorted(good_filepaths(), key=str.lower):
+ for filepath in sorted(good_filepaths(top_dir), key=str.lower):
filepath, filename = os.path.split(filepath)
if filepath != old_path:
old_path = print_path(old_path, filepath)
From 805f09850c325583f08343a4bf75d41afaea91ad Mon Sep 17 00:00:00 2001
From: duyuanch <680888@gmail.com>
Date: Sun, 2 Apr 2023 23:09:51 +0800
Subject: [PATCH 0009/1457] Update SortUtils (#4139)
---
.../com/thealgorithms/sorts/CombSort.java | 3 +-
.../com/thealgorithms/sorts/SortUtils.java | 129 +++++++++---------
2 files changed, 65 insertions(+), 67 deletions(-)
diff --git a/src/main/java/com/thealgorithms/sorts/CombSort.java b/src/main/java/com/thealgorithms/sorts/CombSort.java
index 7ddce43df9f5..78951fb3c916 100644
--- a/src/main/java/com/thealgorithms/sorts/CombSort.java
+++ b/src/main/java/com/thealgorithms/sorts/CombSort.java
@@ -54,7 +54,8 @@ public > T[] sort(T[] arr) {
for (int i = 0; i < size - gap; i++) {
if (less(arr[i + gap], arr[i])) {
// Swap arr[i] and arr[i+gap]
- swapped = swap(arr, i, i + gap);
+ swap(arr, i, i + gap);
+ swapped = true;
}
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/SortUtils.java b/src/main/java/com/thealgorithms/sorts/SortUtils.java
index f9f99055a49e..5f3563fbeb57 100644
--- a/src/main/java/com/thealgorithms/sorts/SortUtils.java
+++ b/src/main/java/com/thealgorithms/sorts/SortUtils.java
@@ -2,121 +2,118 @@
import java.util.Arrays;
import java.util.List;
+import java.util.stream.Collectors;
-/**
- * The class contains util methods
- *
- * @author Podshivalov Nikita (https://github.com/nikitap492)
- */
final class SortUtils {
/**
- * Helper method for swapping places in array
+ * Swaps two elements at the given positions in an array.
*
- * @param array The array which elements we want to swap
- * @param idx index of the first element
- * @param idy index of the second element
+ * @param array the array in which to swap elements
+ * @param i the index of the first element to swap
+ * @param j the index of the second element to swap
+ * @param the type of elements in the array
*/
- static boolean swap(T[] array, int idx, int idy) {
- T swap = array[idx];
- array[idx] = array[idy];
- array[idy] = swap;
- return true;
+ public static void swap(T[] array, int i, int j) {
+ T temp = array[i];
+ array[i] = array[j];
+ array[j] = temp;
}
/**
- * This method checks if first element is less than the other element
+ * Compares two elements to see if the first is less than the second.
*
- * @param v first element
- * @param w second element
- * @return true if the first element is less than the second element
+ * @param firstElement the first element to compare
+ * @param secondElement the second element to compare
+ * @return true if the first element is less than the second, false otherwise
*/
- static > boolean less(T v, T w) {
- return v.compareTo(w) < 0;
+ public static > boolean less(T firstElement, T secondElement) {
+ return firstElement.compareTo(secondElement) < 0;
}
/**
- * This method checks if first element is greater than the other element
+ * Compares two elements to see if the first is greater than the second.
*
- * @param v first element
- * @param w second element
- * @return true if the first element is greater than the second element
+ * @param firstElement the first element to compare
+ * @param secondElement the second element to compare
+ * @return true if the first element is greater than the second, false otherwise
*/
- static > boolean greater(T v, T w) {
- return v.compareTo(w) > 0;
+ public static > boolean greater(T firstElement, T secondElement) {
+ return firstElement.compareTo(secondElement) > 0;
}
/**
- * This method checks if first element is greater than or equal the other
- * element
+ * Compares two elements to see if the first is greater than or equal to the second.
*
- * @param v first element
- * @param w second element
- * @return true if the first element is greater than or equal the second
- * element
+ * @param firstElement the first element to compare
+ * @param secondElement the second element to compare
+ * @return true if the first element is greater than or equal to the second, false otherwise
*/
- static > boolean greaterOrEqual(T v, T w) {
- return v.compareTo(w) >= 0;
+ static > boolean greaterOrEqual(T firstElement, T secondElement) {
+ return firstElement.compareTo(secondElement) >= 0;
}
/**
- * Prints a list
+ * Prints the elements of a list to standard output.
*
- * @param toPrint - a list which should be printed
+ * @param listToPrint the list to print
*/
- static void print(List> toPrint) {
- toPrint
- .stream()
- .map(Object::toString)
- .map(str -> str + " ")
- .forEach(System.out::print);
-
- System.out.println();
+ static void print(List> listToPrint) {
+ String result = listToPrint.stream()
+ .map(Object::toString)
+ .collect(Collectors.joining(" "));
+ System.out.println(result);
}
/**
- * Prints an array
+ * Prints the elements of an array to standard output.
*
- * @param toPrint - an array which should be printed
+ * @param array the array to print
*/
- static void print(Object[] toPrint) {
- System.out.println(Arrays.toString(toPrint));
+ static void print(T[] array) {
+ System.out.println(Arrays.toString(array));
}
/**
- * Swaps all position from {
+ * Flips the order of elements in the specified range of an array.
*
- * @param left} to @{
- * @param right} for {
- * @param array}
- *
- * @param array is an array
- * @param left is a left flip border of the array
- * @param right is a right flip border of the array
+ * @param array the array whose elements are to be flipped
+ * @param left the left boundary of the range to be flipped (inclusive)
+ * @param right the right boundary of the range to be flipped (inclusive)
*/
- static > void flip(T[] array, int left, int right) {
+ public static > void flip(T[] array, int left, int right) {
while (left <= right) {
swap(array, left++, right--);
}
}
/**
- * Function to check if the array is sorted. By default, it will check if the array is sorted in ASC order.
+ * Checks whether the array is sorted in ascending order.
*
- * @param array - an array which to check is it sorted or not.
- * @return true - if array sorted in ASC order, false otherwise.
+ * @param array the array to check
+ * @return true if the array is sorted in ascending order, false otherwise
*/
- static > boolean isSorted(T[] array) {
- for (int i = 1; i < array.length; i++)
- if (less(array[i], array[i - 1]))
+ public static > boolean isSorted(T[] array) {
+ for (int i = 1; i < array.length; i++) {
+ if (less(array[i], array[i - 1])) {
return false;
+ }
+ }
return true;
}
- static > boolean isSorted(List list) {
- for (int i = 1; i < list.size(); i++)
- if (less(list.get(i), list.get(i - 1)))
+ /**
+ * Checks whether the list is sorted in ascending order.
+ *
+ * @param list the list to check
+ * @return true if the list is sorted in ascending order, false otherwise
+ */
+ public static > boolean isSorted(List list) {
+ for (int i = 1; i < list.size(); i++) {
+ if (less(list.get(i), list.get(i - 1))) {
return false;
+ }
+ }
return true;
}
}
From ad72c28d91989460f61917b28545f4f33c2771d4 Mon Sep 17 00:00:00 2001
From: Saurabh Rahate <55960054+saurabh-rahate@users.noreply.github.com>
Date: Mon, 3 Apr 2023 20:05:59 +0530
Subject: [PATCH 0010/1457] Remove unnecessary code (#4141)
---
.../com/thealgorithms/ciphers/Blowfish.java | 2 +-
.../com/thealgorithms/ciphers/HillCipher.java | 1 -
.../conversions/AnyBaseToAnyBase.java | 2 +-
.../conversions/OctalToDecimal.java | 3 +--
.../datastructures/graphs/BellmanFord.java | 4 ++--
.../graphs/BipartiteGrapfDFS.java | 2 +-
.../graphs/DIJSKSTRAS_ALGORITHM.java | 2 +-
.../datastructures/graphs/MatrixGraphs.java | 12 ++++------
.../datastructures/graphs/PrimMST.java | 4 ++--
.../graphs/TarjansAlgorithm.java | 2 +-
.../datastructures/heaps/FibonacciHeap.java | 1 -
.../heaps/MinPriorityQueue.java | 10 ++------
.../lists/CursorLinkedList.java | 3 +--
.../lists/SinglyLinkedList.java | 4 ++--
.../datastructures/queues/CircularQueue.java | 12 ++--------
.../datastructures/queues/Deques.java | 3 +--
.../datastructures/queues/Queues.java | 2 +-
.../datastructures/trees/AVLSimple.java | 3 +--
.../datastructures/trees/AVLTree.java | 17 +++++--------
.../datastructures/trees/BinaryTree.java | 8 ++-----
.../datastructures/trees/GenericTree.java | 1 -
.../datastructures/trees/RedBlackBST.java | 23 ++++++++----------
.../datastructures/trees/TrieImp.java | 2 +-
.../BruteForceKnapsack.java | 10 +-------
.../DyanamicProgrammingKnapsack.java | 8 +------
.../dynamicprogramming/EditDistance.java | 7 +++---
.../LongestCommonSubsequence.java | 5 +---
.../LongestPalindromicSubstring.java | 14 ++---------
.../MatrixChainMultiplication.java | 2 +-
.../PalindromicPartitioning.java | 14 ++++-------
.../dynamicprogramming/RegexMatching.java | 4 ++--
.../dynamicprogramming/WineProblem.java | 4 +---
.../thealgorithms/maths/AmicableNumber.java | 2 +-
.../com/thealgorithms/maths/Combinations.java | 3 +--
.../thealgorithms/maths/DistanceFormula.java | 6 ++---
.../com/thealgorithms/maths/EulerMethod.java | 24 ++++---------------
.../thealgorithms/maths/FastInverseSqrt.java | 2 +-
.../maths/KrishnamurthyNumber.java | 6 +----
.../thealgorithms/maths/StandardScore.java | 3 +--
.../others/BankersAlgorithm.java | 4 ++--
.../com/thealgorithms/others/Dijkstra.java | 10 +-------
...g_auto_completing_features_using_trie.java | 2 +-
.../others/LowestBasePalindrome.java | 2 +-
.../others/MiniMaxAlgorithm.java | 8 +++----
.../com/thealgorithms/others/PageRank.java | 4 ++--
.../others/RemoveDuplicateFromString.java | 2 +-
.../thealgorithms/searches/BinarySearch.java | 16 +++----------
.../searches/ExponentalSearch.java | 16 +++----------
.../searches/InterpolationSearch.java | 18 ++++----------
.../searches/IterativeBinarySearch.java | 16 +++----------
.../searches/IterativeTernarySearch.java | 16 +++----------
.../thealgorithms/searches/LinearSearch.java | 6 ++---
.../thealgorithms/searches/LowerBound.java | 16 +++----------
.../searches/MonteCarloTreeSearch.java | 6 ++---
.../thealgorithms/searches/TernarySearch.java | 16 +++----------
.../thealgorithms/searches/UpperBound.java | 16 +++----------
.../com/thealgorithms/sorts/BeadSort.java | 2 +-
.../com/thealgorithms/sorts/CircleSort.java | 2 +-
.../com/thealgorithms/sorts/CombSort.java | 2 +-
.../sorts/MergeSortRecursive.java | 3 +--
.../com/thealgorithms/sorts/TreeSort.java | 16 ++++++-------
.../com/thealgorithms/sorts/WiggleSort.java | 2 +-
.../strings/LongestPalindromicSubstring.java | 2 +-
.../com/thealgorithms/strings/MyAtoi.java | 7 +-----
64 files changed, 125 insertions(+), 322 deletions(-)
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index 7e74cc6dab3e..b60cf7c7ac74 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -1079,7 +1079,7 @@ public class Blowfish {
*/
private String hexToBin(String hex) {
String binary = "";
- Long num;
+ long num;
String binary4B;
int n = hex.length();
for (int i = 0; i < n; i++) {
diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
index f989502ed6d2..102d760d16c1 100644
--- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
@@ -160,7 +160,6 @@ static void validateDeterminant(int[][] keyMatrix, int n) {
System.out.println(
"Invalid key, as determinant = 0. Program Terminated"
);
- return;
}
}
diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
index 25d9ded3b458..b5974dd65f3b 100644
--- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
+++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
@@ -175,7 +175,7 @@ public static String base2base(String n, int b1, int b2) {
// If the remainder is a digit < 10, simply add it to
// the left side of the new number.
if (decimalValue % b2 < 10) {
- output = Integer.toString(decimalValue % b2) + output;
+ output = decimalValue % b2 + output;
} // If the remainder is >= 10, add a character with the
// corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
else {
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
index be8b43375cc2..782f3488383b 100644
--- a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
@@ -34,8 +34,7 @@ public static void main(String args[]) {
public static int convertOctalToDecimal(String inputOctal) {
try {
// Actual conversion of Octal to Decimal:
- Integer outputDecimal = Integer.parseInt(inputOctal, 8);
- return outputDecimal;
+ return Integer.parseInt(inputOctal, 8);
} catch (NumberFormatException ne) {
// Printing a warning message if the input is not a valid octal
// number:
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
index ac0898e10a30..b640eeaf599d 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
@@ -74,7 +74,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
+ dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
@@ -85,7 +85,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde
// Final cycle for negative checking
for (j = 0; j < e; j++) {
if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
+ dist[arr[j].u] != Integer.MAX_VALUE &&
dist[arr[j].v] > dist[arr[j].u] + arr[j].w
) {
neg = 1;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
index 5d484d187eea..651b3e617794 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
@@ -28,7 +28,7 @@ private static boolean bipartite(
for (Integer it : adj.get(node)) {
if (color[it] == -1) {
color[it] = 1 - color[node];
- if (bipartite(V, adj, color, it) == false) {
+ if (!bipartite(V, adj, color, it)) {
return false;
}
} else if (color[it] == color[node]) {
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
index 928516d2ba54..5b8533b8df59 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
@@ -12,7 +12,7 @@ int minDist(int dist[], Boolean Set[]) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int r = 0; r < k; r++) {
- if (Set[r] == false && dist[r] <= min) {
+ if (!Set[r] && dist[r] <= min) {
min = dist[r];
min_index = r;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
index 90386230b95a..8d382cdde8f9 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
@@ -154,11 +154,7 @@ private boolean adjacencyOfEdgeDoesExist(int from, int to) {
* @return whether or not the vertex exists
*/
public boolean vertexDoesExist(int aVertex) {
- if (aVertex >= 0 && aVertex < this.numberOfVertices()) {
- return true;
- } else {
- return false;
- }
+ return aVertex >= 0 && aVertex < this.numberOfVertices();
}
/**
@@ -343,14 +339,14 @@ public List breadthFirstOrder(int startVertex) {
public String toString() {
String s = " ";
for (int i = 0; i < this.numberOfVertices(); i++) {
- s = s + String.valueOf(i) + " ";
+ s = s + i + " ";
}
s = s + " \n";
for (int i = 0; i < this.numberOfVertices(); i++) {
- s = s + String.valueOf(i) + " : ";
+ s = s + i + " : ";
for (int j = 0; j < this.numberOfVertices(); j++) {
- s = s + String.valueOf(this._adjacency[i][j]) + " ";
+ s = s + this._adjacency[i][j] + " ";
}
s = s + "\n";
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
index 4365f721436f..75de04713d47 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
@@ -17,7 +17,7 @@ int minKey(int key[], Boolean mstSet[]) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int v = 0; v < V; v++) {
- if (mstSet[v] == false && key[v] < min) {
+ if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
}
@@ -80,7 +80,7 @@ void primMST(int graph[][]) {
{
if (
graph[u][v] != 0 &&
- mstSet[v] == false &&
+ !mstSet[v] &&
graph[u][v] < key[v]
) {
parent[v] = u;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index 18e43c49daf2..bb633c4ee6c0 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -114,7 +114,7 @@ private void stronglyConnCompsUtil(int u, int lowTime[], int insertionTime[],
stronglyConnCompsUtil(n, lowTime, insertionTime, isInStack, st, graph);
//update lowTime for the current node comparing lowtime of adj node
lowTime[u] = Math.min(lowTime[u], lowTime[n]);
- } else if (isInStack[n] == true) {
+ } else if (isInStack[n]) {
//If adj node is in stack, update low
lowTime[u] = Math.min(lowTime[u], insertionTime[n]);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
index 3359ccb5e70c..eeeb591c2e02 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -234,7 +234,6 @@ private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { //stop the recursion
curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++;
- return;
} else {
if (curr.isRoot()) {
return;
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
index 034e32ce9481..23ac5d3aaabf 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java
@@ -51,18 +51,12 @@ public int peek() {
// returns boolean value whether the heap is empty or not
public boolean isEmpty() {
- if (0 == this.size) {
- return true;
- }
- return false;
+ return 0 == this.size;
}
// returns boolean value whether the heap is full or not
public boolean isFull() {
- if (this.size == this.capacity) {
- return true;
- }
- return false;
+ return this.size == this.capacity;
}
// prints the heap
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
index b3ad535c7121..6ed317d6d4ef 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java
@@ -174,8 +174,7 @@ private int alloc() {
}
// 2- make the os point to the next of the @var{availableNodeIndex}
- int availableNext = cursorSpace[availableNodeIndex].next;
- cursorSpace[os].next = availableNext;
+ cursorSpace[os].next = cursorSpace[availableNodeIndex].next;
// this to indicate an end of the list , helpful at testing since any err
// would throw an outOfBoundException
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index 03ce735f2f5e..a4276b021002 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -407,7 +407,7 @@ public static void main(String[] arg) {
list.insert(3);
list.insertNth(1, 4);
assert list.toString().equals("10->7->5->3->1");
- System.out.println(list.toString());
+ System.out.println(list);
/* Test search function */
assert list.search(10) &&
list.search(5) &&
@@ -424,7 +424,7 @@ public static void main(String[] arg) {
list.deleteNth(1);
list.delete();
assert list.toString().equals("7->3");
- System.out.println(list.toString());
+ System.out.println(list);
assert list.size == 2 && list.size() == list.count();
list.clear();
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
index 18293bffe077..e5bedd9beae3 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java
@@ -17,21 +17,13 @@ public CircularQueue(int size) {
}
public boolean isEmpty() {
- if (beginningOfQueue == -1) {
- return true;
- } else {
- return false;
- }
+ return beginningOfQueue == -1;
}
public boolean isFull() {
if (topOfQueue + 1 == beginningOfQueue) {
return true;
- } else if (topOfQueue == size - 1 && beginningOfQueue == 0) {
- return true;
- } else {
- return false;
- }
+ } else return topOfQueue == size - 1 && beginningOfQueue == 0;
}
public void enQueue(int value) {
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/Deques.java b/src/main/java/com/thealgorithms/datastructures/queues/Deques.java
index 06d7c5995111..5c4e9b641445 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/Deques.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/Deques.java
@@ -91,13 +91,12 @@ public void addLast(T val) {
if (tail == null) {
// If the deque is empty, add the node as the head and tail
head = newNode;
- tail = newNode;
} else {
// If the deque is not empty, insert the node as the new tail
newNode.prev = tail;
tail.next = newNode;
- tail = newNode;
}
+ tail = newNode;
size++;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/Queues.java b/src/main/java/com/thealgorithms/datastructures/queues/Queues.java
index 47de89928628..bcc292b3e9a9 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/Queues.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/Queues.java
@@ -177,6 +177,6 @@ public static void main(String[] args) {
System.out.println(myQueue.peekFront()); // Will print 2
System.out.println(myQueue.peekRear()); // Will print 7
- System.out.println(myQueue.toString()); // Will print [2, 5, 3, 7]
+ System.out.println(myQueue); // Will print [2, 5, 3, 7]
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
index 72fe7972d329..85c44707ea24 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
@@ -49,8 +49,7 @@ public void insert(int data) {
private Node insert(Node node, int item) {
if (node == null) {
- Node add = new Node(item);
- return add;
+ return new Node(item);
}
if (node.data > item) {
node.left = insert(node.left, item);
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
index 5549adbd29b7..b56a71421ed3 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
@@ -62,21 +62,20 @@ private void delete(Node node) {
}
return;
}
+ Node child;
if (node.left != null) {
- Node child = node.left;
+ child = node.left;
while (child.right != null) {
child = child.right;
}
- node.key = child.key;
- delete(child);
} else {
- Node child = node.right;
+ child = node.right;
while (child.left != null) {
child = child.left;
}
- node.key = child.key;
- delete(child);
}
+ node.key = child.key;
+ delete(child);
}
public void delete(int delKey) {
@@ -216,11 +215,7 @@ private void reheight(Node node) {
public boolean search(int key) {
Node result = searchHelper(this.root, key);
- if (result != null) {
- return true;
- }
-
- return false;
+ return result != null;
}
private Node searchHelper(Node root, int key) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
index 48dfe9658467..fc0db9b8cd92 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
@@ -117,11 +117,9 @@ public void put(int value) {
if (value < parent.data) {
parent.left = newNode;
parent.left.parent = parent;
- return;
} else {
parent.right = newNode;
parent.right.parent = parent;
- return;
}
}
}
@@ -177,7 +175,6 @@ else if (temp.left != null && temp.right != null) {
if (temp == root) {
successor.parent = null;
root = successor;
- return true;
} // If you're not deleting the root
else {
successor.parent = temp.parent;
@@ -188,8 +185,8 @@ else if (temp.left != null && temp.right != null) {
} else {
temp.parent.left = successor;
}
- return true;
}
+ return true;
} // One child
else {
// If it has a right child
@@ -207,7 +204,6 @@ else if (temp.left != null && temp.right != null) {
} else {
temp.parent.right = temp.right;
}
- return true;
} // If it has a left child
else {
if (temp == root) {
@@ -223,8 +219,8 @@ else if (temp.left != null && temp.right != null) {
} else {
temp.parent.right = temp.left;
}
- return true;
}
+ return true;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
index 9f776e6d7df4..c22bdab08f2b 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
@@ -168,7 +168,6 @@ public void depth(Node node, int dep) {
for (int i = 0; i < node.child.size(); i++) {
depth(node.child.get(i), dep - 1);
}
- return;
}
/**
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
index d7f34007fa87..7103a9ead2ca 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
@@ -309,23 +309,20 @@ void deleteFixup(Node x) {
public void insertDemo() {
Scanner scan = new Scanner(System.in);
- while (true) {
- System.out.println("Add items");
+ System.out.println("Add items");
- int item;
- Node node;
+ int item;
+ Node node;
+ item = scan.nextInt();
+ while (item != -999) {
+ node = new Node(item);
+ insert(node);
item = scan.nextInt();
- while (item != -999) {
- node = new Node(item);
- insert(node);
- item = scan.nextInt();
- }
- printTree(root);
- System.out.println("Pre order");
- printTreepre(root);
- break;
}
+ printTree(root);
+ System.out.println("Pre order");
+ printTreepre(root);
scan.close();
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
index a650900a23ba..5829f920cac8 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java
@@ -62,7 +62,7 @@ public boolean delete(String word) {
}
currentNode = node;
}
- if (currentNode.end == true) {
+ if (currentNode.end) {
currentNode.end = false;
return true;
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
index 4e2e25484bb8..49031152e57d 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
@@ -3,13 +3,6 @@
/* A Naive recursive implementation
of 0-1 Knapsack problem */
public class BruteForceKnapsack {
-
- // A utility function that returns
- // maximum of two integers
- static int max(int a, int b) {
- return (a > b) ? a : b;
- }
-
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
@@ -29,8 +22,7 @@ static int knapSack(int W, int wt[], int val[], int n) {
// (1) nth item included
// (2) not included
else {
- return max(
- val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
+ return Math.max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1)
);
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
index ffbefd479552..445f1e9d0517 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
@@ -3,11 +3,6 @@
// A Dynamic Programming based solution
// for 0-1 Knapsack problem
public class DyanamicProgrammingKnapsack {
-
- static int max(int a, int b) {
- return (a > b) ? a : b;
- }
-
// Returns the maximum value that can
// be put in a knapsack of capacity W
static int knapSack(int W, int wt[], int val[], int n) {
@@ -20,8 +15,7 @@ static int knapSack(int W, int wt[], int val[], int n) {
if (i == 0 || w == 0) {
K[i][w] = 0;
} else if (wt[i - 1] <= w) {
- K[i][w] =
- max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
+ K[i][w] = Math.max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
} else {
K[i][w] = K[i - 1][w];
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
index 0f27ba0bcc26..5141e12db2a5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
@@ -57,8 +57,8 @@ then take the minimum of the various operations(i.e insertion,removal,substituti
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
- int min = replace > insert ? insert : replace;
- min = delete > min ? min : delete;
+ int min = Math.min(replace, insert);
+ min = Math.min(delete, min);
dp[i + 1][j + 1] = min;
}
}
@@ -110,13 +110,12 @@ public static int editDistance(String s1, String s2, int[][] storage) {
if (s1.charAt(0) == s2.charAt(0)) {
storage[m][n] =
editDistance(s1.substring(1), s2.substring(1), storage);
- return storage[m][n];
} else {
int op1 = editDistance(s1, s2.substring(1), storage);
int op2 = editDistance(s1.substring(1), s2, storage);
int op3 = editDistance(s1.substring(1), s2.substring(1), storage);
storage[m][n] = 1 + Math.min(op1, Math.min(op2, op3));
- return storage[m][n];
}
+ return storage[m][n];
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
index b749423642fe..a2711a810cf8 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
@@ -30,10 +30,7 @@ public static String getLCS(String str1, String str2) {
if (arr1[i - 1].equals(arr2[j - 1])) {
lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1;
} else {
- lcsMatrix[i][j] =
- lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]
- ? lcsMatrix[i - 1][j]
- : lcsMatrix[i][j - 1];
+ lcsMatrix[i][j] = Math.max(lcsMatrix[i - 1][j], lcsMatrix[i][j - 1]);
}
}
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
index 1d7bbe438cdf..824bce085b83 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
@@ -27,19 +27,9 @@ private static String LPS(String input) {
if (g == 0) {
arr[i][j] = true;
} else if (g == 1) {
- if (input.charAt(i) == input.charAt(j)) {
- arr[i][j] = true;
- } else {
- arr[i][j] = false;
- }
+ arr[i][j] = input.charAt(i) == input.charAt(j);
} else {
- if (
- input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]
- ) {
- arr[i][j] = true;
- } else {
- arr[i][j] = false;
- }
+ arr[i][j] = input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1];
}
if (arr[i][j]) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
index 5c4be18e38dc..7a3213558ef2 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
@@ -87,7 +87,7 @@ private static void printOptimalParens(int i, int j) {
private static void printArray(int[][] array) {
for (int i = 1; i < size + 1; i++) {
for (int j = 1; j < size + 1; j++) {
- System.out.print(String.format("%7d", array[i][j]));
+ System.out.printf("%7d", array[i][j]);
}
System.out.println();
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java
index e1218fefccb7..98b9d163141c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java
@@ -48,27 +48,21 @@ public static int minimalpartitions(String word) {
if (L == 2) {
isPalindrome[i][j] = (word.charAt(i) == word.charAt(j));
} else {
- if (
- (word.charAt(i) == word.charAt(j)) &&
- isPalindrome[i + 1][j - 1]
- ) {
- isPalindrome[i][j] = true;
- } else {
- isPalindrome[i][j] = false;
- }
+ isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) &&
+ isPalindrome[i + 1][j - 1];
}
}
}
//We find the minimum for each index
for (i = 0; i < len; i++) {
- if (isPalindrome[0][i] == true) {
+ if (isPalindrome[0][i]) {
minCuts[i] = 0;
} else {
minCuts[i] = Integer.MAX_VALUE;
for (j = 0; j < i; j++) {
if (
- isPalindrome[j + 1][i] == true &&
+ isPalindrome[j + 1][i] &&
1 + minCuts[j] < minCuts[i]
) {
minCuts[i] = 1 + minCuts[j];
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
index 238d8abcdae3..5994ffe8dde5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
@@ -112,7 +112,7 @@ static boolean regexRecursion(
return true;
}
if (strg[svidx][pvidx] != 0) {
- return strg[svidx][pvidx] == 1 ? false : true;
+ return strg[svidx][pvidx] != 1;
}
char chs = src.charAt(svidx);
char chp = pat.charAt(pvidx);
@@ -127,7 +127,7 @@ static boolean regexRecursion(
} else {
ans = false;
}
- strg[svidx][pvidx] = ans == false ? 1 : 2;
+ strg[svidx][pvidx] = ans ? 2 : 1;
return ans;
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
index ce8836ee6a9c..8e48218063c6 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
@@ -24,9 +24,7 @@ public static int WPRecursion(int[] arr, int si, int ei) {
int start = WPRecursion(arr, si + 1, ei) + arr[si] * year;
int end = WPRecursion(arr, si, ei - 1) + arr[ei] * year;
- int ans = Math.max(start, end);
-
- return ans;
+ return Math.max(start, end);
}
// Method 2: Top-Down DP(Memoization)
diff --git a/src/main/java/com/thealgorithms/maths/AmicableNumber.java b/src/main/java/com/thealgorithms/maths/AmicableNumber.java
index 4b49e21c726e..3efea0e16f4f 100644
--- a/src/main/java/com/thealgorithms/maths/AmicableNumber.java
+++ b/src/main/java/com/thealgorithms/maths/AmicableNumber.java
@@ -58,7 +58,7 @@ static void findAllInRange(int startValue, int stopValue) {
countofRes +
" Amicable_numbers.These are \n "
);
- System.out.println(res.toString());
+ System.out.println(res);
}
/**
diff --git a/src/main/java/com/thealgorithms/maths/Combinations.java b/src/main/java/com/thealgorithms/maths/Combinations.java
index 34b324466725..68d653229fa9 100644
--- a/src/main/java/com/thealgorithms/maths/Combinations.java
+++ b/src/main/java/com/thealgorithms/maths/Combinations.java
@@ -52,8 +52,7 @@ public static long combinationsOptimized(int n, int k) {
// nC0 is always 1
long solution = 1;
for (int i = 0; i < k; i++) {
- long next = (n - i) * solution / (i + 1);
- solution = next;
+ solution = (n - i) * solution / (i + 1);
}
return solution;
}
diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
index 96f8e6969f7c..89f9b4298077 100644
--- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java
+++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
@@ -10,8 +10,7 @@ public static double euclideanDistance(
) {
double dX = Math.pow(x2 - x1, 2);
double dY = Math.pow(y2 - x1, 2);
- double d = Math.sqrt(dX + dY);
- return d;
+ return Math.sqrt(dX + dY);
}
public static double manhattanDistance(
@@ -20,8 +19,7 @@ public static double manhattanDistance(
double x2,
double y2
) {
- double d = Math.abs(x1 - x2) + Math.abs(y1 - y2);
- return d;
+ return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
public static int hammingDistance(int[] b1, int[] b2) {
diff --git a/src/main/java/com/thealgorithms/maths/EulerMethod.java b/src/main/java/com/thealgorithms/maths/EulerMethod.java
index 4904c5038f04..eca4007656be 100644
--- a/src/main/java/com/thealgorithms/maths/EulerMethod.java
+++ b/src/main/java/com/thealgorithms/maths/EulerMethod.java
@@ -26,22 +26,14 @@ public static void main(String[] args) {
BiFunction exampleEquation1 = (x, y) -> x;
ArrayList points1 = eulerFull(0, 4, 0.1, 0, exampleEquation1);
assert points1.get(points1.size() - 1)[1] == 7.800000000000003;
- points1.forEach(point ->
- System.out.println(
- String.format("x: %1$f; y: %2$f", point[0], point[1])
- )
- );
+ points1.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1]));
// example from https://en.wikipedia.org/wiki/Euler_method
System.out.println("\n\nexample 2:");
BiFunction exampleEquation2 = (x, y) -> y;
ArrayList points2 = eulerFull(0, 4, 0.1, 1, exampleEquation2);
assert points2.get(points2.size() - 1)[1] == 45.25925556817596;
- points2.forEach(point ->
- System.out.println(
- String.format("x: %1$f; y: %2$f", point[0], point[1])
- )
- );
+ points2.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1]));
// example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/
System.out.println("\n\nexample 3:");
@@ -55,11 +47,7 @@ public static void main(String[] args) {
exampleEquation3
);
assert points3.get(points3.size() - 1)[1] == 1.1116729841674804;
- points3.forEach(point ->
- System.out.println(
- String.format("x: %1$f; y: %2$f", point[0], point[1])
- )
- );
+ points3.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1]));
}
/**
@@ -83,11 +71,7 @@ public static double eulerStep(
"stepSize should be greater than zero"
);
}
- double yNext =
- yCurrent +
- stepSize *
- differentialEquation.apply(xCurrent, yCurrent);
- return yNext;
+ return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent);
}
/**
diff --git a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
index c8ba532b2598..1e30374e57f0 100644
--- a/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
+++ b/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
@@ -17,7 +17,7 @@ public static boolean inverseSqrt(float number) {
i = 0x5f3759df - (i >> 1);
x = Float.intBitsToFloat(i);
x = x * (1.5f - xhalf * x * x);
- return x == (float) ((float) 1 / (float) Math.sqrt(number));
+ return x == ((float) 1 / (float) Math.sqrt(number));
}
/**
diff --git a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java
index 64569be4b6c3..28fe772ed14d 100644
--- a/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java
+++ b/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java
@@ -36,11 +36,7 @@ public static boolean isKMurthy(int n) {
}
//evaluating if sum of the factorials of the digits equals the number itself
- if (tmp == s) {
- return true;
- } else {
- return false;
- }
+ return tmp == s;
}
}
diff --git a/src/main/java/com/thealgorithms/maths/StandardScore.java b/src/main/java/com/thealgorithms/maths/StandardScore.java
index 42a41f3cb036..dcedf458b09e 100644
--- a/src/main/java/com/thealgorithms/maths/StandardScore.java
+++ b/src/main/java/com/thealgorithms/maths/StandardScore.java
@@ -3,7 +3,6 @@
public class StandardScore {
public static double zScore(double num, double mean, double stdDev) {
- double z = (num - mean) / stdDev;
- return z;
+ return (num - mean) / stdDev;
}
}
diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
index f6d683a22eef..1c7870e05fe7 100644
--- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
@@ -88,7 +88,7 @@ static boolean checkSafeSystem(
while (count < totalProcess) {
boolean foundSafeSystem = false;
for (int m = 0; m < totalProcess; m++) {
- if (finishProcesses[m] == false) {
+ if (!finishProcesses[m]) {
int j;
for (j = 0; j < totalResources; j++) {
@@ -112,7 +112,7 @@ static boolean checkSafeSystem(
}
// If we could not find a next process in safe sequence.
- if (foundSafeSystem == false) {
+ if (!foundSafeSystem) {
System.out.print(
"The system is not in the safe state because lack of resources"
);
diff --git a/src/main/java/com/thealgorithms/others/Dijkstra.java b/src/main/java/com/thealgorithms/others/Dijkstra.java
index 8f5a5f570aa8..e2cd2630da51 100644
--- a/src/main/java/com/thealgorithms/others/Dijkstra.java
+++ b/src/main/java/com/thealgorithms/others/Dijkstra.java
@@ -131,15 +131,7 @@ public boolean equals(Object object) {
) {
return false;
}
- if (
- neighbours != null
- ? !neighbours.equals(vertex.neighbours)
- : vertex.neighbours != null
- ) {
- return false;
- }
-
- return true;
+ return neighbours != null ? neighbours.equals(vertex.neighbours) : vertex.neighbours == null;
}
@Override
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 6364c5cd3df1..08cdd44fb33a 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
@@ -120,7 +120,7 @@ static int printAutoSuggestions(TrieNode root, final String query) {
}
// If prefix is present as a word.
- boolean isWord = (pCrawl.isWordEnd == true);
+ boolean isWord = (pCrawl.isWordEnd);
// If prefix is last node of tree (has no
// children)
diff --git a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
index 95fffd41ca90..3d50b4840f17 100644
--- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
+++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
@@ -139,7 +139,7 @@ private static String base2base(String n, int b1, int b2) {
// If the remainder is a digit < 10, simply add it to
// the left side of the new number.
if (decimalValue % b2 < 10) {
- output = Integer.toString(decimalValue % b2) + output;
+ output = decimalValue % b2 + output;
} // If the remainder is >= 10, add a character with the
// corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
else {
diff --git a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java
index 87ecd8594842..f05d19389fad 100644
--- a/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/MiniMaxAlgorithm.java
@@ -46,7 +46,7 @@ public static void main(String[] args) {
"The best score for " +
(isMaximizer ? "Maximizer" : "Minimizer") +
" is " +
- String.valueOf(bestScore)
+ bestScore
);
}
@@ -88,14 +88,12 @@ public int miniMax(
// (1 x 2) = 2; ((1 x 2) + 1) = 3
// (2 x 2) = 4; ((2 x 2) + 1) = 5 ...
if (verbose) {
- System.out.println(
- String.format(
- "From %02d and %02d, %s chooses %02d",
+ System.out.printf(
+ "From %02d and %02d, %s chooses %02d%n",
score1,
score2,
(isMaximizer ? "Maximizer" : "Minimizer"),
bestScore
- )
);
}
diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java
index b25ca3e3f61a..8d67ff8f983c 100644
--- a/src/main/java/com/thealgorithms/others/PageRank.java
+++ b/src/main/java/com/thealgorithms/others/PageRank.java
@@ -49,7 +49,7 @@ public void calc(double totalNodes) {
for (k = 1; k <= totalNodes; k++) {
this.pagerank[k] = InitialPageRank;
}
- System.out.printf("\n Initial PageRank Values , 0th Step \n");
+ System.out.print("\n Initial PageRank Values , 0th Step \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(
@@ -113,7 +113,7 @@ public void calc(double totalNodes) {
}
// Display PageRank
- System.out.printf("\n Final Page Rank : \n");
+ System.out.print("\n Final Page Rank : \n");
for (k = 1; k <= totalNodes; k++) {
System.out.printf(
" Page Rank of " + k + " is :\t" + this.pagerank[k] + "\n"
diff --git a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java
index b1e13816dea8..0b410a9d5947 100644
--- a/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java
+++ b/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java
@@ -40,7 +40,7 @@ public static String removeDuplicate(String s) {
for (int i = 0; i < n; i++) {
if (sb.toString().indexOf(s.charAt(i)) == -1) {
- sb.append(String.valueOf(s.charAt(i)));
+ sb.append(s.charAt(i));
}
}
diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java
index 18ec2c0c4ee7..bc5b41580e20 100644
--- a/src/main/java/com/thealgorithms/searches/BinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
import java.util.Random;
@@ -86,23 +84,15 @@ public static void main(String[] args) {
BinarySearch search = new BinarySearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
index f1fc7705f35c..1b9accdca308 100644
--- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
+++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
import java.util.Random;
@@ -29,24 +27,16 @@ public static void main(String[] args) {
ExponentialSearch search = new ExponentialSearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
@Override
diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
index bb53389a113d..0632971b7296 100644
--- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
+++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import java.util.Arrays;
import java.util.Random;
import java.util.stream.IntStream;
@@ -67,28 +65,20 @@ public static void main(String[] args) {
.toArray();
// the element that should be found
- Integer shouldBeFound = integers[r.nextInt(size - 1)];
+ int shouldBeFound = integers[r.nextInt(size - 1)];
InterpolationSearch search = new InterpolationSearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- String.format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java
index 7f71ba3dd12a..cec8703bed1f 100644
--- a/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/IterativeBinarySearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
import java.util.Random;
@@ -72,23 +70,15 @@ public static void main(String[] args) {
IterativeBinarySearch search = new IterativeBinarySearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- String.format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
index 176091229112..933056987b4e 100644
--- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
import java.util.Random;
@@ -70,23 +68,15 @@ public static void main(String[] args) {
IterativeTernarySearch search = new IterativeTernarySearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java
index bd97d0a9c7d9..350cfc6e8861 100644
--- a/src/main/java/com/thealgorithms/searches/LinearSearch.java
+++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java
@@ -53,14 +53,12 @@ public static void main(String[] args) {
LinearSearch search = new LinearSearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- String.format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java
index 0822ae6df007..d800a6cc1db6 100644
--- a/src/main/java/com/thealgorithms/searches/LowerBound.java
+++ b/src/main/java/com/thealgorithms/searches/LowerBound.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
@@ -48,24 +46,16 @@ public static void main(String[] args) {
LowerBound search = new LowerBound();
int atIndex = search.find(integers, val);
- System.out.println(
- format(
- "Val: %d. Lower Bound Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Val: %d. Lower Bound Found %d at index %d. An array length %d%n",
val,
integers[atIndex],
atIndex,
size
- )
);
boolean toCheck = integers[atIndex] >= val || integers[size - 1] < val;
- System.out.println(
- format(
- "Lower Bound found at an index: %d. Is greater or max element: %b",
- atIndex,
- toCheck
- )
- );
+ System.out.printf("Lower Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
}
/**
diff --git a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java
index 3765d871bdf1..88c097b039ad 100644
--- a/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java
+++ b/src/main/java/com/thealgorithms/searches/MonteCarloTreeSearch.java
@@ -187,13 +187,11 @@ public void printScores(Node rootNode) {
System.out.println("N.\tScore\t\tVisits");
for (int i = 0; i < rootNode.childNodes.size(); i++) {
- System.out.println(
- String.format(
- "%02d\t%d\t\t%d",
+ System.out.printf(
+ "%02d\t%d\t\t%d%n",
i + 1,
rootNode.childNodes.get(i).score,
rootNode.childNodes.get(i).visitCount
- )
);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java
index 170b3e104b45..5b447fa4912f 100644
--- a/src/main/java/com/thealgorithms/searches/TernarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
import java.util.Random;
@@ -89,23 +87,15 @@ public static void main(String[] args) {
TernarySearch search = new TernarySearch();
int atIndex = search.find(integers, shouldBeFound);
- System.out.println(
- format(
- "Should be found: %d. Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Should be found: %d. Found %d at index %d. An array length %d%n",
shouldBeFound,
integers[atIndex],
atIndex,
size
- )
);
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
- System.out.println(
- format(
- "Found by system method at an index: %d. Is equal: %b",
- toCheck,
- toCheck == atIndex
- )
- );
+ System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
}
}
diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java
index 0b5cfa09091d..1c842fbccb0a 100644
--- a/src/main/java/com/thealgorithms/searches/UpperBound.java
+++ b/src/main/java/com/thealgorithms/searches/UpperBound.java
@@ -1,7 +1,5 @@
package com.thealgorithms.searches;
-import static java.lang.String.format;
-
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
@@ -48,24 +46,16 @@ public static void main(String[] args) {
UpperBound search = new UpperBound();
int atIndex = search.find(integers, val);
- System.out.println(
- format(
- "Val: %d. Upper Bound Found %d at index %d. An array length %d",
+ System.out.printf(
+ "Val: %d. Upper Bound Found %d at index %d. An array length %d%n",
val,
integers[atIndex],
atIndex,
size
- )
);
boolean toCheck = integers[atIndex] > val || integers[size - 1] < val;
- System.out.println(
- format(
- "Upper Bound found at an index: %d. Is greater or max element: %b",
- atIndex,
- toCheck
- )
- );
+ System.out.printf("Upper Bound found at an index: %d. Is greater or max element: %b%n", atIndex, toCheck);
}
/**
diff --git a/src/main/java/com/thealgorithms/sorts/BeadSort.java b/src/main/java/com/thealgorithms/sorts/BeadSort.java
index dd064b4fe125..cd60ab0b585f 100644
--- a/src/main/java/com/thealgorithms/sorts/BeadSort.java
+++ b/src/main/java/com/thealgorithms/sorts/BeadSort.java
@@ -27,7 +27,7 @@ public int[] sort(int[] unsorted) {
for(int i = 0; i < unsorted.length; i++) {
int k = 0;
- for(int j = 0; j < (int) unsorted[i] ; j++) {
+ for(int j = 0; j < unsorted[i]; j++) {
grid[count[max - k - 1]++][k] = '*';
k++;
}
diff --git a/src/main/java/com/thealgorithms/sorts/CircleSort.java b/src/main/java/com/thealgorithms/sorts/CircleSort.java
index 2ad09d15bf8a..3d013c88e1b7 100644
--- a/src/main/java/com/thealgorithms/sorts/CircleSort.java
+++ b/src/main/java/com/thealgorithms/sorts/CircleSort.java
@@ -24,7 +24,7 @@ private > Boolean doSort(
int left,
int right
) {
- Boolean swapped = false;
+ boolean swapped = false;
if (left == right) {
return false;
diff --git a/src/main/java/com/thealgorithms/sorts/CombSort.java b/src/main/java/com/thealgorithms/sorts/CombSort.java
index 78951fb3c916..2341ac652e83 100644
--- a/src/main/java/com/thealgorithms/sorts/CombSort.java
+++ b/src/main/java/com/thealgorithms/sorts/CombSort.java
@@ -23,7 +23,7 @@ class CombSort implements SortAlgorithm {
private int nextGap(int gap) {
// Shrink gap by Shrink factor
gap = (gap * 10) / 13;
- return (gap < 1) ? 1 : gap;
+ return Math.max(gap, 1);
}
/**
diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
index 57f1d9be3dde..902507abc419 100644
--- a/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
+++ b/src/main/java/com/thealgorithms/sorts/MergeSortRecursive.java
@@ -13,8 +13,7 @@ public MergeSortRecursive(List arr) {
}
public List mergeSort() {
- List arrSorted = merge(arr);
- return arrSorted;
+ return merge(arr);
}
private static List merge(List arr) {
diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java
index ca9d4c80c85e..78f233783ff0 100644
--- a/src/main/java/com/thealgorithms/sorts/TreeSort.java
+++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java
@@ -72,20 +72,20 @@ public static void main(String[] args) {
// ==== Integer Array =======
System.out.println("Testing for Integer Array....");
Integer[] a = { 3, -7, 45, 1, 343, -5, 2, 9 };
- System.out.print(String.format("%-10s", "unsorted: "));
+ System.out.printf("%-10s", "unsorted: ");
print(a);
a = treeSort.sort(a);
- System.out.print(String.format("%-10s", "sorted: "));
+ System.out.printf("%-10s", "sorted: ");
print(a);
System.out.println();
// ==== Integer List =======
System.out.println("Testing for Integer List....");
List intList = List.of(3, -7, 45, 1, 343, -5, 2, 9);
- System.out.print(String.format("%-10s", "unsorted: "));
+ System.out.printf("%-10s", "unsorted: ");
print(intList);
intList = treeSort.sort(intList);
- System.out.print(String.format("%-10s", "sorted: "));
+ System.out.printf("%-10s", "sorted: ");
print(intList);
System.out.println();
@@ -101,10 +101,10 @@ public static void main(String[] args) {
"apple",
"pineapple",
};
- System.out.print(String.format("%-10s", "unsorted: "));
+ System.out.printf("%-10s", "unsorted: ");
print(b);
b = treeSort.sort(b);
- System.out.print(String.format("%-10s", "sorted: "));
+ System.out.printf("%-10s", "sorted: ");
print(b);
System.out.println();
@@ -120,10 +120,10 @@ public static void main(String[] args) {
"apple",
"pineapple"
);
- System.out.print(String.format("%-10s", "unsorted: "));
+ System.out.printf("%-10s", "unsorted: ");
print(stringList);
stringList = treeSort.sort(stringList);
- System.out.print(String.format("%-10s", "sorted: "));
+ System.out.printf("%-10s", "sorted: ");
print(stringList);
}
}
diff --git a/src/main/java/com/thealgorithms/sorts/WiggleSort.java b/src/main/java/com/thealgorithms/sorts/WiggleSort.java
index c69fcdbe91ed..dc05de43cbdd 100644
--- a/src/main/java/com/thealgorithms/sorts/WiggleSort.java
+++ b/src/main/java/com/thealgorithms/sorts/WiggleSort.java
@@ -59,7 +59,7 @@ private > T[] wiggleSort(T[] sortThis) {
median =
select(
- Arrays.asList(sortThis),
+ Arrays.asList(sortThis),
(int) floor(sortThis.length / 2.0)
);
diff --git a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java
index e2c7d9078ab4..8ebff8576630 100644
--- a/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java
+++ b/src/main/java/com/thealgorithms/strings/LongestPalindromicSubstring.java
@@ -27,7 +27,7 @@ public String longestPalindrome(String s) {
String maxStr = "";
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j) {
- if (isValid(s, i, j) == true) {
+ if (isValid(s, i, j)) {
if (j - i + 1 > maxStr.length()) { // update maxStr
maxStr = s.substring(i, j + 1);
}
diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java
index a68a5fd3939c..0770f66c7313 100644
--- a/src/main/java/com/thealgorithms/strings/MyAtoi.java
+++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java
@@ -72,13 +72,8 @@ public static int myAtoi(String s) {
if (db1 > (2147483647)) {
return 2147483647;
}
- }else if (number.length() == 10 && negative) {
- double db1 = Double.parseDouble(number);
- if (db1 >= 2147483648d) {
- return -2147483648;
- }
}
-
+
if(negative){
return Integer.parseInt(number)*-1;
}
From d1601560032b75f347adf987417eda0fdc2d95f4 Mon Sep 17 00:00:00 2001
From: duyuanch <680888@gmail.com>
Date: Mon, 3 Apr 2023 22:39:17 +0800
Subject: [PATCH 0011/1457] Update AbsoluteMax (#4140)
---
.../com/thealgorithms/maths/AbsoluteMax.java | 32 ++++++++-----------
.../thealgorithms/maths/AbsoluteMaxTest.java | 9 ++----
2 files changed, 16 insertions(+), 25 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
index bb89fb238ac2..64338297e399 100644
--- a/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
+++ b/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
@@ -1,30 +1,24 @@
package com.thealgorithms.maths;
-import java.util.Arrays;
-
public class AbsoluteMax {
/**
- * Compares the numbers given as arguments to get the absolute max value.
+ * Finds the absolute maximum value among the given numbers.
*
- * @param numbers The numbers to compare
- * @return The absolute max value
+ * @param numbers The numbers to compare.
+ * @return The absolute maximum value.
+ * @throws IllegalArgumentException If the input array is empty or null.
*/
public static int getMaxValue(int... numbers) {
- if (numbers.length == 0) {
- throw new IllegalArgumentException("Numbers array cannot be empty");
+ if (numbers == null || numbers.length == 0) {
+ throw new IllegalArgumentException("Numbers array cannot be empty or null");
}
-
- var absMaxWrapper = new Object() {
- int value = numbers[0];
- };
-
- Arrays
- .stream(numbers)
- .skip(1)
- .filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
- .forEach(number -> absMaxWrapper.value = number);
-
- return absMaxWrapper.value;
+ int absMax = numbers[0];
+ for (int i = 1; i < numbers.length; i++) {
+ if (Math.abs(numbers[i]) > Math.abs(absMax)) {
+ absMax = numbers[i];
+ }
+ }
+ return absMax;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
index 78a8c09369e3..85ffb91e27f4 100644
--- a/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
+++ b/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java
@@ -10,15 +10,12 @@ public class AbsoluteMaxTest {
@Test
void testGetMaxValue() {
assertEquals(16, AbsoluteMax.getMaxValue(-2, 0, 16));
- assertEquals(-10, AbsoluteMax.getMaxValue(3, -10, -2));
+ assertEquals(-22, AbsoluteMax.getMaxValue(-3, -10, -22));
+ assertEquals(-888, AbsoluteMax.getMaxValue(-888));
}
@Test
void testGetMaxValueWithNoArguments() {
- Exception exception = assertThrows(
- IllegalArgumentException.class,
- () -> AbsoluteMax.getMaxValue()
- );
- assertEquals("Numbers array cannot be empty", exception.getMessage());
+ assertThrows(IllegalArgumentException.class, AbsoluteMax::getMaxValue);
}
}
From 8798e042a899223ee29bae3acd20253e836fcd94 Mon Sep 17 00:00:00 2001
From: Sukruti Mallesh
Date: Mon, 3 Apr 2023 07:42:50 -0700
Subject: [PATCH 0012/1457] Refactor BinaryToDecimal class (#4135)
---
.../conversions/BinaryToDecimal.java | 8 ++++----
.../conversions/BinaryToDecimalTest.java | 17 ++++++++++++++++-
2 files changed, 20 insertions(+), 5 deletions(-)
diff --git a/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java b/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
index de06ca6b3140..b0ab817d06b2 100644
--- a/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
@@ -7,12 +7,12 @@
*/
class BinaryToDecimal {
- public static int binaryToDecimal(int binNum) {
- int binCopy, d, s = 0, power = 0;
+ public static long binaryToDecimal(long binNum) {
+ long binCopy, d, s = 0, power = 0;
binCopy = binNum;
while (binCopy != 0) {
d = binCopy % 10;
- s += d * (int) Math.pow(2, power++);
+ s += d * (long) Math.pow(2, power++);
binCopy /= 10;
}
return s;
@@ -26,7 +26,7 @@ public static int binaryToDecimal(int binNum) {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Binary number: ");
- System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextInt()));
+ System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));
sc.close();
}
}
diff --git a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java
index d44c30d19449..336aeef3ebbe 100644
--- a/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java
+++ b/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java
@@ -7,12 +7,27 @@
public class BinaryToDecimalTest {
@Test
+ // Test converting binary to decimal
public void testBinaryToDecimal() {
- //zeros at the starting should be removed
+ // zeros at the starting should be removed
assertEquals(0, BinaryToDecimal.binaryToDecimal(0));
assertEquals(1, BinaryToDecimal.binaryToDecimal(1));
assertEquals(5, BinaryToDecimal.binaryToDecimal(101));
assertEquals(63, BinaryToDecimal.binaryToDecimal(111111));
assertEquals(512, BinaryToDecimal.binaryToDecimal(1000000000));
}
+
+ @Test
+ // Test converting negative binary numbers
+ public void testNegativeBinaryToDecimal() {
+ assertEquals(-1, BinaryToDecimal.binaryToDecimal(-1));
+ assertEquals(-42, BinaryToDecimal.binaryToDecimal(-101010));
+ }
+
+ @Test
+ // Test converting binary numbers with large values
+ public void testLargeBinaryToDecimal() {
+ assertEquals(262144L, BinaryToDecimal.binaryToDecimal(1000000000000000000L));
+ assertEquals(524287L, BinaryToDecimal.binaryToDecimal(1111111111111111111L));
+ }
}
\ No newline at end of file
From f35e9a7d81b027ef6efb195efdd6e511e13bc5a4 Mon Sep 17 00:00:00 2001
From: Rohan Anand <96521078+rohan472000@users.noreply.github.com>
Date: Fri, 7 Apr 2023 18:20:43 +0530
Subject: [PATCH 0013/1457] Update SieveOfEratosthenes.java (#4149)
---
.../others/SieveOfEratosthenes.java | 32 +++----------------
1 file changed, 5 insertions(+), 27 deletions(-)
diff --git a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java
index a62cbbda4df1..3ffc38062339 100644
--- a/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java
+++ b/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java
@@ -4,45 +4,24 @@
/**
* Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers
- * up to any given limit. It does so by iteratively marking as composite (i.e.,
- * not prime) the multiples of each prime, starting with the first prime number,
- * 2. The multiples of a given prime are generated as a sequence of numbers
- * starting from that prime, with constant difference between them that is equal
- * to that prime. This is the sieve's key distinction from using trial division
- * to sequentially test each candidate number for divisibility by each prime.
- * Once all the multiples of each discovered prime have been marked as
- * composites, the remaining unmarked numbers are primes.
- *
- * Poetry about Sieve of Eratosthenes:
- *
- * Sift the Two's and Sift the Three's:
- *
- * The Sieve of Eratosthenes.
- *
- * When the multiples sublime,
- *
- * The numbers that remain are Prime.
+ * up to any given limit.
*
* @see Wiki
*/
public class SieveOfEratosthenes {
/**
- * @param n The number till which we have to check for prime Prints all the
- * prime numbers till n. Should be more than 1.
- * @return array of all prime numbers between 0 to n
+ * Finds all prime numbers till n.
+ *
+ * @param n The number till which we have to check for primes. Should be more than 1.
+ * @return Array of all prime numbers between 0 to n.
*/
public static int[] findPrimesTill(int n) {
- // Create array where index is number and value is flag - is that number a prime or not.
- // size of array is n + 1 cause in Java array indexes starts with 0
Type[] numbers = new Type[n + 1];
-
- // Start with assumption that all numbers except 0 and 1 are primes.
Arrays.fill(numbers, Type.PRIME);
numbers[0] = numbers[1] = Type.NOT_PRIME;
double cap = Math.sqrt(n);
- // Main algorithm: mark all numbers which are multiples of some other values as not prime
for (int i = 2; i <= cap; i++) {
if (numbers[i] == Type.PRIME) {
for (int j = 2; i * j <= n; j++) {
@@ -51,7 +30,6 @@ public static int[] findPrimesTill(int n) {
}
}
- //Write all primes to result array
int primesCount = (int) Arrays
.stream(numbers)
.filter(element -> element == Type.PRIME)
From 7779c18ef612f50b8389382e9e43ff7e159dc21e Mon Sep 17 00:00:00 2001
From: Volodymyr Labliuk <50242030+n1ceFella@users.noreply.github.com>
Date: Sat, 8 Apr 2023 12:56:07 -0400
Subject: [PATCH 0014/1457] Add More Tests (#4148)
---
.../thealgorithms/maths/LeonardoNumber.java | 17 +++++----
.../com/thealgorithms/maths/LucasSeries.java | 16 ++-------
.../java/com/thealgorithms/maths/Median.java | 11 +-----
.../maths/LeonardoNumberTest.java | 28 +++++++++++++++
.../thealgorithms/maths/LucasSeriesTest.java | 27 ++++++++++++++
.../com/thealgorithms/maths/MedianTest.java | 36 +++++++++++++++++++
6 files changed, 105 insertions(+), 30 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java
create mode 100644 src/test/java/com/thealgorithms/maths/LucasSeriesTest.java
create mode 100644 src/test/java/com/thealgorithms/maths/MedianTest.java
diff --git a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java
index 8af36e803c13..7b9620a46ccb 100644
--- a/src/main/java/com/thealgorithms/maths/LeonardoNumber.java
+++ b/src/main/java/com/thealgorithms/maths/LeonardoNumber.java
@@ -1,20 +1,23 @@
package com.thealgorithms.maths;
+ /**
+ * https://en.wikipedia.org/wiki/Leonardo_number
+ */
public class LeonardoNumber {
+ /**
+ * Calculate nth Leonardo Number (1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, ...)
+ *
+ * @param n the index of Leonardo Number to calculate
+ * @return nth number of Leonardo sequences
+ */
public static int leonardoNumber(int n) {
if (n < 0) {
- return 0;
+ throw new ArithmeticException();
}
if (n == 0 || n == 1) {
return 1;
}
return (leonardoNumber(n - 1) + leonardoNumber(n - 2) + 1);
}
-
- public static void main(String args[]) {
- for (int i = 0; i < 20; i++) {
- System.out.print(leonardoNumber(i) + " ");
- }
- }
}
diff --git a/src/main/java/com/thealgorithms/maths/LucasSeries.java b/src/main/java/com/thealgorithms/maths/LucasSeries.java
index e1d9c3361ba4..59c9a9f3f2e4 100644
--- a/src/main/java/com/thealgorithms/maths/LucasSeries.java
+++ b/src/main/java/com/thealgorithms/maths/LucasSeries.java
@@ -5,22 +5,12 @@
*/
public class LucasSeries {
- public static void main(String[] args) {
- assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
- assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1;
- assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3;
- assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4;
- assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
- assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
- assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
- }
-
/**
- * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
+ * Calculate nth number of Lucas Series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
* 123, ....) using recursion
*
* @param n nth
- * @return nth number of lucas series
+ * @return nth number of Lucas Series
*/
public static int lucasSeries(int n) {
return n == 1
@@ -29,7 +19,7 @@ public static int lucasSeries(int n) {
}
/**
- * Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
+ * Calculate nth number of Lucas Series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76,
* 123, ....) using iteration
*
* @param n nth
diff --git a/src/main/java/com/thealgorithms/maths/Median.java b/src/main/java/com/thealgorithms/maths/Median.java
index 3bc8bae26c69..44f94ad6bb9c 100644
--- a/src/main/java/com/thealgorithms/maths/Median.java
+++ b/src/main/java/com/thealgorithms/maths/Median.java
@@ -7,18 +7,9 @@
*/
public class Median {
- public static void main(String[] args) {
- assert median(new int[] { 0 }) == 0;
- assert median(new int[] { 1, 2 }) == 1.5;
- assert median(new int[] { 4, 1, 3, 2 }) == 2.5;
- assert median(new int[] { 1, 3, 3, 6, 7, 8, 9 }) == 6;
- assert median(new int[] { 1, 2, 3, 4, 5, 6, 8, 9 }) == 4.5;
- }
-
/**
* Calculate average median
- *
- * @param values number series
+ * @param values sorted numbers to find median of
* @return median of given {@code values}
*/
public static double median(int[] values) {
diff --git a/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java
new file mode 100644
index 000000000000..7af452e1b4c7
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java
@@ -0,0 +1,28 @@
+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 LeonardoNumberTest {
+ @Test
+ void leonardoNumberNegative() {
+ assertThrows(ArithmeticException.class, ()-> LeonardoNumber.leonardoNumber(-1));
+ }
+ @Test
+ void leonardoNumberZero() {
+ assertEquals(1, LeonardoNumber.leonardoNumber(0));
+ }
+ @Test
+ void leonardoNumberOne() {
+ assertEquals(1, LeonardoNumber.leonardoNumber(1));
+ }
+ @Test
+ void leonardoNumberFive() {
+ assertEquals(15, LeonardoNumber.leonardoNumber(5));
+ }
+ @Test
+ void leonardoNumberTwenty() {
+ assertEquals(21891 , LeonardoNumber.leonardoNumber(20));
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java
new file mode 100644
index 000000000000..e5ac62240989
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java
@@ -0,0 +1,27 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class LucasSeriesTest {
+ @Test
+ void lucasSeriesTwo() {
+ assertEquals(2, LucasSeries.lucasSeries(1));
+ assertEquals(2, LucasSeries.lucasSeriesIteration(1));
+ }
+ @Test
+ void lucasSeriesOne() {
+ assertEquals(1, LucasSeries.lucasSeries(2));
+ assertEquals(1, LucasSeries.lucasSeriesIteration(2));
+ }
+ @Test
+ void lucasSeriesSeven() {
+ assertEquals(7, LucasSeries.lucasSeries(5));
+ assertEquals(7, LucasSeries.lucasSeriesIteration(5));
+ }
+ @Test
+ void lucasSeriesEleven() {
+ assertEquals(123, LucasSeries.lucasSeries(11));
+ assertEquals(123, LucasSeries.lucasSeriesIteration(11));
+ }
+}
diff --git a/src/test/java/com/thealgorithms/maths/MedianTest.java b/src/test/java/com/thealgorithms/maths/MedianTest.java
new file mode 100644
index 000000000000..f3825b7f12b7
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/MedianTest.java
@@ -0,0 +1,36 @@
+package com.thealgorithms.maths;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class MedianTest {
+ @Test
+ void medianSingleValue() {
+ int[] arr = {0};
+ assertEquals(0, Median.median(arr));
+ }
+
+ @Test
+ void medianTwoValues() {
+ int[] arr = {1, 2};
+ assertEquals(1.5, Median.median(arr));
+ }
+
+ @Test
+ void medianThreeValues() {
+ int[] arr = {1, 2, 3};
+ assertEquals(2, Median.median(arr));
+ }
+
+ @Test
+ void medianDecimalValueReturn() {
+ int[] arr = {1, 2, 3, 4, 5, 6, 8, 9};
+ assertEquals(4.5, Median.median(arr));
+ }
+
+ @Test
+ void medianNegativeValues() {
+ int[] arr = {-27, -16, -7, -4, -2, -1};
+ assertEquals(-5.5, Median.median(arr));
+ }
+}
From 181906d5f72c92fcb003f0363893eb26ffafa1af Mon Sep 17 00:00:00 2001
From: Ishan Makadia <45734338+intrepid-ishan@users.noreply.github.com>
Date: Wed, 12 Apr 2023 12:18:49 -0300
Subject: [PATCH 0015/1457] Refactor Code (MemoryManagementAlgorithms): Pull Up
Variable (#4145)
---
.../others/MemoryManagementAlgorithms.java | 24 +++++++++----------
1 file changed, 12 insertions(+), 12 deletions(-)
diff --git a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
index 3ab711d27dc6..576d83a9789f 100644
--- a/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
+++ b/src/main/java/com/thealgorithms/others/MemoryManagementAlgorithms.java
@@ -25,6 +25,18 @@ public abstract ArrayList fitProcess(
int[] sizeOfBlocks,
int[] sizeOfProcesses
);
+
+ /**
+ * A constant value used to indicate that an allocation has not been made.
+ * This value is used as a sentinel value to represent that no allocation has been made
+ * when allocating space in an array or other data structure.
+ * The value is -255 and is marked as protected and final to ensure that it cannot be modified
+ * from outside the class and that its value remains consistent throughout the program execution.
+ *
+ * @author: Ishan Makadia (github.com/intrepid-ishan)
+ * @version: April 06, 2023
+ */
+ protected static final int NO_ALLOCATION = -255;
}
/**
@@ -32,9 +44,6 @@ public abstract ArrayList fitProcess(
*/
class BestFitCPU extends MemoryManagementAlgorithms {
- private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
-
- // it means that it has not been actually allocated.
/**
* Method to find the maximum valued element of an array filled with
@@ -115,10 +124,6 @@ public ArrayList fitProcess(
*/
class WorstFitCPU extends MemoryManagementAlgorithms {
- private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
-
- // it means that it has not been actually allocated.
-
/**
* Method to find the index of the memory block that is going to fit the
* given process based on the worst fit algorithm.
@@ -179,9 +184,6 @@ public ArrayList fitProcess(
*/
class FirstFitCPU extends MemoryManagementAlgorithms {
- private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
-
- // it means that it has not been actually allocated.
/**
* Method to find the index of the memory block that is going to fit the
@@ -237,8 +239,6 @@ public ArrayList fitProcess(
*/
class NextFit extends MemoryManagementAlgorithms {
- private static final int NO_ALLOCATION = -255; // if a process has been allocated in position -255,
- // it means that it has not been actually allocated.
private int counter = 0; // variable that keeps the position of the last registration into the memory
/**
From 8259f0e9cf086fd8632b86eb3417a3753727712d Mon Sep 17 00:00:00 2001
From: Rohan Anand <96521078+rohan472000@users.noreply.github.com>
Date: Thu, 13 Apr 2023 17:58:36 +0530
Subject: [PATCH 0016/1457] Add Majority Element (#4131)
---
.../hashmap/hashing/MajorityElement.java | 34 +++++++++++++
.../hashmap/hashing/MajorityElementTest.java | 49 +++++++++++++++++++
2 files changed, 83 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
new file mode 100644
index 000000000000..5231431e9bf7
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java
@@ -0,0 +1,34 @@
+package com.thealgorithms.datastructures.hashmap.hashing;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+/*
+This class finds the majority element(s) in an array of integers.
+A majority element is an element that appears more than or equal to n/2 times, where n is the length of the array.
+*/
+public class MajorityElement {
+ /*
+ This method returns the majority element(s) in the given array of integers.
+ @param nums: an array of integers
+ @return a list of majority elements
+ */
+ public static List majority(int[] nums){
+ HashMap numToCount = new HashMap<>();
+ int n = nums.length;
+ for (int i = 0; i < n; i++) {
+ if (numToCount.containsKey(nums[i])){
+ numToCount.put(nums[i],numToCount.get(nums[i])+1);
+ } else {
+ numToCount.put(nums[i],1);
+ }
+ }
+ List majorityElements = new ArrayList<>();
+ for (int key: numToCount.keySet()) {
+ if (numToCount.get(key) >= n/2){
+ majorityElements.add(key);
+ }
+ }
+ return majorityElements;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java
new file mode 100644
index 000000000000..45c7b6c5d19d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java
@@ -0,0 +1,49 @@
+package com.thealgorithms.datastructures.hashmap.hashing;
+
+import com.thealgorithms.datastructures.hashmap.hashing.MajorityElement;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.Collections;
+import java.util.List;
+
+import java.util.ArrayList;
+
+public class MajorityElementTest{
+ @Test
+ void testMajorityWithSingleMajorityElement() {
+ int[] nums = {1, 2, 3, 9, 9, 6, 7, 8, 9, 9, 9, 9};
+ List expected = new ArrayList<>();
+ expected.add(9);
+ List actual = MajorityElement.majority(nums);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void testMajorityWithMultipleMajorityElements() {
+ int[] nums = {1, 2, 3, 3, 4, 4, 4, 4};
+ List expected = new ArrayList<>();
+ expected.add(4);
+ List actual = MajorityElement.majority(nums);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void testMajorityWithNoMajorityElement() {
+ int[] nums = {1, 2, 4, 4, 5, 4};
+ List expected = new ArrayList<>();
+ expected.add(4);
+ List actual = MajorityElement.majority(nums);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void testMajorityWithEmptyArray() {
+ int[] nums = {};
+ List expected = Collections.emptyList();
+ List actual = MajorityElement.majority(nums);
+ assertEquals(expected, actual);
+ }
+}
From d241fafd6433948e93bced7398c0d05b1c3ffdf7 Mon Sep 17 00:00:00 2001
From: Andrii Siriak
Date: Fri, 14 Apr 2023 11:33:22 +0300
Subject: [PATCH 0017/1457] Remove blinking test for BufferedReader (#4153)
---
DIRECTORY.md | 74 ++++++++++++++++++-
.../thealgorithms/io/BufferedReaderTest.java | 33 +--------
2 files changed, 71 insertions(+), 36 deletions(-)
diff --git a/DIRECTORY.md b/DIRECTORY.md
index d4dc56ebb7df..fb49d163e745 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -7,6 +7,8 @@
* audiofilters
* [IIRFilter](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java)
* backtracking
+ * [AllPathsFromSourceToTarget](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java)
+ * [ArrayCombination](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/backtracking/ArrayCombination.java)
* [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)
@@ -82,26 +84,30 @@
* [Graphs](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java)
* [HamiltonianCycle](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java)
* [KahnsAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java)
+ * [Kosaraju](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java)
* [Kruskal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java)
* [MatrixGraphs](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java)
* [PrimMST](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java)
+ * [TarjansAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java)
* hashmap
* hashing
* [GenericHashMapUsingArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java)
* [GenericHashMapUsingArrayList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java)
* [HashMap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java)
* [HashMapCuckooHashing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java)
- * [HashMapLinearProbing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapLinearProbing.java)
* [Intersection](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java)
+ * [LinearProbingHashMap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java)
* [Main](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Main.java)
* [MainCuckooHashing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java)
- * [MainLinearProbing](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainLinearProbing.java)
+ * [MajorityElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java)
+ * [Map](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java)
* heaps
* [EmptyHeapException](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/EmptyHeapException.java)
* [FibonacciHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java)
* [GenericHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java)
* [Heap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java)
* [HeapElement](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java)
+ * [LeftistHeap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java)
* [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)
@@ -155,20 +161,25 @@
* [CreateBSTFromSortedArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java)
* [FenwickTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java)
* [GenericTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java)
+ * [InorderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java)
* [KDTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java)
* [LazySegmentTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java)
* [LCA](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LCA.java)
* [LevelOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java)
- * [LevelOrderTraversalQueue](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalQueue.java)
+ * [LevelOrderTraversalHelper](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java)
* [nearestRightKey](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java)
+ * [PostOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java)
+ * [PreOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java)
* [PrintTopViewofTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java)
* [RedBlackBST](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java)
+ * [SameTreesCheck](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java)
* [SegmentTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java)
* [TreeRandomNode](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java)
* [TreeTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java)
* [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java)
* [ValidBSTOrNot](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java)
* [VerticalOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java)
+ * [ZigzagTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java)
* devutils
* entities
* [ProcessDetails](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java)
@@ -214,6 +225,7 @@
* [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)
+ * [OptimalJobScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.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)
@@ -223,6 +235,10 @@
* [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)
+ * geometry
+ * [GrahamScan](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/geometry/GrahamScan.java)
+ * io
+ * [BufferedReader](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/io/BufferedReader.java)
* maths
* [AbsoluteMax](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/AbsoluteMax.java)
* [AbsoluteMin](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/AbsoluteMin.java)
@@ -260,6 +276,7 @@
* [FindMin](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindMin.java)
* [FindMinRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FindMinRecursion.java)
* [Floor](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/Floor.java)
+ * [FrizzyNumber](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/FrizzyNumber.java)
* [Gaussian](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/Gaussian.java)
* [GCD](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/GCD.java)
* [GCDRecursion](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/maths/GCDRecursion.java)
@@ -344,6 +361,7 @@
* [BrianKernighanAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java)
* cn
* [HammingDistance](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/cn/HammingDistance.java)
+ * [Conway](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Conway.java)
* [CountChar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountChar.java)
* [countSetBits](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/countSetBits.java)
* [CountWords](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/CountWords.java)
@@ -372,6 +390,7 @@
* [PageRank](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PageRank.java)
* [PasswordGen](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PasswordGen.java)
* [PerlinNoise](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PerlinNoise.java)
+ * [PrintAMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/PrintAMatrixInSpiralOrder.java)
* [QueueUsingTwoStacks](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java)
* [RabinKarp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RabinKarp.java)
* [RemoveDuplicateFromString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RemoveDuplicateFromString.java)
@@ -380,7 +399,6 @@
* [RootPrecision](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RootPrecision.java)
* [RotateMatriceBy90Degree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java)
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/SieveOfEratosthenes.java)
- * [SJF](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/SJF.java)
* [SkylineProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/SkylineProblem.java)
* [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/StackPostfixNotation.java)
* [StringMatchFiniteAutomata](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java)
@@ -392,6 +410,7 @@
* [Verhoeff](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Verhoeff.java)
* scheduling
* [FCFSScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java)
+ * [SJFScheduling](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java)
* searches
* [BinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/BinarySearch.java)
* [BinarySearch2dArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java)
@@ -415,6 +434,8 @@
* [RabinKarpAlgorithm](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java)
* [RowColumnWiseSorted2dArrayBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java)
* [SaddlebackSearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java)
+ * [SearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java)
+ * [sortOrderAgnosticBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java)
* [SquareRootBinarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java)
* [TernarySearch](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/TernarySearch.java)
* [UnionFind](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/UnionFind.java)
@@ -438,6 +459,7 @@
* [GnomeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/GnomeSort.java)
* [HeapSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/HeapSort.java)
* [InsertionSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/InsertionSort.java)
+ * [IntrospectiveSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/IntrospectiveSort.java)
* [LinkListSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/LinkListSort.java)
* [MergeSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/MergeSort.java)
* [MergeSortNoExtraSpace](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java)
@@ -481,13 +503,19 @@
* [ReverseString](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ReverseString.java)
* [ReverseStringRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ReverseStringRecursive.java)
* [Rotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Rotation.java)
+ * [StringCompression](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/StringCompression.java)
* [Upper](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/Upper.java)
* [ValidParentheses](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/ValidParentheses.java)
* [WordLadder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/WordLadder.java)
* zigZagPattern
* [zigZagPattern](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/strings/zigZagPattern/zigZagPattern.java)
* test
+ * java
+ * com
+ * thealgorithms
* backtracking
+ * [AllPathsFromSourceToTargetTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java)
+ * [ArrayCombinationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/ArrayCombinationTest.java)
* [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)
* [MazeRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java)
@@ -501,6 +529,7 @@
* [PolybiusTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java)
* [RSATest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/RSATest.java)
* [SimpleSubCipherTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java)
+ * [SimpleSubstitutionCipherTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/SimpleSubstitutionCipherTest.java)
* [VigenereTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/VigenereTest.java)
* conversions
* [BinaryToDecimalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java)
@@ -525,23 +554,40 @@
* [MRUCacheTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/caches/MRUCacheTest.java)
* graphs
* [HamiltonianCycleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/HamiltonianCycleTest.java)
+ * [KosarajuTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/KosarajuTest.java)
+ * [TarjansAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithmTest.java)
* hashmap
* hashing
* [GenericHashMapUsingArrayListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayListTest.java)
* [GenericHashMapUsingArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayTest.java)
+ * [LinearProbingHashMapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMapTest.java)
+ * [MajorityElementTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElementTest.java)
+ * [MapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/MapTest.java)
* [HashMapCuckooHashingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/hashmap/HashMapCuckooHashingTest.java)
* heaps
* [FibonacciHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java)
+ * [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java)
* lists
+ * [SinglyLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java)
* [SkipListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/SkipListTest.java)
* queues
+ * [LinkedQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/LinkedQueueTest.java)
* [PriorityQueuesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java)
* trees
+ * [BinaryTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java)
* [CeilInBinarySearchTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java)
* [CheckTreeIsSymmetricTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java)
+ * [InorderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java)
* [KDTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java)
* [LazySegmentTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/LazySegmentTreeTest.java)
+ * [LevelOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalTest.java)
+ * [PostOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/PostOrderTraversalTest.java)
+ * [PreOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java)
+ * [SameTreesCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java)
* [TreeTestUtils](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java)
+ * [ValidBSTOrNotTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ValidBSTOrNotTest.java)
+ * [VerticalOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java)
+ * [ZigzagTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java)
* divideandconquer
* [BinaryExponentiationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java)
* [StrassenMatrixMultiplicationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java)
@@ -549,7 +595,13 @@
* [CatalanNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java)
* [EggDroppingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java)
* [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java)
+ * [LevenshteinDistanceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java)
+ * [OptimalJobSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/OptimalJobSchedulingTest.java)
* [SubsetCountTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/SubsetCountTest.java)
+ * geometry
+ * [GrahamScanTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/geometry/GrahamScanTest.java)
+ * io
+ * [BufferedReaderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/io/BufferedReaderTest.java)
* maths
* [AbsoluteMaxTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/AbsoluteMaxTest.java)
* [AbsoluteMinTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/AbsoluteMinTest.java)
@@ -574,6 +626,7 @@
* [FFTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FFTTest.java)
* [FindMaxTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindMaxTest.java)
* [FindMinTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FindMinTest.java)
+ * [FrizzyNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/FrizzyNumberTest.java)
* [GaussianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GaussianTest.java)
* [GCDTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/GCDTest.java)
* [HarshadNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/HarshadNumberTest.java)
@@ -581,8 +634,11 @@
* [JosephusProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/JosephusProblemTest.java)
* [KaprekarNumbersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/KaprekarNumbersTest.java)
* [LeastCommonMultipleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LeastCommonMultipleTest.java)
+ * [LeonardoNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LeonardoNumberTest.java)
* [LiouvilleLambdaFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LiouvilleLambdaFunctionTest.java)
* [LongDivisionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LongDivisionTest.java)
+ * [LucasSeriesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/LucasSeriesTest.java)
+ * [MedianTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MedianTest.java)
* [MobiusFunctionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/MobiusFunctionTest.java)
* [PascalTriangleTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PascalTriangleTest.java)
* [PerfectCubeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/maths/PerfectCubeTest.java)
@@ -610,20 +666,24 @@
* [CalculateMaxOfMinTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java)
* cn
* [HammingDistanceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java)
+ * [ConwayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/ConwayTest.java)
* [CountCharTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountCharTest.java)
* [CountFriendsPairingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java)
* [countSetBitsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/countSetBitsTest.java)
* [CRC16Test](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRC16Test.java)
+ * [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.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)
* [LinkListSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkListSortTest.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)
* [PasswordGenTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/PasswordGenTest.java)
+ * [TestPrintMatrixInSpiralOrder](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/TestPrintMatrixInSpiralOrder.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)
* scheduling
* [FCFSSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/FCFSSchedulingTest.java)
+ * [SJFSchedulingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/scheduling/SJFSchedulingTest.java)
* searches
* [BinarySearch2dArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java)
* [BreadthFirstSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java)
@@ -633,6 +693,8 @@
* [QuickSelectTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/QuickSelectTest.java)
* [RabinKarpAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RabinKarpAlgorithmTest.java)
* [RowColumnWiseSorted2dArrayBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java)
+ * [sortOrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java)
+ * [TestSearchInARowAndColWiseSortedMatrix](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/TestSearchInARowAndColWiseSortedMatrix.java)
* sorts
* [BeadSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BeadSortTest.java)
* [BinaryInsertionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BinaryInsertionSortTest.java)
@@ -645,6 +707,7 @@
* [DutchNationalFlagSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java)
* [HeapSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/HeapSortTest.java)
* [InsertionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/InsertionSortTest.java)
+ * [IntrospectiveSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/IntrospectiveSortTest.java)
* [MergeSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortRecursiveTest.java)
* [MergeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/MergeSortTest.java)
* [OddEvenSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java)
@@ -653,11 +716,13 @@
* [ShellSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/ShellSortTest.java)
* [SimpleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SimpleSortTest.java)
* [SlowSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SlowSortTest.java)
+ * [SortingAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortingAlgorithmTest.java)
* [SortUtilsRandomGeneratorTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortUtilsRandomGeneratorTest.java)
* [SortUtilsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SortUtilsTest.java)
* [StrandSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/StrandSortTest.java)
* [TimSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TimSortTest.java)
* [TopologicalSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TopologicalSortTest.java)
+ * [TreeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/TreeSortTest.java)
* [WiggleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/WiggleSortTest.java)
* strings
* [AlphabeticalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/AlphabeticalTest.java)
@@ -676,6 +741,7 @@
* [ReverseStringRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ReverseStringRecursiveTest.java)
* [ReverseStringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ReverseStringTest.java)
* [RotationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/RotationTest.java)
+ * [StringCompressionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/StringCompressionTest.java)
* [UpperTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/UpperTest.java)
* [ValidParenthesesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/ValidParenthesesTest.java)
* [WordLadderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/WordLadderTest.java)
diff --git a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
index a183881743f8..5d0c3b06c369 100644
--- a/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
+++ b/src/test/java/com/thealgorithms/io/BufferedReaderTest.java
@@ -99,35 +99,4 @@ public void testBlockPractical() throws IOException {
throw new IOException("Something not right");
}
}
-
- @Test
- public void randomTest() throws IOException {
- Random random = new Random();
-
- int len = random.nextInt(9999);
- int bound = 256;
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream(len);
- while (len-- > 0)
- stream.write(random.nextInt(bound));
-
- byte[] bytes = stream.toByteArray();
- ByteArrayInputStream comparer = new ByteArrayInputStream(bytes);
-
- int blockSize = random.nextInt(7) + 5;
- BufferedReader reader = new BufferedReader(
- new ByteArrayInputStream(bytes), blockSize);
-
- for (int i = 0; i < 50; i++) {
- if ((i & 1) == 0) {
- assertEquals(comparer.read(), reader.read());
- continue;
- }
- byte[] block = new byte[blockSize];
- comparer.read(block);
- byte[] read = reader.readBlock();
-
- assertArrayEquals(block, read);
- }
- }
-}
\ No newline at end of file
+}
From 0c618b5ee806e96b2cae92a8f0b9b5f4dc76aa0b Mon Sep 17 00:00:00 2001
From: Ishan Makadia <45734338+intrepid-ishan@users.noreply.github.com>
Date: Fri, 14 Apr 2023 05:34:47 -0300
Subject: [PATCH 0018/1457] Refactoring (#4146)
---
.../graphs/HamiltonianCycle.java | 3 +-
.../trees/CheckTreeIsSymmetric.java | 6 ++-
.../KnapsackMemoization.java | 39 +++++++++----------
3 files changed, 26 insertions(+), 22 deletions(-)
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
index 68bc5074ca9e..1430f1a246dd 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -47,7 +47,8 @@ public int[] findHamiltonianCycle(int[][] graph) {
* @returns true if path is found false otherwise
*/
public boolean isPathFound(int vertex) {
- if (this.graph[vertex][0] == 1 && this.pathCount == this.V) {
+ boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
+ if (isLastVertexConnectedToStart) {
return true;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
index 713dc083a93a..0df93cefb9e3 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
@@ -44,10 +44,14 @@ private static boolean isSymmetric(Node leftSubtreeRoot, Node rightSubtreRoot) {
return true;
}
- if (leftSubtreeRoot == null || rightSubtreRoot == null || leftSubtreeRoot.data != rightSubtreRoot.data) {
+ if (isInvalidSubtree(leftSubtreeRoot, rightSubtreRoot)) {
return false;
}
return isSymmetric(leftSubtreeRoot.right, rightSubtreRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreRoot.right);
}
+
+ private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) {
+ return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.data;
+ }
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
index e3cc7cefabf5..81888fda5296 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
@@ -9,44 +9,43 @@
*/
public class KnapsackMemoization {
- int knapSack(int W, int wt[], int val[], int N) {
+ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
// Declare the table dynamically
- int dp[][] = new int[N + 1][W + 1];
+ int[][] dpTable = new int[numOfItems + 1][capacity + 1];
- // Loop to initially filled the
- // table with -1
- for (int i = 0; i < N + 1; i++) {
- for (int j = 0; j < W + 1; j++) {
- dp[i][j] = -1;
+ // Loop to initially fill the table with -1
+ for (int i = 0; i < numOfItems + 1; i++) {
+ for (int j = 0; j < capacity + 1; j++) {
+ dpTable[i][j] = -1;
}
}
- return knapSackRec(W, wt, val, N, dp);
+ return solveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable);
}
- // Returns the value of maximum profit using Recursive approach
- int knapSackRec(int W, int wt[],
- int val[], int n,
- int[][] dp) {
+ // Returns the value of maximum profit using recursive approach
+ int solveKnapsackRecursive(int capacity, int[] weights,
+ int[] profits, int numOfItems,
+ int[][] dpTable) {
// Base condition
- if (n == 0 || W == 0) {
+ if (numOfItems == 0 || capacity == 0) {
return 0;
}
- if (dp[n][W] != -1) {
- return dp[n][W];
+ if (dpTable[numOfItems][capacity] != -1) {
+ return dpTable[numOfItems][capacity];
}
- if (wt[n - 1] > W) {
+ if (weights[numOfItems - 1] > capacity) {
// Store the value of function call stack in table
- dp[n][W] = knapSackRec(W, wt, val, n - 1, dp);
- return dp[n][W];
+ dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable);
+ return dpTable[numOfItems][capacity];
} else {
// Return value of table after storing
- return dp[n][W] = Math.max((val[n - 1] + knapSackRec(W - wt[n - 1], wt, val, n - 1, dp)),
- knapSackRec(W, wt, val, n - 1, dp));
+ return dpTable[numOfItems][capacity] = Math.max((profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable)),
+ solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable));
}
}
}
From 1ce907625b65abe27fef450df9c645b5d71c383d Mon Sep 17 00:00:00 2001
From: Akshith121 <117920896+Akshith121@users.noreply.github.com>
Date: Sat, 15 Apr 2023 13:40:39 +0530
Subject: [PATCH 0019/1457] Fix NullPointer Exception (#4142)
---
.../lists/SinglyLinkedList.java | 23 ++++---
.../lists/SinglyLinkedListTest.java | 61 +++++++++++++++++++
2 files changed, 74 insertions(+), 10 deletions(-)
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
index a4276b021002..df460938390a 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java
@@ -122,20 +122,23 @@ public void swapNodes(int valueFirst, int valueSecond) {
* Reverse a singly linked list from a given node till the end
*
*/
- 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;
+ public Node reverseList(Node node) {
+ Node prev = null;
+ Node curr = node;
+
+ while (curr != null && curr.next != null) {
+ Node next=curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
- prevNode.next = prev;
- return head;
+ //when curr.next==null, the current element is left without pointing it to its prev,so
+ if(curr != null){
+ curr.next = prev;
+ prev=curr;
+ }
+ //prev will be pointing to the last element in the Linkedlist, it will be the new head of the reversed linkedlist
+ return prev;
}
/**
diff --git a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
index b02fb433ad4a..94896132cb36 100644
--- a/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/lists/SinglyLinkedListTest.java
@@ -1,5 +1,6 @@
package com.thealgorithms.datastructures.lists;
+
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
@@ -99,4 +100,64 @@ void deleteNth() {
list.deleteNth(6); //Index 6 has value 7
assertFalse(list.search(7));
}
+ //Test to check whether the method reverseList() works fine
+ @Test
+ void reverseList(){
+
+ //Creating a new LinkedList of size:4
+ //The linkedlist will be 1->2->3->4->null
+ SinglyLinkedList list = createSampleList(4);
+
+ //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node
+ //The reversed linkedlist will be 4->3->2->1->null
+ Node head=list.reverseList(list.getHead());
+
+ //Recording the Nodes after reversing the LinkedList
+ Node firstNode = head; //4
+ Node secondNode = firstNode.next; //3
+ Node thirdNode = secondNode.next; //2
+ Node fourthNode = thirdNode.next; //1
+
+ //Checking whether the LinkedList is reversed or not by comparing the original list and reversed list nodes
+ assertEquals(1,fourthNode.value);
+ assertEquals(2,thirdNode.value);
+ assertEquals(3,secondNode.value);
+ assertEquals(4,firstNode.value);
+ }
+
+ //Test to check whether implemented reverseList() method handles NullPointer Exception for TestCase where head==null
+ @Test
+ void reverseListNullPointer(){
+ //Creating a linkedlist with first node assigned to null
+ SinglyLinkedList list=new SinglyLinkedList();
+ Node first=list.getHead();
+
+ //Reversing the linkedlist
+ Node head=list.reverseList(first);
+
+ //checking whether the method works fine if the input is null
+ assertEquals(head,first);
+ }
+
+ //Testing reverseList() method for a linkedlist of size: 20
+ @Test
+ void reverseListTest(){
+ //Creating a new linkedlist
+ SinglyLinkedList list = createSampleList(20);
+
+ //Reversing the LinkedList using reverseList() method and storing the head of the reversed linkedlist in a head node
+ Node head=list.reverseList(list.getHead());
+
+ //Storing the head in a temp variable, so that we cannot loose the track of head
+ Node temp=head;
+
+ int i=20; //This is for the comparison of values of nodes of the reversed linkedlist
+ //Checking whether the reverseList() method performed its task
+ while(temp!=null && i>0){
+ assertEquals(i,temp.value);
+ temp=temp.next;
+ i--;
+ }
+ }
+
}
\ No newline at end of file
From 1dc388653a3895fe51f464c5b0f140bb88216dc8 Mon Sep 17 00:00:00 2001
From: Saurabh Rahate <55960054+saurabh-rahate@users.noreply.github.com>
Date: Sat, 15 Apr 2023 13:55:54 +0530
Subject: [PATCH 0020/1457] Refactor Code Style (#4151)
---
.../AllPathsFromSourceToTarget.java | 2 +-
.../com/thealgorithms/ciphers/Blowfish.java | 6 ++--
.../com/thealgorithms/ciphers/HillCipher.java | 12 ++++----
.../thealgorithms/ciphers/ProductCipher.java | 2 +-
.../conversions/BinaryToDecimal.java | 2 +-
.../conversions/BinaryToOctal.java | 2 +-
.../conversions/DecimalToBinary.java | 2 +-
.../thealgorithms/conversions/HexToOct.java | 2 +-
.../conversions/HexaDecimalToDecimal.java | 2 +-
.../conversions/OctalToDecimal.java | 2 +-
.../conversions/OctalToHexadecimal.java | 2 +-
.../conversions/TurkishToLatinConversion.java | 2 +-
.../datastructures/bags/Bag.java | 5 ++--
.../datastructures/graphs/BellmanFord.java | 18 +++++------
.../graphs/DIJSKSTRAS_ALGORITHM.java | 12 ++++----
.../datastructures/graphs/FloydWarshall.java | 4 +--
.../datastructures/graphs/Graphs.java | 2 +-
.../datastructures/graphs/Kosaraju.java | 8 ++---
.../datastructures/graphs/MatrixGraphs.java | 2 +-
.../datastructures/graphs/PrimMST.java | 14 ++++-----
.../graphs/TarjansAlgorithm.java | 28 +++++++----------
.../lists/DoublyLinkedList.java | 2 +-
.../stacks/MaximumMinimumWindow.java | 8 ++---
.../datastructures/stacks/PostfixToInfix.java | 2 +-
.../datastructures/stacks/ReverseStack.java | 2 +-
.../datastructures/trees/FenwickTree.java | 2 +-
.../datastructures/trees/SegmentTree.java | 6 ++--
.../searches/MatrixSearchAlgorithm.java | 2 +-
.../devutils/searches/SearchAlgorithm.java | 2 +-
.../dynamicprogramming/BoardPath.java | 2 +-
.../BruteForceKnapsack.java | 8 ++---
.../dynamicprogramming/CatalanNumber.java | 2 +-
.../CountFriendsPairing.java | 4 +--
.../DyanamicProgrammingKnapsack.java | 10 +++----
.../dynamicprogramming/EggDropping.java | 2 +-
.../dynamicprogramming/KadaneAlgorithm.java | 2 +-
.../dynamicprogramming/Knapsack.java | 10 +++----
.../KnapsackMemoization.java | 5 ++--
.../LongestAlternatingSubsequence.java | 6 ++--
.../LongestIncreasingSubsequence.java | 6 ++--
.../LongestPalindromicSubstring.java | 2 +-
...atrixChainRecursiveTopDownMemoisation.java | 8 ++---
.../dynamicprogramming/NewManShanksPrime.java | 2 +-
.../dynamicprogramming/RegexMatching.java | 2 +-
.../dynamicprogramming/RodCutting.java | 4 +--
.../ShortestCommonSupersequenceLength.java | 2 +-
.../dynamicprogramming/SubsetCount.java | 4 +--
.../dynamicprogramming/UniquePaths.java | 2 +-
.../maths/DeterminantOfMatrix.java | 6 ++--
.../maths/KrishnamurthyNumber.java | 2 +-
.../maths/NonRepeatingElement.java | 2 +-
.../maths/TrinomialTriangle.java | 2 +-
.../misc/ColorContrastRatio.java | 2 +-
.../thealgorithms/misc/InverseOfMatrix.java | 18 +++++------
.../misc/MedianOfRunningArray.java | 2 +-
.../java/com/thealgorithms/misc/Sort012D.java | 4 +--
.../thealgorithms/misc/ThreeSumProblem.java | 4 +--
.../com/thealgorithms/misc/TwoSumProblem.java | 10 +++----
.../others/BankersAlgorithm.java | 30 +++++++++----------
.../com/thealgorithms/others/BoyerMoore.java | 4 +--
.../others/BrianKernighanAlgorithm.java | 2 +-
.../thealgorithms/others/CRCAlgorithm.java | 4 +--
.../thealgorithms/others/GuassLegendre.java | 4 +--
...g_auto_completing_features_using_trie.java | 2 +-
.../others/InsertDeleteInArray.java | 4 +--
.../thealgorithms/others/Krishnamurthy.java | 2 +-
.../com/thealgorithms/others/PageRank.java | 8 ++---
.../com/thealgorithms/others/PasswordGen.java | 2 +-
.../others/QueueUsingTwoStacks.java | 2 +-
.../others/RotateMatriceBy90Degree.java | 4 +--
.../others/StackPostfixNotation.java | 13 ++++----
.../java/com/thealgorithms/others/Sudoku.java | 2 +-
.../com/thealgorithms/others/ThreeSum.java | 4 +--
.../thealgorithms/searches/BinarySearch.java | 8 ++---
.../searches/InterpolationSearch.java | 2 +-
.../com/thealgorithms/searches/KMPSearch.java | 4 +--
.../searches/OrderAgnosticBinarySearch.java | 2 +-
.../searches/SaddlebackSearch.java | 8 ++---
.../searches/SquareRootBinarySearch.java | 2 +-
.../sortOrderAgnosticBinarySearch.java | 2 +-
.../com/thealgorithms/sorts/BitonicSort.java | 14 ++++-----
.../com/thealgorithms/sorts/CycleSort.java | 2 +-
.../java/com/thealgorithms/sorts/DNFSort.java | 6 ++--
.../sorts/DualPivotQuickSort.java | 2 +-
.../com/thealgorithms/sorts/LinkListSort.java | 24 +++++++--------
.../sorts/MergeSortNoExtraSpace.java | 18 +++++------
.../com/thealgorithms/strings/Anagrams.java | 12 ++++----
.../LetterCombinationsOfPhoneNumber.java | 2 +-
.../com/thealgorithms/strings/MyAtoi.java | 14 ++-------
.../com/thealgorithms/strings/WordLadder.java | 5 +---
.../AllPathsFromSourceToTargetTest.java | 8 ++---
.../backtracking/FloodFillTest.java | 20 ++++++-------
.../backtracking/MazeRecursionTest.java | 4 +--
.../maths/AutomorphicNumberTest.java | 4 +--
.../maths/PerfectNumberTest.java | 4 +--
.../others/CalculateMaxOfMinTest.java | 14 ++++-----
.../others/CountFriendsPairingTest.java | 16 +++++-----
.../others/KadaneAlogrithmTest.java | 16 +++++-----
.../others/LinkListSortTest.java | 16 +++++-----
.../sortOrderAgnosticBinarySearchTest.java | 4 +--
100 files changed, 293 insertions(+), 319 deletions(-)
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
index 424c451edb55..8acaa954ce75 100644
--- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -91,7 +91,7 @@ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List> allPathsFromSourceToTarget(int vertices, int a[][], int source, int destination)
+ public static List> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination)
{
// Create a sample graph
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index b60cf7c7ac74..8864fc75f342 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -11,7 +11,7 @@
public class Blowfish {
//Initializing substitution boxes
- String S[][] = {
+ String[][] S = {
{
"d1310ba6",
"98dfb5ac",
@@ -1047,7 +1047,7 @@ public class Blowfish {
};
//Initializing subkeys with digits of pi
- String P[] = {
+ String[] P = {
"243f6a88",
"85a308d3",
"13198a2e",
@@ -1146,7 +1146,7 @@ private String addBin(String a, String b) {
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[] a = new String[4];
String ans = "";
for (int i = 0; i < 8; i += 2) {
//column number for S-box is a 8-bit value
diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
index 102d760d16c1..ffc7e08bedf7 100644
--- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
@@ -22,7 +22,7 @@ static void encrypt(String message) {
System.out.println("Enter key matrix size");
int matrixSize = userInput.nextInt();
System.out.println("Enter Key/encryptionKey matrix ");
- int keyMatrix[][] = new int[matrixSize][matrixSize];
+ int[][] keyMatrix = new int[matrixSize][matrixSize];
for (int i = 0; i < matrixSize; i++) {
for (int j = 0; j < matrixSize; j++) {
keyMatrix[i][j] = userInput.nextInt();
@@ -33,7 +33,7 @@ static void encrypt(String message) {
int[][] messageVector = new int[matrixSize][1];
String CipherText = "";
- int cipherMatrix[][] = new int[matrixSize][1];
+ int[][] cipherMatrix = new int[matrixSize][1];
int j = 0;
while (j < message.length()) {
for (int i = 0; i < matrixSize; i++) {
@@ -69,7 +69,7 @@ static void decrypt(String message) {
System.out.println("Enter key matrix size");
int n = userInput.nextInt();
System.out.println("Enter inverseKey/decryptionKey matrix ");
- int keyMatrix[][] = new int[n][n];
+ int[][] keyMatrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
keyMatrix[i][j] = userInput.nextInt();
@@ -81,7 +81,7 @@ static void decrypt(String message) {
//solving for the required plaintext message
int[][] messageVector = new int[n][1];
String PlainText = "";
- int plainMatrix[][] = new int[n][1];
+ int[][] plainMatrix = new int[n][1];
int j = 0;
while (j < message.length()) {
for (int i = 0; i < n; i++) {
@@ -111,13 +111,13 @@ static void decrypt(String message) {
}
// Determinant calculator
- public static int determinant(int a[][], int n) {
+ public static int determinant(int[][] a, int n) {
int det = 0, sign = 1, p = 0, q = 0;
if (n == 1) {
det = a[0][0];
} else {
- int b[][] = new int[n - 1][n - 1];
+ int[][] b = new int[n - 1][n - 1];
for (int x = 0; x < n; x++) {
p = 0;
q = 0;
diff --git a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
index e2a33e035e16..c5ce8a9b157c 100644
--- a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
@@ -4,7 +4,7 @@
class ProductCipher {
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the input to be encrypted: ");
String substitutionInput = sc.nextLine();
diff --git a/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java b/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
index b0ab817d06b2..fdf9df7b2467 100644
--- a/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java
@@ -23,7 +23,7 @@ public static long binaryToDecimal(long binNum) {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Binary number: ");
System.out.println("Decimal equivalent:" + binaryToDecimal(sc.nextLong()));
diff --git a/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java b/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
index b0d6b32fd63b..70bad812141b 100644
--- a/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
+++ b/src/main/java/com/thealgorithms/conversions/BinaryToOctal.java
@@ -14,7 +14,7 @@ public class BinaryToOctal {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the binary number: ");
int b = sc.nextInt();
diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
index 7bd67123de33..c87508c62e86 100644
--- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
+++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
@@ -12,7 +12,7 @@ class DecimalToBinary {
*
* @param args Command Line Arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
conventionalConversion();
bitwiseConversion();
}
diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java
index ccbab30f070e..2a57fbde5c41 100644
--- a/src/main/java/com/thealgorithms/conversions/HexToOct.java
+++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java
@@ -52,7 +52,7 @@ public static int decimal2octal(int q) {
*
* @param args arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
String hexadecnum;
int decnum, octalnum;
Scanner scan = new Scanner(System.in);
diff --git a/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java b/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java
index cb9d7fafde8f..7675c83ebcfa 100644
--- a/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/HexaDecimalToDecimal.java
@@ -17,7 +17,7 @@ public static int getHexaToDec(String hex) {
}
// Main method gets the hexadecimal input from user and converts it into Decimal output.
- public static void main(String args[]) {
+ public static void main(String[] args) {
String hexa_Input;
int dec_output;
Scanner scan = new Scanner(System.in);
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
index 782f3488383b..d4916a3dbcca 100644
--- a/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/OctalToDecimal.java
@@ -14,7 +14,7 @@ public class OctalToDecimal {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Octal Input: ");
String inputOctal = sc.nextLine();
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
index b1755b8a0aca..5edd94c38430 100644
--- a/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
+++ b/src/main/java/com/thealgorithms/conversions/OctalToHexadecimal.java
@@ -46,7 +46,7 @@ public static String decimalToHex(int d) {
return hex;
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Octal number: ");
// Take octal number as input from user in a string
diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
index af26cc056f1a..81c8d9bd1f3c 100644
--- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
+++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
@@ -14,7 +14,7 @@ public class TurkishToLatinConversion {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the string: ");
String b = sc.next();
diff --git a/src/main/java/com/thealgorithms/datastructures/bags/Bag.java b/src/main/java/com/thealgorithms/datastructures/bags/Bag.java
index 1d03e5cf46a3..c82b9124bebc 100644
--- a/src/main/java/com/thealgorithms/datastructures/bags/Bag.java
+++ b/src/main/java/com/thealgorithms/datastructures/bags/Bag.java
@@ -59,9 +59,8 @@ public void add(Element element) {
* @return true if bag contains element, otherwise false
*/
public boolean contains(Element element) {
- Iterator iterator = this.iterator();
- while (iterator.hasNext()) {
- if (iterator.next().equals(element)) {
+ for (Element value : this) {
+ if (value.equals(element)) {
return true;
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
index b640eeaf599d..aba377329aa0 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
@@ -6,7 +6,7 @@ class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Gr
start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
int vertex, edge;
- private Edge edges[];
+ private Edge[] edges;
private int index = 0;
BellmanFord(int v, int e) {
@@ -36,7 +36,7 @@ public Edge(int a, int b, int c) {
* @param p[] Parent array which shows updates in edges
* @param i Current vertex under consideration
*/
- void printPath(int p[], int i) {
+ void printPath(int[] p, int i) {
if (p[i] == -1) { // Found the path back to parent
return;
}
@@ -44,7 +44,7 @@ void printPath(int p[], int i) {
System.out.print(i + " ");
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables
obj.go();
}
@@ -55,7 +55,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde
System.out.println("Enter no. of vertices and edges please");
v = sc.nextInt();
e = sc.nextInt();
- Edge arr[] = new Edge[e]; // Array of edges
+ Edge[] arr = new Edge[e]; // Array of edges
System.out.println("Input edges");
for (i = 0; i < e; i++) {
u = sc.nextInt();
@@ -63,9 +63,9 @@ public void go() { // shows distance to all vertices // Interactive run for unde
w = sc.nextInt();
arr[i] = new Edge(u, ve, w);
}
- int dist[] = new int[v]; // Distance array for holding the finalized shortest path distance between source
+ int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
- int p[] = new int[v]; // Parent array for holding the paths
+ int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
dist[i] = Integer.MAX_VALUE; // Initializing distance values
}
@@ -113,11 +113,11 @@ public void go() { // shows distance to all vertices // Interactive run for unde
* @param end Ending vertex
* @param Edge Array of edges
*/
- public void show(int source, int end, Edge arr[]) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
+ public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
int i, j, v = vertex, e = edge, neg = 0;
- double dist[] = new double[v]; // Distance array for holding the finalized shortest path distance between source
+ double[] dist = new double[v]; // Distance array for holding the finalized shortest path distance between source
// and all vertices
- int p[] = new int[v]; // Parent array for holding the paths
+ int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
dist[i] = Integer.MAX_VALUE; // Initializing distance values
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
index 5b8533b8df59..31ed7ef2de2a 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
@@ -8,7 +8,7 @@ class dijkstras {
int k = 9;
- int minDist(int dist[], Boolean Set[]) {
+ int minDist(int[] dist, Boolean[] Set) {
int min = Integer.MAX_VALUE, min_index = -1;
for (int r = 0; r < k; r++) {
@@ -21,16 +21,16 @@ int minDist(int dist[], Boolean Set[]) {
return min_index;
}
- void print(int dist[]) {
+ void print(int[] dist) {
System.out.println("Vertex \t\t Distance");
for (int i = 0; i < k; i++) {
System.out.println(i + " \t " + dist[i]);
}
}
- void dijkstra(int graph[][], int src) {
- int dist[] = new int[k];
- Boolean Set[] = new Boolean[k];
+ void dijkstra(int[][] graph, int src) {
+ int[] dist = new int[k];
+ Boolean[] Set = new Boolean[k];
for (int i = 0; i < k; i++) {
dist[i] = Integer.MAX_VALUE;
@@ -60,7 +60,7 @@ void dijkstra(int graph[][], int src) {
}
public static void main(String[] args) {
- int graph[][] = new int[][] {
+ int[][] graph = new int[][] {
{ 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
index ab9ef7352cbc..bf3ef8e6eab9 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
@@ -4,7 +4,7 @@
public class FloydWarshall {
- private int DistanceMatrix[][];
+ private int[][] DistanceMatrix;
private int numberofvertices; // number of vertices in the graph
public static final int INFINITY = 999;
@@ -15,7 +15,7 @@ public FloydWarshall(int numberofvertices) {
this.numberofvertices = numberofvertices;
}
- public void floydwarshall(int AdjacencyMatrix[][]) { // calculates all the distances from source to destination vertex
+ public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) {
for (
int destination = 1;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java
index 8d19a8ca04fc..77cea399c173 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java
@@ -122,7 +122,7 @@ public String toString() {
public class Graphs {
- public static void main(String args[]) {
+ public static void main(String[] args) {
AdjacencyListGraph graph = new AdjacencyListGraph<>();
assert graph.addEdge(1, 2);
assert graph.addEdge(1, 5);
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
index b3632b47970d..f24791dce596 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
@@ -83,7 +83,7 @@ public List> kosaraju(int v, List> list){
}
private void sortEdgesByLowestFinishTime(int v, List> list){
- int vis[] = new int[v];
+ int[] vis = new int[v];
for (int i = 0; i < v; i++) {
if(vis[i] == 0){
dfs(i, vis, list);
@@ -110,7 +110,7 @@ private List> createTransposeMatrix(int v, List> lis
* @param transposeGraph Transpose of the given adjacency list
*/
public void findStronglyConnectedComponents(int v, List> transposeGraph){
- int vis[] = new int[v];
+ int[] vis = new int[v];
while (!stack.isEmpty()) {
var node = stack.pop();
if(vis[node] == 0){
@@ -122,7 +122,7 @@ public void findStronglyConnectedComponents(int v, List> transpose
}
//Dfs to store the nodes in order of lowest finish time
- private void dfs(int node, int vis[], List> list){
+ private void dfs(int node, int[] vis, List> list){
vis[node] = 1;
for(Integer neighbour : list.get(node)){
if(vis[neighbour] == 0)
@@ -132,7 +132,7 @@ private void dfs(int node, int vis[], List> list){
}
//Dfs to find all the nodes of each strongly connected component
- private void dfs2(int node, int vis[], List> list){
+ private void dfs2(int node, int[] vis, List> list){
vis[node] = 1;
for(Integer neighbour : list.get(node)){
if(vis[neighbour] == 0)
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
index 8d382cdde8f9..7593a9cfc253 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
@@ -14,7 +14,7 @@
*/
public class MatrixGraphs {
- public static void main(String args[]) {
+ public static void main(String[] args) {
AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10);
graph.addEdge(1, 2);
graph.addEdge(1, 5);
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
index 75de04713d47..893b835e0ed9 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
@@ -12,7 +12,7 @@ class PrimMST {
// A utility function to find the vertex with minimum key
// value, from the set of vertices not yet included in MST
- int minKey(int key[], Boolean mstSet[]) {
+ int minKey(int[] key, Boolean[] mstSet) {
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
@@ -28,7 +28,7 @@ int minKey(int key[], Boolean mstSet[]) {
// A utility function to print the constructed MST stored in
// parent[]
- void printMST(int parent[], int n, int graph[][]) {
+ void printMST(int[] parent, int n, int[][] graph) {
System.out.println("Edge Weight");
for (int i = 1; i < V; i++) {
System.out.println(
@@ -39,15 +39,15 @@ void printMST(int parent[], int n, int graph[][]) {
// Function to construct and print MST for a graph represented
// using adjacency matrix representation
- void primMST(int graph[][]) {
+ void primMST(int[][] graph) {
// Array to store constructed MST
- int parent[] = new int[V];
+ int[] parent = new int[V];
// Key values used to pick minimum weight edge in cut
- int key[] = new int[V];
+ int[] key = new int[V];
// To represent set of vertices not yet included in MST
- Boolean mstSet[] = new Boolean[V];
+ Boolean[] mstSet = new Boolean[V];
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
@@ -103,7 +103,7 @@ public static void main(String[] args) {
(3)-------(4)
9 */
PrimMST t = new PrimMST();
- int graph[][] = new int[][] {
+ int[][] graph = new int[][] {
{ 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
index bb633c4ee6c0..497daeca4428 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
@@ -68,15 +68,15 @@ public List> stronglyConnectedComponents(int V, List
// lowTime: indicates the earliest visited vertex (the vertex with minimum insertion time) that can
// be reached from a subtree rooted with a particular node.
- int lowTime[] = new int[V];
- int insertionTime[] = new int[V];
+ int[] lowTime = new int[V];
+ int[] insertionTime = new int[V];
for (int i = 0; i < V; i++) {
insertionTime[i] = -1;
lowTime[i] = -1;
}
// To check if element is present in stack
- boolean isInStack[] = new boolean[V];
+ boolean[] isInStack = new boolean[V];
// Store nodes during DFS
Stack st = new Stack();
@@ -89,8 +89,8 @@ public List> stronglyConnectedComponents(int V, List
return SCClist;
}
- private void stronglyConnCompsUtil(int u, int lowTime[], int insertionTime[],
- boolean isInStack[], Stack st, List> graph) {
+ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime,
+ boolean[] isInStack, Stack st, List> graph) {
// Initialize insertion time and lowTime value of current node
insertionTime[u] = Time;
@@ -101,22 +101,16 @@ private void stronglyConnCompsUtil(int u, int lowTime[], int insertionTime[],
isInStack[u] = true;
st.push(u);
- int n;
-
// Go through all vertices adjacent to this
- Iterator i = graph.get(u).iterator();
-
- while (i.hasNext()) {
- n = i.next();
-
+ for (Integer vertex : graph.get(u)) {
//If the adjacent node is unvisited, do DFS
- if (insertionTime[n] == -1) {
- stronglyConnCompsUtil(n, lowTime, insertionTime, isInStack, st, graph);
+ if (insertionTime[vertex] == -1) {
+ stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph);
//update lowTime for the current node comparing lowtime of adj node
- lowTime[u] = Math.min(lowTime[u], lowTime[n]);
- } else if (isInStack[n]) {
+ lowTime[u] = Math.min(lowTime[u], lowTime[vertex]);
+ } else if (isInStack[vertex]) {
//If adj node is in stack, update low
- lowTime[u] = Math.min(lowTime[u], insertionTime[n]);
+ lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]);
}
}
//If lowtime and insertion time are same, current node is the head of an SCC
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
index 88f762ba56e6..2d048d9967b5 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java
@@ -133,7 +133,7 @@ public void displayLink() {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
DoublyLinkedList myList = new DoublyLinkedList();
LinkOperations linkOperations = new LinkOperations();
linkOperations.insertHead(13, myList);
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
index ecde496c031a..53a502798caa 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/MaximumMinimumWindow.java
@@ -39,8 +39,8 @@ public class MaximumMinimumWindow {
*/
public static int[] calculateMaxOfMin(int[] arr, int n) {
Stack s = new Stack<>();
- int left[] = new int[n + 1];
- int right[] = new int[n + 1];
+ int[] left = new int[n + 1];
+ int[] right = new int[n + 1];
for (int i = 0; i < n; i++) {
left[i] = -1;
right[i] = n;
@@ -74,7 +74,7 @@ public static int[] calculateMaxOfMin(int[] arr, int n) {
s.push(i);
}
- int ans[] = new int[n + 1];
+ int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) {
ans[i] = 0;
}
@@ -96,7 +96,7 @@ public static int[] calculateMaxOfMin(int[] arr, int n) {
return ans;
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
int[] arr = new int[] { 10, 20, 30, 50, 10, 70, 30 };
int[] target = new int[] { 70, 30, 20, 10, 10, 10, 10 };
int[] res = calculateMaxOfMin(arr, arr.length);
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
index 6b6ce7568fb0..868aa778a626 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/PostfixToInfix.java
@@ -118,7 +118,7 @@ public static String getPostfixToInfix(String postfix) {
return infix;
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
assert getPostfixToInfix("ABC+/").equals("(A/(B+C))");
assert getPostfixToInfix("AB+CD+*").equals("((A+B)*(C+D))");
assert getPostfixToInfix("AB+C+D+").equals("(((A+B)+C)+D)");
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
index 7fc761b4d2c8..1dd9fe11d891 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java
@@ -10,7 +10,7 @@
*/
public class ReverseStack {
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(
"Enter the number of elements you wish to insert in the stack"
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
index e44984b1b9a7..5cd28202229e 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
@@ -3,7 +3,7 @@
public class FenwickTree {
private int n;
- private int fen_t[];
+ private int[] fen_t;
/* Constructor which takes the size of the array as a parameter */
public FenwickTree(int n) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
index 68154129dd1d..e24db38da08f 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
@@ -2,12 +2,12 @@
public class SegmentTree {
- private int seg_t[];
+ private int[] seg_t;
private int n;
- private int arr[];
+ private int[] arr;
/* Constructor which takes the size of the array and the array as a parameter*/
- public SegmentTree(int n, int arr[]) {
+ public SegmentTree(int n, int[] arr) {
this.n = n;
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int seg_size = 2 * (int) Math.pow(2, x) - 1;
diff --git a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java
index f102bd5c673b..36587a21c863 100644
--- a/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java
+++ b/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java
@@ -12,5 +12,5 @@ public interface MatrixSearchAlgorithm {
* @param Comparable type
* @return array containing the first found coordinates of the element
*/
- > int[] find(T matrix[][], T key);
+ > int[] find(T[][] matrix, T key);
}
diff --git a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java
index 69602811c8f9..eb5b42756958 100644
--- a/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java
+++ b/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java
@@ -12,5 +12,5 @@ public interface SearchAlgorithm {
* @param Comparable type
* @return first found index of the element
*/
- > int find(T array[], T key);
+ > int find(T[] array, T key);
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
index dfb75717b970..0f2a14282240 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
@@ -52,7 +52,7 @@ public static int bpR(int start, int end) {
return count;
}
- public static int bpRS(int curr, int end, int strg[]) {
+ public static int bpRS(int curr, int end, int[] strg) {
if (curr == end) {
return 1;
} else if (curr > end) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
index 49031152e57d..c6f555609a24 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
@@ -6,7 +6,7 @@ public class BruteForceKnapsack {
// Returns the maximum value that
// can be put in a knapsack of
// capacity W
- static int knapSack(int W, int wt[], int val[], int n) {
+ static int knapSack(int W, int[] wt, int[] val, int n) {
// Base Case
if (n == 0 || W == 0) {
return 0;
@@ -29,9 +29,9 @@ static int knapSack(int W, int wt[], int val[], int n) {
}
// Driver code
- public static void main(String args[]) {
- int val[] = new int[] { 60, 100, 120 };
- int wt[] = new int[] { 10, 20, 30 };
+ public static void main(String[] args) {
+ int[] val = new int[] { 60, 100, 120 };
+ int[] wt = new int[] { 10, 20, 30 };
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
index 41bd49715721..9744f3c03c7e 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
@@ -23,7 +23,7 @@ public class CatalanNumber {
*/
static long findNthCatalan(int n) {
// Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
- long catalanArray[] = new long[n + 1];
+ long[] catalanArray = new long[n + 1];
// Initialising C₀ = 1 and C₁ = 1
catalanArray[0] = 1;
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
index 968586c552ab..75189b61d53f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
@@ -15,8 +15,8 @@
public class CountFriendsPairing {
- public static boolean countFriendsPairing(int n, int a[]) {
- int dp[] = new int[n + 1];
+ 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
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
index 445f1e9d0517..3b501f669ade 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DyanamicProgrammingKnapsack.java
@@ -5,9 +5,9 @@
public class DyanamicProgrammingKnapsack {
// Returns the maximum value that can
// be put in a knapsack of capacity W
- static int knapSack(int W, int wt[], int val[], int n) {
+ static int knapSack(int W, int[] wt, int[] val, int n) {
int i, w;
- int K[][] = new int[n + 1][W + 1];
+ int[][] K = new int[n + 1][W + 1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++) {
@@ -26,9 +26,9 @@ static int knapSack(int W, int wt[], int val[], int n) {
}
// Driver code
- public static void main(String args[]) {
- int val[] = new int[] { 60, 100, 120 };
- int wt[] = new int[] { 10, 20, 30 };
+ public static void main(String[] args) {
+ int[] val = new int[] { 60, 100, 120 };
+ int[] wt = new int[] { 10, 20, 30 };
int W = 50;
int n = val.length;
System.out.println(knapSack(W, wt, val, n));
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
index efceb4494962..eee6ab7878e4 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
@@ -40,7 +40,7 @@ public static int minTrials(int n, int m) {
return eggFloor[n][m];
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
int n = 2, m = 4;
// result outputs min no. of trials in worst case for n eggs and m floors
int result = minTrials(n, m);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
index 8123a02562f3..0c15e2febeb6 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
@@ -7,7 +7,7 @@
public class KadaneAlgorithm {
- public static boolean max_Sum(int a[], int predicted_answer) {
+ public static boolean max_Sum(int[] a, int predicted_answer) {
int sum = a[0], running_sum = 0;
for (int k : a) {
running_sum = running_sum + k;
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
index df1bbd234fb7..13296b8456a2 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
@@ -5,13 +5,13 @@
*/
public class Knapsack {
- private static int knapSack(int W, int wt[], int val[], int n)
+ private static int knapSack(int W, int[] wt, int[] val, int n)
throws IllegalArgumentException {
if (wt == null || val == null) {
throw new IllegalArgumentException();
}
int i, w;
- int rv[][] = new int[n + 1][W + 1]; // rv means return value
+ int[][] rv = new int[n + 1][W + 1]; // rv means return value
// Build table rv[][] in bottom up manner
for (i = 0; i <= n; i++) {
@@ -34,9 +34,9 @@ private static int knapSack(int W, int wt[], int val[], int n)
}
// Driver program to test above function
- public static void main(String args[]) {
- int val[] = new int[] { 50, 100, 130 };
- int wt[] = new int[] { 10, 20, 40 };
+ public static void main(String[] args) {
+ int[] val = new int[] { 50, 100, 130 };
+ int[] wt = new int[] { 10, 20, 40 };
int W = 50;
System.out.println(knapSack(W, wt, val, val.length));
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
index 81888fda5296..bcf1909d49d6 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
@@ -26,9 +26,8 @@ int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) {
// Returns the value of maximum profit using recursive approach
int solveKnapsackRecursive(int capacity, int[] weights,
- int[] profits, int numOfItems,
- int[][] dpTable) {
-
+ int[] profits, int numOfItems,
+ int[][] dpTable) {
// Base condition
if (numOfItems == 0 || capacity == 0) {
return 0;
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
index e3786ac6bbad..bfa75a908441 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
@@ -13,7 +13,7 @@
public class LongestAlternatingSubsequence {
/* Function to return longest alternating subsequence length*/
- static int AlternatingLength(int arr[], int n) {
+ static int AlternatingLength(int[] arr, int n) {
/*
las[i][0] = Length of the longest
@@ -28,7 +28,7 @@ static int AlternatingLength(int arr[], int n) {
element
*/
- int las[][] = new int[n][2]; // las = LongestAlternatingSubsequence
+ int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence
for (int i = 0; i < n; i++) {
las[i][0] = las[i][1] = 1;
@@ -61,7 +61,7 @@ static int AlternatingLength(int arr[], int n) {
}
public static void main(String[] args) {
- int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 };
+ int[] arr = { 10, 22, 9, 33, 49, 50, 31, 60 };
int n = arr.length;
System.out.println(
"Length of Longest " +
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
index 3911d60bb718..373077e88e4c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
@@ -11,7 +11,7 @@ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
- int arr[] = new int[n];
+ int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
@@ -70,9 +70,9 @@ else if (array[i] > tail[length - 1]) {
* @author Alon Firestein (https://github.com/alonfirestein)
*/
// A function for finding the length of the LIS algorithm in O(nlogn) complexity.
- public static int findLISLen(int a[]) {
+ public static int findLISLen(int[] a) {
int size = a.length;
- int arr[] = new int[size];
+ int[] arr = new int[size];
arr[0] = a[0];
int lis = 1;
for (int i = 1; i < size; i++) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
index 824bce085b83..0704272963fd 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
@@ -20,7 +20,7 @@ private static String LPS(String input) {
if (input == null || input.length() == 0) {
return input;
}
- boolean arr[][] = new boolean[input.length()][input.length()];
+ boolean[][] arr = new boolean[input.length()][input.length()];
int start = 0, end = 0;
for (int g = 0; g < input.length(); g++) {
for (int i = 0, j = g; j < input.length(); i++, j++) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
index bf751e8c359e..0bcff7678bd4 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
@@ -8,9 +8,9 @@
// minimizes the number of scalar multiplications.
public class MatrixChainRecursiveTopDownMemoisation {
- static int Memoized_Matrix_Chain(int p[]) {
+ static int Memoized_Matrix_Chain(int[] p) {
int n = p.length;
- int m[][] = new int[n][n];
+ int[][] m = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
m[i][j] = Integer.MAX_VALUE;
@@ -19,7 +19,7 @@ static int Memoized_Matrix_Chain(int p[]) {
return Lookup_Chain(m, p, 1, n - 1);
}
- static int Lookup_Chain(int m[][], int p[], int i, int j) {
+ static int Lookup_Chain(int[][] m, int[] p, int i, int j) {
if (i == j) {
m[i][j] = 0;
return m[i][j];
@@ -43,7 +43,7 @@ static int Lookup_Chain(int m[][], int p[], int i, int j) {
// in this code we are taking the example of 4 matrixes whose orders are 1x2,2x3,3x4,4x5 respectively
// output should be Minimum number of multiplications is 38
public static void main(String[] args) {
- int arr[] = { 1, 2, 3, 4, 5 };
+ int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(
"Minimum number of multiplications is " + Memoized_Matrix_Chain(arr)
);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
index e52d72fd4942..d41135b1f118 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
@@ -10,7 +10,7 @@
public class NewManShanksPrime {
public static boolean nthManShanksPrime(int n, int expected_answer) {
- int a[] = new int[n + 1];
+ int[] a = new int[n + 1];
// array of n+1 size is initialized
a[0] = a[1] = 1;
// The 0th and 1st index position values are fixed. They are initialized as 1
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
index 5994ffe8dde5..f30267ecc646 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
@@ -134,7 +134,7 @@ static boolean regexRecursion(
// Method 4: Bottom-Up DP(Tabulation)
// Time Complexity=0(N*M) Space Complexity=0(N*M)
static boolean regexBU(String src, String pat) {
- boolean strg[][] = new boolean[src.length() + 1][pat.length() + 1];
+ boolean[][] strg = new boolean[src.length() + 1][pat.length() + 1];
strg[src.length()][pat.length()] = true;
for (int row = src.length(); row >= 0; row--) {
for (int col = pat.length() - 1; col >= 0; col--) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java
index 90369b6ff0c1..066113a235f1 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java
@@ -8,7 +8,7 @@
public class RodCutting {
private static int cutRod(int[] price, int n) {
- int val[] = new int[n + 1];
+ int[] val = new int[n + 1];
val[0] = 0;
for (int i = 1; i <= n; i++) {
@@ -24,7 +24,7 @@ private static int cutRod(int[] price, int n) {
}
// main function to test
- public static void main(String args[]) {
+ public static void main(String[] args) {
int[] arr = new int[] { 2, 5, 13, 19, 20 };
int result = cutRod(arr, arr.length);
System.out.println("Maximum Obtainable Value is " + result);
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java
index 722e0a8989f0..c24bdeda6485 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java
@@ -45,7 +45,7 @@ static int lcs(String X, String Y, int m, int n) {
}
// Driver code
- public static void main(String args[]) {
+ public static void main(String[] args) {
String X = "AGGTAB";
String Y = "GXTXAYB";
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
index 2d36f5adf97c..46ba3999c8ad 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
@@ -49,11 +49,11 @@ public int getCount(int[] arr, int target){
*/
public int getCountSO(int[] arr, int target){
int n = arr.length;
- int prev[]=new int[target+1];
+ int[] prev =new int[target+1];
prev[0] =1;
if(arr[0]<=target) prev[arr[0]] = 1;
for(int ind = 1; ind hm = new HashMap();
for (int i = 0; i < nums.length; i++) {
hm.put(i, nums[i]);
@@ -90,7 +90,7 @@ public int[] TwoPointer(int[] nums, int target) {
public int[] HashMap(int[] nums, int target) {
//Using Hashmaps
- int ans[] = new int[2];
+ int[] ans = new int[2];
HashMap hm = new HashMap();
for (int i = 0; i < nums.length; i++) {
hm.put(nums[i], i);
diff --git a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
index 1c7870e05fe7..7e6ce9db4417 100644
--- a/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/BankersAlgorithm.java
@@ -26,11 +26,11 @@ public class BankersAlgorithm {
* This method finds the need of each process
*/
static void calculateNeed(
- int needArray[][],
- int maxArray[][],
- int allocationArray[][],
- int totalProcess,
- int totalResources
+ int[][] needArray,
+ int[][] maxArray,
+ int[][] allocationArray,
+ int totalProcess,
+ int totalResources
) {
for (int i = 0; i < totalProcess; i++) {
for (int j = 0; j < totalResources; j++) {
@@ -55,12 +55,12 @@ static void calculateNeed(
* @return boolean if the system is in safe state or not
*/
static boolean checkSafeSystem(
- int processes[],
- int availableArray[],
- int maxArray[][],
- int allocationArray[][],
- int totalProcess,
- int totalResources
+ int[] processes,
+ int[] availableArray,
+ int[][] maxArray,
+ int[][] allocationArray,
+ int totalProcess,
+ int totalResources
) {
int[][] needArray = new int[totalProcess][totalResources];
@@ -144,14 +144,14 @@ public static void main(String[] args) {
System.out.println("Enter total number of resources");
numberOfResources = sc.nextInt();
- int processes[] = new int[numberOfProcesses];
+ int[] processes = new int[numberOfProcesses];
for (int i = 0; i < numberOfProcesses; i++) {
processes[i] = i;
}
System.out.println("--Enter the availability of--");
- int availableArray[] = new int[numberOfResources];
+ int[] availableArray = new int[numberOfResources];
for (int i = 0; i < numberOfResources; i++) {
System.out.println("resource " + i + ": ");
availableArray[i] = sc.nextInt();
@@ -159,7 +159,7 @@ public static void main(String[] args) {
System.out.println("--Enter the maximum matrix--");
- int maxArray[][] = new int[numberOfProcesses][numberOfResources];
+ int[][] maxArray = new int[numberOfProcesses][numberOfResources];
for (int i = 0; i < numberOfProcesses; i++) {
System.out.println("For process " + i + ": ");
for (int j = 0; j < numberOfResources; j++) {
@@ -172,7 +172,7 @@ public static void main(String[] args) {
System.out.println("--Enter the allocation matrix--");
- int allocationArray[][] = new int[numberOfProcesses][numberOfResources];
+ int[][] allocationArray = new int[numberOfProcesses][numberOfResources];
for (int i = 0; i < numberOfProcesses; i++) {
System.out.println("For process " + i + ": ");
for (int j = 0; j < numberOfResources; j++) {
diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java
index bb3a186b46e4..2e4edbd9a1f6 100644
--- a/src/main/java/com/thealgorithms/others/BoyerMoore.java
+++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java
@@ -35,10 +35,10 @@ public static int findmajor(int[] a) {
return -1;
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
- int a[] = new int[n];
+ int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = input.nextInt();
}
diff --git a/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java b/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java
index 8730ed76338d..a1983feccb2e 100644
--- a/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/BrianKernighanAlgorithm.java
@@ -38,7 +38,7 @@ static int countSetBits(int num) {
/**
* @param args : command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int setBitCount = countSetBits(num);
diff --git a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java
index 3b0d2f3a3003..bfa8828e250b 100644
--- a/src/main/java/com/thealgorithms/others/CRCAlgorithm.java
+++ b/src/main/java/com/thealgorithms/others/CRCAlgorithm.java
@@ -158,9 +158,7 @@ public void divideMessageWithP(boolean check) {
}
dividedMessage = (ArrayList) x.clone();
if (!check) {
- for (int z : dividedMessage) {
- message.add(z);
- }
+ message.addAll(dividedMessage);
} else {
if (dividedMessage.contains(1) && messageChanged) {
wrongMessCaught++;
diff --git a/src/main/java/com/thealgorithms/others/GuassLegendre.java b/src/main/java/com/thealgorithms/others/GuassLegendre.java
index 9d1b169a0d04..8b15739a6d91 100644
--- a/src/main/java/com/thealgorithms/others/GuassLegendre.java
+++ b/src/main/java/com/thealgorithms/others/GuassLegendre.java
@@ -21,7 +21,7 @@ static double pi(int l) {
double a = 1, b = Math.pow(2, -0.5), t = 0.25, p = 1;
for (int i = 0; i < l; ++i) {
- double temp[] = update(a, b, t, p);
+ double[] temp = update(a, b, t, p);
a = temp[0];
b = temp[1];
t = temp[2];
@@ -32,7 +32,7 @@ static double pi(int l) {
}
static double[] update(double a, double b, double t, double p) {
- double values[] = new double[4];
+ double[] values = new double[4];
values[0] = (a + b) / 2;
values[1] = Math.sqrt(a * b);
values[2] = t - p * Math.pow(a - values[0], 2);
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 08cdd44fb33a..3904691a91d8 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
@@ -10,7 +10,7 @@ class Trieac {
// Trie node
static class TrieNode {
- TrieNode children[] = new TrieNode[ALPHABET_SIZE];
+ TrieNode[] children = new TrieNode[ALPHABET_SIZE];
// isWordEnd is true if the node represents
// end of a word
diff --git a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
index e38fab67468d..81697750e21a 100644
--- a/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
+++ b/src/main/java/com/thealgorithms/others/InsertDeleteInArray.java
@@ -8,7 +8,7 @@ public static void main(String[] args) {
Scanner s = new Scanner(System.in); // Input statement
System.out.println("Enter the size of the array");
int size = s.nextInt();
- int a[] = new int[size];
+ int[] a = new int[size];
int i;
// To enter the initial elements
@@ -25,7 +25,7 @@ public static void main(String[] args) {
System.out.println("Enter the element to be inserted");
int ins = s.nextInt();
int size2 = size + 1;
- int b[] = new int[size2];
+ int[] b = new int[size2];
for (i = 0; i < size2; i++) {
if (i <= insert_pos) {
b[i] = a[i];
diff --git a/src/main/java/com/thealgorithms/others/Krishnamurthy.java b/src/main/java/com/thealgorithms/others/Krishnamurthy.java
index 2b0c61ff99c7..1f7cd121933f 100644
--- a/src/main/java/com/thealgorithms/others/Krishnamurthy.java
+++ b/src/main/java/com/thealgorithms/others/Krishnamurthy.java
@@ -12,7 +12,7 @@ static int fact(int n) {
return p;
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a, b, s = 0;
System.out.print("Enter the number : ");
diff --git a/src/main/java/com/thealgorithms/others/PageRank.java b/src/main/java/com/thealgorithms/others/PageRank.java
index 8d67ff8f983c..b5a7422aece4 100644
--- a/src/main/java/com/thealgorithms/others/PageRank.java
+++ b/src/main/java/com/thealgorithms/others/PageRank.java
@@ -4,7 +4,7 @@
class PageRank {
- public static void main(String args[]) {
+ public static void main(String[] args) {
int nodes, i, j;
Scanner in = new Scanner(System.in);
System.out.print("Enter the Number of WebPages: ");
@@ -24,14 +24,14 @@ public static void main(String args[]) {
p.calc(nodes);
}
- public int path[][] = new int[10][10];
- public double pagerank[] = new double[10];
+ public int[][] path = new int[10][10];
+ public double[] pagerank = new double[10];
public void calc(double totalNodes) {
double InitialPageRank;
double OutgoingLinks = 0;
double DampingFactor = 0.85;
- double TempPageRank[] = new double[10];
+ double[] TempPageRank = new double[10];
int ExternalNodeNumber;
int InternalNodeNumber;
int k = 1; // For Traversing
diff --git a/src/main/java/com/thealgorithms/others/PasswordGen.java b/src/main/java/com/thealgorithms/others/PasswordGen.java
index e1de7242385b..38a20841ab74 100644
--- a/src/main/java/com/thealgorithms/others/PasswordGen.java
+++ b/src/main/java/com/thealgorithms/others/PasswordGen.java
@@ -13,7 +13,7 @@
*/
class PasswordGen {
- public static void main(String args[]) {
+ public static void main(String[] args) {
String password = generatePassword(8, 16);
System.out.print("Password: " + password);
}
diff --git a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java
index f73ce0f31238..4bd3fa69cf6e 100644
--- a/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java
+++ b/src/main/java/com/thealgorithms/others/QueueUsingTwoStacks.java
@@ -119,7 +119,7 @@ public class QueueUsingTwoStacks {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
QueueWithStack myQueue = new QueueWithStack();
myQueue.insert(1);
System.out.println(myQueue.peekBack()); // Will print 1
diff --git a/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java b/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java
index 3c1b349e70b8..bc04616634bc 100644
--- a/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java
+++ b/src/main/java/com/thealgorithms/others/RotateMatriceBy90Degree.java
@@ -29,7 +29,7 @@ public static void main(String[] args) {
sc.close();
}
- static void printMatrix(int arr[][]) {
+ static void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
@@ -44,7 +44,7 @@ static void printMatrix(int arr[][]) {
*/
class Rotate {
- static void rotate(int a[][]) {
+ static void rotate(int[][] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
diff --git a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java
index b951d9d910dd..08b0f9f40273 100644
--- a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java
+++ b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java
@@ -24,14 +24,11 @@ public static int postfixEvaluate(String exp) {
int num1 = s.pop();
String op = tokens.next();
- if (op.equals("+")) {
- s.push(num1 + num2);
- } else if (op.equals("-")) {
- s.push(num1 - num2);
- } else if (op.equals("*")) {
- s.push(num1 * num2);
- } else {
- s.push(num1 / num2);
+ switch (op) {
+ case "+" -> s.push(num1 + num2);
+ case "-" -> s.push(num1 - num2);
+ case "*" -> s.push(num1 * num2);
+ default -> s.push(num1 / num2);
}
// "+", "-", "*", "/"
}
diff --git a/src/main/java/com/thealgorithms/others/Sudoku.java b/src/main/java/com/thealgorithms/others/Sudoku.java
index 5ebe92c0c96d..574ca98370a7 100644
--- a/src/main/java/com/thealgorithms/others/Sudoku.java
+++ b/src/main/java/com/thealgorithms/others/Sudoku.java
@@ -100,7 +100,7 @@ public static void print(int[][] board, int N) {
}
// Driver Code
- public static void main(String args[]) {
+ public static void main(String[] args) {
int[][] board = new int[][] {
{ 3, 0, 6, 5, 0, 8, 4, 0, 0 },
{ 5, 2, 0, 0, 0, 0, 0, 0, 0 },
diff --git a/src/main/java/com/thealgorithms/others/ThreeSum.java b/src/main/java/com/thealgorithms/others/ThreeSum.java
index 7c9f3a1f2909..299eaf4eeae6 100644
--- a/src/main/java/com/thealgorithms/others/ThreeSum.java
+++ b/src/main/java/com/thealgorithms/others/ThreeSum.java
@@ -18,11 +18,11 @@
*/
class ThreeSum {
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Length of an array
- int a[] = new int[n];
+ int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch.java b/src/main/java/com/thealgorithms/searches/BinarySearch.java
index bc5b41580e20..1373748e0a54 100644
--- a/src/main/java/com/thealgorithms/searches/BinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/BinarySearch.java
@@ -42,10 +42,10 @@ public > int find(T[] array, T key) {
* @return the location of the key
*/
private > int search(
- T array[],
- T key,
- int left,
- int right
+ T[] array,
+ T key,
+ int left,
+ int right
) {
if (right < left) {
return -1; // this means that the key not found
diff --git a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
index 0632971b7296..f982598da875 100644
--- a/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
+++ b/src/main/java/com/thealgorithms/searches/InterpolationSearch.java
@@ -21,7 +21,7 @@ class InterpolationSearch {
* @param key is a value what shoulb be found in the array
* @return an index if the array contains the key unless -1
*/
- public int find(int array[], int key) {
+ public int find(int[] array, int key) {
// Find indexes of two corners
int start = 0, end = (array.length - 1);
diff --git a/src/main/java/com/thealgorithms/searches/KMPSearch.java b/src/main/java/com/thealgorithms/searches/KMPSearch.java
index 223bc06699ac..c9b647fd3ed7 100644
--- a/src/main/java/com/thealgorithms/searches/KMPSearch.java
+++ b/src/main/java/com/thealgorithms/searches/KMPSearch.java
@@ -8,7 +8,7 @@ int KMPSearch(String pat, String txt) {
// create lps[] that will hold the longest
// prefix suffix values for pattern
- int lps[] = new int[M];
+ int[] lps = new int[M];
int j = 0; // index for pat[]
// Preprocess the pattern (calculate lps[]
@@ -38,7 +38,7 @@ else if (i < N && pat.charAt(j) != txt.charAt(i)) {
return -1;
}
- void computeLPSArray(String pat, int M, int lps[]) {
+ void computeLPSArray(String pat, int M, int[] lps) {
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
diff --git a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
index 39f26a97dd31..1ff560049e23 100644
--- a/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/OrderAgnosticBinarySearch.java
@@ -13,7 +13,7 @@ In the while loop, we use the two pointer method (start and end) to get the midd
public class OrderAgnosticBinarySearch {
- static int BinSearchAlgo(int arr[], int start, int end, int target) {
+ static int BinSearchAlgo(int[] arr, int start, int end, int target) {
// Checking whether the given array is ascending order
boolean AscOrd = arr[start] < arr[end];
diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
index 5bcda7dd8d1f..44d38a480dd6 100644
--- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
+++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
@@ -28,9 +28,9 @@ public class SaddlebackSearch {
* @return The index(row and column) of the element if found. Else returns
* -1 -1.
*/
- private static int[] find(int arr[][], int row, int col, int key) {
+ private static int[] find(int[][] arr, int row, int col, int key) {
// array to store the answer row and column
- int ans[] = { -1, -1 };
+ int[] ans = { -1, -1 };
if (row < 0 || col >= arr[row].length) {
return ans;
}
@@ -54,7 +54,7 @@ else if (arr[row][col] > key) {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
- int arr[][];
+ int[][] arr;
int i, j, rows = sc.nextInt(), col = sc.nextInt();
arr = new int[rows][col];
for (i = 0; i < rows; i++) {
@@ -64,7 +64,7 @@ public static void main(String[] args) {
}
int ele = sc.nextInt();
// we start from bottom left corner
- int ans[] = find(arr, rows - 1, 0, ele);
+ int[] ans = find(arr, rows - 1, 0, ele);
System.out.println(ans[0] + " " + ans[1]);
sc.close();
}
diff --git a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java
index 362fef91d53a..5b305831bdfa 100644
--- a/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/SquareRootBinarySearch.java
@@ -21,7 +21,7 @@ public class SquareRootBinarySearch {
*
* @param args Command line arguments
*/
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(
"Enter a number you want to calculate square root of : "
diff --git a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java
index 9f60b31b603b..eb62555f5497 100644
--- a/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearch.java
@@ -1,7 +1,7 @@
package com.thealgorithms.searches;
import java.util.*;
public class sortOrderAgnosticBinarySearch {
- public static int find(int arr[],int key){
+ public static int find(int[] arr, int key){
int start = 0;
int end = arr.length-1;
boolean arrDescending = arr[start]>arr[end]; //checking for Array is in ascending order or descending order.
diff --git a/src/main/java/com/thealgorithms/sorts/BitonicSort.java b/src/main/java/com/thealgorithms/sorts/BitonicSort.java
index 35acaf4de1ec..414aa647eb50 100644
--- a/src/main/java/com/thealgorithms/sorts/BitonicSort.java
+++ b/src/main/java/com/thealgorithms/sorts/BitonicSort.java
@@ -8,7 +8,7 @@ public class BitonicSort {
ASCENDING or DESCENDING; if (a[i] > a[j]) agrees
with the direction, then a[i] and a[j] are
interchanged. */
- void compAndSwap(int a[], int i, int j, int dir) {
+ void compAndSwap(int[] a, int i, int j, int dir) {
if ((a[i] > a[j] && dir == 1) || (a[i] < a[j] && dir == 0)) {
// Swapping elements
int temp = a[i];
@@ -22,7 +22,7 @@ void compAndSwap(int a[], int i, int j, int dir) {
(means dir=0). The sequence to be sorted starts at
index position low, the parameter cnt is the number
of elements to be sorted.*/
- void bitonicMerge(int a[], int low, int cnt, int dir) {
+ void bitonicMerge(int[] a, int low, int cnt, int dir) {
if (cnt > 1) {
int k = cnt / 2;
for (int i = low; i < low + k; i++) {
@@ -37,7 +37,7 @@ void bitonicMerge(int a[], int low, int cnt, int dir) {
recursively sorting its two halves in opposite sorting
orders, and then calls bitonicMerge to make them in
the same order */
- void bitonicSort(int a[], int low, int cnt, int dir) {
+ void bitonicSort(int[] a, int low, int cnt, int dir) {
if (cnt > 1) {
int k = cnt / 2;
@@ -55,12 +55,12 @@ void bitonicSort(int a[], int low, int cnt, int dir) {
/*Caller of bitonicSort for sorting the entire array
of length N in ASCENDING order */
- void sort(int a[], int N, int up) {
+ void sort(int[] a, int N, int up) {
bitonicSort(a, 0, N, up);
}
/* A utility function to print array of size n */
- static void printArray(int arr[]) {
+ static void printArray(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
@@ -68,8 +68,8 @@ static void printArray(int arr[]) {
System.out.println();
}
- public static void main(String args[]) {
- int a[] = { 3, 7, 4, 8, 6, 2, 1, 5 };
+ public static void main(String[] args) {
+ int[] a = { 3, 7, 4, 8, 6, 2, 1, 5 };
int up = 1;
BitonicSort ob = new BitonicSort();
ob.sort(a, a.length, up);
diff --git a/src/main/java/com/thealgorithms/sorts/CycleSort.java b/src/main/java/com/thealgorithms/sorts/CycleSort.java
index 6d21888e4135..0852abfaae24 100644
--- a/src/main/java/com/thealgorithms/sorts/CycleSort.java
+++ b/src/main/java/com/thealgorithms/sorts/CycleSort.java
@@ -74,7 +74,7 @@ private > T replace(T[] arr, int pos, T item) {
}
public static void main(String[] args) {
- Integer arr[] = {
+ Integer[] arr = {
4,
23,
6,
diff --git a/src/main/java/com/thealgorithms/sorts/DNFSort.java b/src/main/java/com/thealgorithms/sorts/DNFSort.java
index 912b673409e9..4c4520c63cab 100644
--- a/src/main/java/com/thealgorithms/sorts/DNFSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DNFSort.java
@@ -4,7 +4,7 @@ public class DNFSort {
// Sort the input array, the array is assumed to
// have values in {0, 1, 2}
- static void sort012(int a[], int arr_size) {
+ static void sort012(int[] a, int arr_size) {
int low = 0;
int high = arr_size - 1;
int mid = 0, temp = 0;
@@ -35,7 +35,7 @@ static void sort012(int a[], int arr_size) {
}
/* Utility function to print array arr[] */
- static void printArray(int arr[], int arr_size) {
+ static void printArray(int[] arr, int arr_size) {
for (int i = 0; i < arr_size; i++) {
System.out.print(arr[i] + " ");
}
@@ -44,7 +44,7 @@ static void printArray(int arr[], int arr_size) {
/*Driver function to check for above functions*/
public static void main(String[] args) {
- int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
+ int[] arr = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 };
int arr_size = arr.length;
sort012(arr, arr_size);
System.out.println("Array after seggregation ");
diff --git a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
index 9d6176c2d74f..69a09e67532d 100644
--- a/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DualPivotQuickSort.java
@@ -96,7 +96,7 @@ private static > void swap(T[] array, int left, int righ
* @param args the command line arguments
*/
public static void main(String[] args) {
- Integer array[] = { 24, 8, -42, 75, -29, -77, 38, 57 };
+ Integer[] array = { 24, 8, -42, 75, -29, -77, 38, 57 };
DualPivotQuickSort dualPivotQuickSort = new DualPivotQuickSort();
dualPivotQuickSort.sort(array);
for (int i = 0; i < array.length; i++) {
diff --git a/src/main/java/com/thealgorithms/sorts/LinkListSort.java b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
index 3c9ba1b7d17d..07f03cca072d 100644
--- a/src/main/java/com/thealgorithms/sorts/LinkListSort.java
+++ b/src/main/java/com/thealgorithms/sorts/LinkListSort.java
@@ -10,12 +10,12 @@
public class LinkListSort {
- public static boolean isSorted(int p[], int option) {
+ public static boolean isSorted(int[] p, int option) {
try (Scanner sc = new Scanner(System.in)) {
}
- int a[] = p;
+ int[] a = p;
// Array is taken as input from test class
- int b[] = p;
+ int[] b = p;
// array similar to a
int ch = option;
// Choice is choosed as any number from 1 to 3 (So the linked list will be
@@ -106,7 +106,7 @@ public static boolean isSorted(int p[], int option) {
return false;
}
- boolean compare(int a[], int b[]) {
+ boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
@@ -137,7 +137,7 @@ class Node {
class Task {
- static int a[];
+ static int[] a;
public Node sortByMergeSort(Node head) {
if (head == null || head.next == null)
@@ -171,7 +171,7 @@ int count(Node head) {
// It will return a integer type value denoting the number of nodes present
}
- void task(int n[], int i, int j) {
+ void task(int[] n, int i, int j) {
if (i < j) {
int m = (i + j) / 2;
task(n, i, m);
@@ -181,9 +181,9 @@ void task(int n[], int i, int j) {
}
}
- void task1(int n[], int s, int m, int e) {
+ void task1(int[] n, int s, int m, int e) {
int i = s, k = 0, j = m + 1;
- int b[] = new int[e - s + 1];
+ int[] b = new int[e - s + 1];
while (i <= m && j <= e) {
if (n[j] >= n[i])
b[k++] = n[i++];
@@ -210,7 +210,7 @@ public Node sortByInsertionSort(Node head) {
if (head == null || head.next == null)
return head;
int c = count(head);
- int a[] = new int[c];
+ int[] a = new int[c];
// Array of size c is created
a[0] = head.val;
int i;
@@ -247,7 +247,7 @@ static int count(Node head) {
class Task2 {
- static int a[];
+ static int[] a;
public Node sortByHeapSort(Node head) {
if (head == null || head.next == null)
@@ -280,7 +280,7 @@ int count(Node head) {
// It will return a integer type value denoting the number of nodes present
}
- void task(int n[]) {
+ void task(int[] n) {
int k = n.length;
for (int i = k / 2 - 1; i >= 0; i--) {
task1(n, k, i);
@@ -294,7 +294,7 @@ void task(int n[]) {
}
}
- void task1(int n[], int k, int i) {
+ void task1(int[] n, int k, int i) {
int p = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
diff --git a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
index 3953b5ed1b8c..c06528608278 100644
--- a/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
+++ b/src/main/java/com/thealgorithms/sorts/MergeSortNoExtraSpace.java
@@ -8,12 +8,12 @@
*/
public class MergeSortNoExtraSpace {
- public static void call_merge_sort(int a[], int n) {
+ public static void call_merge_sort(int[] a, int n) {
int maxele = Arrays.stream(a).max().getAsInt() + 1;
merge_sort(a, 0, n - 1, maxele);
}
- public static void merge_sort(int a[], int start, int end, int maxele) { //this function divides the array into 2 halves
+ public static void merge_sort(int[] a, int start, int end, int maxele) { //this function divides the array into 2 halves
if (start < end) {
int mid = (start + end) / 2;
merge_sort(a, start, mid, maxele);
@@ -23,11 +23,11 @@ public static void merge_sort(int a[], int start, int end, int maxele) { //this
}
public static void implement_merge_sort(
- int a[],
- int start,
- int mid,
- int end,
- int maxele
+ int[] a,
+ int start,
+ int mid,
+ int end,
+ int maxele
) { //implementation of mergesort
int i = start;
int j = mid + 1;
@@ -58,11 +58,11 @@ public static void implement_merge_sort(
}
}
- public static void main(String args[]) {
+ public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("Enter array size");
int n = inp.nextInt();
- int a[] = new int[n];
+ int[] a = new int[n];
System.out.println("Enter array elements");
for (int i = 0; i < n; i++) {
a[i] = inp.nextInt();
diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java
index dcde8647f78d..5a9487da678d 100644
--- a/src/main/java/com/thealgorithms/strings/Anagrams.java
+++ b/src/main/java/com/thealgorithms/strings/Anagrams.java
@@ -50,8 +50,8 @@ boolean approach1(String s, String t) {
if (s.length() != t.length()) {
return false;
} else {
- char c[] = s.toCharArray();
- char d[] = t.toCharArray();
+ char[] c = s.toCharArray();
+ char[] d = t.toCharArray();
Arrays.sort(c);
Arrays.sort(
d
@@ -65,8 +65,8 @@ boolean approach2(String a, String b) {
if (a.length() != b.length()) {
return false;
} else {
- int m[] = new int[26];
- int n[] = new int[26];
+ int[] m = new int[26];
+ int[] n = new int[26];
for (char c : a.toCharArray()) {
m[c - 'a']++;
}
@@ -90,8 +90,8 @@ boolean approach3(String s, String t) {
}
// 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[] a = new int[26];
+ int[] b = new int[26];
int k = s.length();
for (int i = 0; i < k; i++) {
a[s.charAt(i) - 'a']++;
diff --git a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
index 59ba954ef440..fcdc310d4a61 100644
--- a/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
+++ b/src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
@@ -44,7 +44,7 @@ protected static void generateNumberToCharMap() {
// Driver code
public static void main(String[] args) {
- int number[] = { 2, 3, 4 };
+ int[] number = { 2, 3, 4 };
printWords(number);
}
}
diff --git a/src/main/java/com/thealgorithms/strings/MyAtoi.java b/src/main/java/com/thealgorithms/strings/MyAtoi.java
index 0770f66c7313..327cc4c19897 100644
--- a/src/main/java/com/thealgorithms/strings/MyAtoi.java
+++ b/src/main/java/com/thealgorithms/strings/MyAtoi.java
@@ -22,18 +22,8 @@ public static int myAtoi(String s) {
number = "0";
break;
}
- switch (ch) {
- case '0' -> number += ch;
- case '1' -> number += ch;
- case '2' -> number += ch;
- case '3' -> number += ch;
- case '4' -> number += ch;
- case '5' -> number += ch;
- case '6' -> number += ch;
- case '7' -> number += ch;
- case '8' -> number += ch;
- case '9' -> number += ch;
- }
+ if(ch >= '0' && ch <= '9')
+ number += ch;
} else if (ch == '-' && !isDigit) {
number += "0";
negative = true;
diff --git a/src/main/java/com/thealgorithms/strings/WordLadder.java b/src/main/java/com/thealgorithms/strings/WordLadder.java
index a08d3d586fdf..c4d8aeb9135d 100644
--- a/src/main/java/com/thealgorithms/strings/WordLadder.java
+++ b/src/main/java/com/thealgorithms/strings/WordLadder.java
@@ -48,10 +48,7 @@ class WordLadder {
* if the endword is there. Otherwise, will return the length as 0.
*/
public static int ladderLength(String beginWord, String endWord, List wordList) {
- HashSet set = new HashSet();
- for (String word : wordList) {
- set.add(word);
- }
+ HashSet set = new HashSet(wordList);
if (!set.contains(endWord)) {
return 0;
diff --git a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java
index c2a1c4db750f..139cd1070676 100644
--- a/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java
+++ b/src/test/java/com/thealgorithms/backtracking/AllPathsFromSourceToTargetTest.java
@@ -9,7 +9,7 @@ public class AllPathsFromSourceToTargetTest {
@Test
void testForFirstCase() {
int vertices = 4;
- int a[][] = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}};
+ int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3}};
int source = 2;
int destination = 3;
List> list2 = List.of(List.of(2, 0, 1, 3),List.of(2, 0, 3),List.of(2, 1, 3));
@@ -21,7 +21,7 @@ void testForFirstCase() {
@Test
void testForSecondCase() {
int vertices = 5;
- int a[][] = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}};
+ int[][] a = {{0,1},{0,2},{0,3},{2,0},{2,1},{1,3},{1,4},{3,4},{2,4}};
int source = 0;
int destination = 4;
List> list2 = List.of(List.of(0, 1, 3, 4),List.of(0, 1, 4),List.of(0, 2, 1, 3, 4),List.of(0, 2, 1, 4),List.of(0, 2, 4),List.of(0, 3, 4));
@@ -33,7 +33,7 @@ void testForSecondCase() {
@Test
void testForThirdCase() {
int vertices = 6;
- int a[][] = {{1,0},{2,3},{0,4},{1,5},{4,3},{0,2},{0,3},{1,2},{0,5},{3,4},{2,5},{2,4}};
+ int[][] a = {{1,0},{2,3},{0,4},{1,5},{4,3},{0,2},{0,3},{1,2},{0,5},{3,4},{2,5},{2,4}};
int source = 1;
int destination = 5;
List> list2 = List.of(List.of(1, 0, 2, 5),List.of(1, 0, 5),List.of(1, 5),List.of(1, 2, 5));
@@ -45,7 +45,7 @@ void testForThirdCase() {
@Test
void testForFourthcase() {
int vertices = 3;
- int a[][] = {{0,1},{0,2},{1,2}};
+ int[][] a = {{0,1},{0,2},{1,2}};
int source = 0;
int destination = 2;
List> list2 = List.of(List.of(0, 1, 2),List.of(0, 2));
diff --git a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java
index 437ddb2333a8..b46c7e0fe832 100644
--- a/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java
+++ b/src/test/java/com/thealgorithms/backtracking/FloodFillTest.java
@@ -8,8 +8,8 @@ class FloodFillTest {
@Test
void testForEmptyImage() {
- int image[][] = {};
- int expected[][] = {};
+ int[][] image = {};
+ int[][] expected = {};
FloodFill.floodFill(image, 4, 5, 3, 2);
assertArrayEquals(expected, image);
@@ -17,8 +17,8 @@ void testForEmptyImage() {
@Test
void testForSingleElementImage() {
- int image[][] = { { 1 } };
- int expected[][] = { { 3 } };
+ int[][] image = { { 1 } };
+ int[][] expected = { { 3 } };
FloodFill.floodFill(image, 0, 0, 3, 1);
assertArrayEquals(expected, image);
@@ -26,7 +26,7 @@ void testForSingleElementImage() {
@Test
void testForImageOne() {
- int image[][] = {
+ int[][] image = {
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 3, 3, 3, 3, 0, 0 },
{ 0, 3, 1, 1, 5, 0, 0 },
@@ -36,7 +36,7 @@ void testForImageOne() {
{ 0, 0, 0, 3, 3, 3, 3 },
};
- int expected[][] = {
+ int[][] expected = {
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 3, 3, 3, 3, 0, 0 },
{ 0, 3, 2, 2, 5, 0, 0 },
@@ -52,7 +52,7 @@ void testForImageOne() {
@Test
void testForImageTwo() {
- int image[][] = {
+ int[][] image = {
{ 0, 0, 1, 1, 0, 0, 0 },
{ 1, 1, 3, 3, 3, 0, 0 },
{ 1, 3, 1, 1, 5, 0, 0 },
@@ -62,7 +62,7 @@ void testForImageTwo() {
{ 0, 0, 0, 1, 3, 1, 3 },
};
- int expected[][] = {
+ int[][] expected = {
{ 0, 0, 2, 2, 0, 0, 0 },
{ 2, 2, 3, 3, 3, 0, 0 },
{ 2, 3, 2, 2, 5, 0, 0 },
@@ -78,13 +78,13 @@ void testForImageTwo() {
@Test
void testForImageThree() {
- int image[][] = {
+ int[][] image = {
{ 1, 1, 2, 3, 1, 1, 1 },
{ 1, 0, 0, 1, 0, 0, 1 },
{ 1, 1, 1, 0, 3, 1, 2 },
};
- int expected[][] = {
+ int[][] expected = {
{ 4, 4, 2, 3, 4, 4, 4 },
{ 4, 0, 0, 4, 0, 0, 4 },
{ 4, 4, 4, 0, 3, 4, 2 },
diff --git a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java
index 97dc4d1b8e42..35f66f92ead7 100644
--- a/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java
+++ b/src/test/java/com/thealgorithms/backtracking/MazeRecursionTest.java
@@ -45,7 +45,7 @@ public void testMaze() {
MazeRecursion.setWay(map, 1, 1);
MazeRecursion.setWay2(map2, 1, 1);
- int expectedMap[][] = new int[][] {
+ int[][] expectedMap = new int[][] {
{ 1, 1, 1, 1, 1, 1, 1 },
{ 1, 2, 0, 0, 0, 0, 1 },
{ 1, 2, 2, 2, 0, 0, 1 },
@@ -56,7 +56,7 @@ public void testMaze() {
{ 1, 1, 1, 1, 1, 1, 1 },
};
- int expectedMap2[][] = new int[][] {
+ int[][] expectedMap2 = new int[][] {
{ 1, 1, 1, 1, 1, 1, 1 },
{ 1, 2, 2, 2, 2, 2, 1 },
{ 1, 0, 0, 0, 0, 2, 1 },
diff --git a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java
index 6bbd1c4059cf..29125efe5fbb 100644
--- a/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java
+++ b/src/test/java/com/thealgorithms/maths/AutomorphicNumberTest.java
@@ -7,8 +7,8 @@ public class AutomorphicNumberTest {
@Test
void testAutomorphicNumber() {
- int trueTestCases[] = { 0, 1, 25, 625, 12890625};
- int falseTestCases[] = { -5, 2, 26, 1234 };
+ int[] trueTestCases = { 0, 1, 25, 625, 12890625};
+ int[] falseTestCases = { -5, 2, 26, 1234 };
for (Integer n : trueTestCases) {
assertTrue(AutomorphicNumber.isAutomorphic(n));
assertTrue(AutomorphicNumber.isAutomorphic2(n));
diff --git a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java
index 92512e99e730..adaccff0a40d 100644
--- a/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java
+++ b/src/test/java/com/thealgorithms/maths/PerfectNumberTest.java
@@ -7,8 +7,8 @@ class PerfectNumberTest {
@Test
public void perfectNumber() {
- int trueTestCases[] = { 6, 28, 496, 8128, 33550336 };
- int falseTestCases[] = { -6, 0, 1, 9, 123 };
+ int[] trueTestCases = { 6, 28, 496, 8128, 33550336 };
+ int[] falseTestCases = { -6, 0, 1, 9, 123 };
for (Integer n : trueTestCases) {
assertTrue(PerfectNumber.isPerfectNumber(n));
assertTrue(PerfectNumber.isPerfectNumber2(n));
diff --git a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
index 00cc1f534191..89fc9b32e30d 100644
--- a/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
+++ b/src/test/java/com/thealgorithms/others/CalculateMaxOfMinTest.java
@@ -9,49 +9,49 @@ public class CalculateMaxOfMinTest {
@Test
void testForOneElement() {
- int a[] = { 10, 20, 30, 50, 10, 70, 30 };
+ 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[] 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[] 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[] a = { 70, 60, 50, 40, 30, 20 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 70);
}
@Test
void testForFiveElements() {
- int a[] = { 50 };
+ int[] a = { 50 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == 50);
}
@Test
void testForSixElements() {
- int a[] = { 1, 4, 7, 9, 2, 4, 6 };
+ 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[] a = { -1, -5, -7, -9, -12, -14 };
int k = CalculateMaxOfMin.calculateMaxOfMin(a);
assertTrue(k == -1);
}
diff --git a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
index 681573bb7eca..e30ffd423585 100644
--- a/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
+++ b/src/test/java/com/thealgorithms/others/CountFriendsPairingTest.java
@@ -9,49 +9,49 @@ public class CountFriendsPairingTest {
@Test
void testForOneElement() {
- int a[] = { 1, 2, 2 };
+ int[] a = { 1, 2, 2 };
assertTrue(CountFriendsPairing.countFriendsPairing(3, a));
}
@Test
void testForTwoElements() {
- int a[] = { 1, 2, 2, 3 };
+ int[] a = { 1, 2, 2, 3 };
assertTrue(CountFriendsPairing.countFriendsPairing(4, a));
}
@Test
void testForThreeElements() {
- int a[] = { 1, 2, 2, 3, 3 };
+ int[] a = { 1, 2, 2, 3, 3 };
assertTrue(CountFriendsPairing.countFriendsPairing(5, a));
}
@Test
void testForFourElements() {
- int a[] = { 1, 2, 2, 3, 3, 4 };
+ 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 };
+ 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 };
+ 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 };
+ 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 };
+ int[] a = { 1, 2, 2, 3, 3, 4, 4, 4, 5, 5 };
assertTrue(CountFriendsPairing.countFriendsPairing(10, a));
}
}
diff --git a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java
index d740f01cc942..74ca9a3efb75 100644
--- a/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java
+++ b/src/test/java/com/thealgorithms/others/KadaneAlogrithmTest.java
@@ -9,49 +9,49 @@ public class KadaneAlogrithmTest {
@Test
void testForOneElement() {
- int a[] = { -1 };
+ int[] a = { -1 };
assertTrue(KadaneAlgorithm.max_Sum(a, -1));
}
@Test
void testForTwoElements() {
- int a[] = { -2, 1 };
+ int[] a = { -2, 1 };
assertTrue(KadaneAlgorithm.max_Sum(a, 1));
}
@Test
void testForThreeElements() {
- int a[] = { 5, 3, 12 };
+ int[] a = { 5, 3, 12 };
assertTrue(KadaneAlgorithm.max_Sum(a, 20));
}
@Test
void testForFourElements() {
- int a[] = { -1, -3, -7, -4 };
+ int[] a = { -1, -3, -7, -4 };
assertTrue(KadaneAlgorithm.max_Sum(a, -1));
}
@Test
void testForFiveElements() {
- int a[] = { 4, 5, 3, 0, 2 };
+ int[] a = { 4, 5, 3, 0, 2 };
assertTrue(KadaneAlgorithm.max_Sum(a, 14));
}
@Test
void testForSixElements() {
- int a[] = { -43, -45, 47, 12, 87, -13 };
+ int[] a = { -43, -45, 47, 12, 87, -13 };
assertTrue(KadaneAlgorithm.max_Sum(a, 146));
}
@Test
void testForSevenElements() {
- int a[] = { 9, 8, 2, 23, 13, 6, 7 };
+ int[] a = { 9, 8, 2, 23, 13, 6, 7 };
assertTrue(KadaneAlgorithm.max_Sum(a, 68));
}
@Test
void testForEightElements() {
- int a[] = { 9, -5, -5, -2, 4, 5, 0, 1 };
+ int[] a = { 9, -5, -5, -2, 4, 5, 0, 1 };
assertTrue(KadaneAlgorithm.max_Sum(a, 10));
}
}
diff --git a/src/test/java/com/thealgorithms/others/LinkListSortTest.java b/src/test/java/com/thealgorithms/others/LinkListSortTest.java
index f16c48dd10c4..7c6da59cb896 100644
--- a/src/test/java/com/thealgorithms/others/LinkListSortTest.java
+++ b/src/test/java/com/thealgorithms/others/LinkListSortTest.java
@@ -9,49 +9,49 @@ public class LinkListSortTest {
@Test
void testForOneElement() {
- int a[] = { 56 };
+ int[] a = { 56 };
assertTrue(LinkListSort.isSorted(a, 2));
}
@Test
void testForTwoElements() {
- int a[] = { 6, 4 };
+ int[] a = { 6, 4 };
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForThreeElements() {
- int a[] = { 875, 253, 12 };
+ int[] a = { 875, 253, 12 };
assertTrue(LinkListSort.isSorted(a, 3));
}
@Test
void testForFourElements() {
- int a[] = { 86, 32, 87, 13 };
+ int[] a = { 86, 32, 87, 13 };
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForFiveElements() {
- int a[] = { 6, 5, 3, 0, 9 };
+ int[] a = { 6, 5, 3, 0, 9 };
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForSixElements() {
- int a[] = { 9, 65, 432, 32, 47, 327 };
+ int[] a = { 9, 65, 432, 32, 47, 327 };
assertTrue(LinkListSort.isSorted(a, 3));
}
@Test
void testForSevenElements() {
- int a[] = { 6, 4, 2, 1, 3, 6, 7 };
+ int[] a = { 6, 4, 2, 1, 3, 6, 7 };
assertTrue(LinkListSort.isSorted(a, 1));
}
@Test
void testForEightElements() {
- int a[] = { 123, 234, 145, 764, 322, 367, 768, 34 };
+ int[] a = { 123, 234, 145, 764, 322, 367, 768, 34 };
assertTrue(LinkListSort.isSorted(a, 2));
}
}
diff --git a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java
index 37f1aa403dcb..804cfc3e9dba 100644
--- a/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java
+++ b/src/test/java/com/thealgorithms/searches/sortOrderAgnosticBinarySearchTest.java
@@ -8,7 +8,7 @@ public class sortOrderAgnosticBinarySearchTest{
@Test
public void testAscending(){
- int arr[] = {1,2,3,4,5};// for ascending order.
+ int[] arr = {1,2,3,4,5};// for ascending order.
int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 1;
@@ -17,7 +17,7 @@ public void testAscending(){
@Test
public void testDescending(){
- int arr[] = {5,4,3,2,1};// for descending order.
+ int[] arr = {5,4,3,2,1};// for descending order.
int target = 2;
int ans=sortOrderAgnosticBinarySearch.find(arr, target);
int excepted = 3;
From 1551b8f50ba485b5a7d34fe9ed1fbf650134fb9f Mon Sep 17 00:00:00 2001
From: LOne2three <39175022+LOne2three@users.noreply.github.com>
Date: Wed, 19 Apr 2023 09:12:30 +0100
Subject: [PATCH 0021/1457] Add line sweep algorithm (#4157)
---
.../com/thealgorithms/others/LineSweep.java | 51 +++++++++++++++++++
.../thealgorithms/others/LineSweepTest.java | 29 +++++++++++
2 files changed, 80 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/others/LineSweep.java
create mode 100644 src/test/java/com/thealgorithms/others/LineSweepTest.java
diff --git a/src/main/java/com/thealgorithms/others/LineSweep.java b/src/main/java/com/thealgorithms/others/LineSweep.java
new file mode 100644
index 000000000000..f9db1f742fe5
--- /dev/null
+++ b/src/main/java/com/thealgorithms/others/LineSweep.java
@@ -0,0 +1,51 @@
+package com.thealgorithms.others;
+import java.util.Arrays;
+import java.util.Comparator;
+
+/* Line Sweep algorithm can be used to solve range problems by first sorting the list of ranges
+ * by the start value of the range in non-decreasing order and doing a "sweep" through the number
+ * line(x-axis) by incrementing the start point by 1 and decrementing the end point+1 by 1 on the
+ * number line.
+ * An overlapping range is defined as (StartA <= EndB) AND (EndA >= StartB)
+ * References
+ * https://en.wikipedia.org/wiki/Sweep_line_algorithm
+ * https://en.wikipedia.org/wiki/De_Morgan%27s_laws>
+ */
+public class LineSweep {
+
+ /** Find Maximum end point
+ * param = ranges : Array of range[start,end]
+ * return Maximum Endpoint
+ */
+ public static int FindMaximumEndPoint (int[][]ranges){
+ Arrays.sort(ranges, Comparator.comparingInt(a->a[1]));
+ return ranges[ranges.length-1][1];
+ }
+
+ /** Find if any ranges overlap
+ * param = ranges : Array of range[start,end]
+ * return true if overlap exists false otherwise.
+ */
+ public static boolean isOverlap(int[][] ranges) {
+
+ int maximumEndPoint = FindMaximumEndPoint(ranges);
+ Arrays.sort(ranges, Comparator.comparingInt(a->a[0]));
+ int[] numberLine = new int[maximumEndPoint+2];
+ for (int[] range : ranges) {
+
+ int start = range[0];
+ int end = range[1];
+
+ numberLine[start] += 1;
+ numberLine[end+1] -= 1;
+ }
+
+ int current = 0;
+ int overlaps = 0;
+ for (int num : numberLine) {
+ current += num;
+ overlaps = Math.max(overlaps, current);
+ }
+ return overlaps >1 ;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/others/LineSweepTest.java b/src/test/java/com/thealgorithms/others/LineSweepTest.java
new file mode 100644
index 000000000000..428556d404c5
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/LineSweepTest.java
@@ -0,0 +1,29 @@
+package com.thealgorithms.others;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
+public class LineSweepTest {
+
+
+ @Test
+ void testForOverlap(){
+ int[][]arr = {{0,10},{7,20},{15,24}};
+ assertTrue(LineSweep.isOverlap(arr));
+ }
+
+ @Test
+ void testForNoOverlap(){
+ int[][]arr = {{0,10},{11,20},{21,24}};
+ assertFalse(LineSweep.isOverlap(arr));
+ }
+ @Test
+ void testForOverlapWhenEndAEqualsStartBAndViceVersa(){
+ int[][]arr = {{0,10},{10,20},{21,24}};
+ assertTrue(LineSweep.isOverlap(arr));
+ }
+ @Test
+ void testForMaximumEndPoint(){
+ int[][]arr = {{10,20},{1,100},{14,16},{1,8}};
+ assertEquals(100,LineSweep.FindMaximumEndPoint(arr));
+ }
+
+}
From c01a382d94f0f9971fb2be9d67653d21e21b98ba Mon Sep 17 00:00:00 2001
From: Albina Gimaletdinova
Date: Fri, 21 Apr 2023 11:41:24 +0300
Subject: [PATCH 0022/1457] Remove redundant tree traversals (#4161)
---
.../trees/LevelOrderTraversal.java | 16 ++-
.../trees/LevelOrderTraversalHelper.java | 43 -------
.../datastructures/trees/TreeTraversal.java | 120 ------------------
3 files changed, 15 insertions(+), 164 deletions(-)
delete mode 100644 src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java
delete mode 100644 src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java
index 4b86d644e29c..e61085cf4def 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java
@@ -7,7 +7,7 @@
public class LevelOrderTraversal {
- static List> traverse(BinaryTree.Node root) {
+ public static List> traverse(BinaryTree.Node root) {
if (root == null) {
return List.of();
}
@@ -35,4 +35,18 @@ static List> traverse(BinaryTree.Node root) {
}
return result;
}
+
+ /* Print nodes at the given level */
+ public static void printGivenLevel(BinaryTree.Node root, int level) {
+ if (root == null) {
+ System.out.println("Root node must not be null! Exiting.");
+ return;
+ }
+ if (level == 1) {
+ System.out.print(root.data + " ");
+ } else if (level > 1) {
+ printGivenLevel(root.left, level - 1);
+ printGivenLevel(root.right, level - 1);
+ }
+ }
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java b/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java
deleted file mode 100644
index 8fa3dc72bb8c..000000000000
--- a/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package com.thealgorithms.datastructures.trees;
-
-public class LevelOrderTraversalHelper {
- /* function to print level order traversal of tree*/
- public static void printLevelOrder(BinaryTree.Node root) {
- if (root == null) {
- System.out.println("Root node must not be null! Exiting.");
- return;
- }
-
- int h = height(root);
- int i;
- for (i = 1; i <= h; i++) {
- printGivenLevel(root, i);
- }
- }
-
- /* Compute the "height" of a tree -- the number of
- nodes along the longest path from the root node
- down to the farthest leaf node.*/
- private static int height(BinaryTree.Node root) {
- if (root == null) {
- return 0;
- } else {
- //return the height of larger subtree
- return Math.max(height(root.left), height(root.right)) + 1;
- }
- }
-
- /* Print nodes at the given level */
- public static void printGivenLevel(BinaryTree.Node root, int level) {
- if (root == null) {
- System.out.println("Root node must not be null! Exiting.");
- return;
- }
- if (level == 1) {
- System.out.print(root.data + " ");
- } else if (level > 1) {
- printGivenLevel(root.left, level - 1);
- printGivenLevel(root.right, level - 1);
- }
- }
-}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java
deleted file mode 100644
index 586f740b1b14..000000000000
--- a/src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package com.thealgorithms.datastructures.trees;
-
-import java.util.LinkedList;
-
-/**
- * @author Varun Upadhyay (https://github.com/varunu28)
- */
-// Driver Program
-public class TreeTraversal {
-
- public static void main(String[] args) {
- Node tree = new Node(5);
- tree.insert(3);
- tree.insert(2);
- tree.insert(7);
- tree.insert(4);
- tree.insert(6);
- tree.insert(8);
-
- // Prints 5 3 2 4 7 6 8
- System.out.println("Pre order traversal:");
- tree.printPreOrder();
- System.out.println();
- // Prints 2 3 4 5 6 7 8
- System.out.println("In order traversal:");
- tree.printInOrder();
- System.out.println();
- // Prints 2 4 3 6 8 7 5
- System.out.println("Post order traversal:");
- tree.printPostOrder();
- System.out.println();
- // Prints 5 3 7 2 4 6 8
- System.out.println("Level order traversal:");
- tree.printLevelOrder();
- System.out.println();
- }
-}
-
-/**
- * The Node class which initializes a Node of a tree Consists of all 4 traversal
- * methods: printInOrder, printPostOrder, printPreOrder & printLevelOrder
- * printInOrder: LEFT -> ROOT -> RIGHT printPreOrder: ROOT -> LEFT -> RIGHT
- * printPostOrder: LEFT -> RIGHT -> ROOT printLevelOrder: Prints by level
- * (starting at root), from left to right.
- */
-class Node {
-
- Node left, right;
- int data;
-
- public Node(int data) {
- this.data = data;
- }
-
- public void insert(int value) {
- if (value < data) {
- if (left == null) {
- left = new Node(value);
- } else {
- left.insert(value);
- }
- } else {
- if (right == null) {
- right = new Node(value);
- } else {
- right.insert(value);
- }
- }
- }
-
- public void printInOrder() {
- if (left != null) {
- left.printInOrder();
- }
- System.out.print(data + " ");
- if (right != null) {
- right.printInOrder();
- }
- }
-
- public void printPreOrder() {
- System.out.print(data + " ");
- if (left != null) {
- left.printPreOrder();
- }
- if (right != null) {
- right.printPreOrder();
- }
- }
-
- public void printPostOrder() {
- if (left != null) {
- left.printPostOrder();
- }
- if (right != null) {
- right.printPostOrder();
- }
- System.out.print(data + " ");
- }
-
- /**
- * O(n) time algorithm. Uses O(n) space to store nodes in a queue to aid in
- * traversal.
- */
- public void printLevelOrder() {
- LinkedList queue = new LinkedList<>();
- queue.add(this);
- while (queue.size() > 0) {
- Node head = queue.remove();
- System.out.print(head.data + " ");
- // Add children of recently-printed node to queue, if they exist.
- if (head.left != null) {
- queue.add(head.left);
- }
- if (head.right != null) {
- queue.add(head.right);
- }
- }
- }
-}
From 4c18e60671adebb2b8236024ad50f14367455e2a Mon Sep 17 00:00:00 2001
From: Albina Gimaletdinova
Date: Sat, 22 Apr 2023 10:53:12 +0300
Subject: [PATCH 0023/1457] Refactor BSTFromSortedArray (#4162)
---
.../trees/BSTFromSortedArray.java | 33 +++++++++++++
...ot.java => CheckBinaryTreeIsValidBST.java} | 2 +-
.../trees/CreateBSTFromSortedArray.java | 44 -----------------
.../trees/BSTFromSortedArrayTest.java | 47 +++++++++++++++++++
...ava => CheckBinaryTreeIsValidBSTTest.java} | 12 ++---
5 files changed, 87 insertions(+), 51 deletions(-)
create mode 100644 src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
rename src/main/java/com/thealgorithms/datastructures/trees/{ValidBSTOrNot.java => CheckBinaryTreeIsValidBST.java} (96%)
delete mode 100644 src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java
create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java
rename src/test/java/com/thealgorithms/datastructures/trees/{ValidBSTOrNotTest.java => CheckBinaryTreeIsValidBSTTest.java} (79%)
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
new file mode 100644
index 000000000000..9066a6f231be
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
@@ -0,0 +1,33 @@
+package com.thealgorithms.datastructures.trees;
+
+import com.thealgorithms.datastructures.trees.BinaryTree.Node;
+
+/**
+ * Given a sorted array. Create a balanced binary search tree from it.
+ *
+ * Steps: 1. Find the middle element of array. This will act as root 2. Use the
+ * left half recursively to create left subtree 3. Use the right half
+ * recursively to create right subtree
+ */
+public class BSTFromSortedArray {
+ public static Node createBST(int[] array) {
+ if (array == null || array.length == 0) {
+ return null;
+ }
+ return createBST(array, 0, array.length - 1);
+ }
+
+ private static Node createBST(int[] array, int startIdx, int endIdx) {
+ // No element left.
+ if (startIdx > endIdx) {
+ return null;
+ }
+ int mid = startIdx + (endIdx - startIdx) / 2;
+
+ // middle element will be the root
+ Node root = new Node(array[mid]);
+ root.left = createBST(array, startIdx, mid - 1);
+ root.right = createBST(array, mid + 1, endIdx);
+ return root;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
similarity index 96%
rename from src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java
rename to src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
index 65c4e1070da7..13246944737c 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
@@ -8,7 +8,7 @@
* where 'min' and 'max' values represent the child nodes (left, right).
* 2. The smallest possible node value is Integer.MIN_VALUE, the biggest - Integer.MAX_VALUE.
*/
-public class ValidBSTOrNot {
+public class CheckBinaryTreeIsValidBST {
public static boolean isBST(BinaryTree.Node root) {
return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java
deleted file mode 100644
index e43b8c28a924..000000000000
--- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.thealgorithms.datastructures.trees;
-
-import com.thealgorithms.datastructures.trees.BinaryTree.Node;
-
-/**
- * Given a sorted array. Create a balanced binary search tree from it.
- *
- * Steps: 1. Find the middle element of array. This will act as root 2. Use the
- * left half recursively to create left subtree 3. Use the right half
- * recursively to create right subtree
- */
-public class CreateBSTFromSortedArray {
-
- public static void main(String[] args) {
- test(new int[] {});
- test(new int[] { 1, 2, 3 });
- test(new int[] { 1, 2, 3, 4, 5 });
- test(new int[] { 1, 2, 3, 4, 5, 6, 7 });
- }
-
- private static void test(int[] array) {
- BinaryTree root = new BinaryTree(createBst(array, 0, array.length - 1));
- System.out.println("\n\nPreorder Traversal: ");
- root.preOrder(root.getRoot());
- System.out.println("\nInorder Traversal: ");
- root.inOrder(root.getRoot());
- System.out.println("\nPostOrder Traversal: ");
- root.postOrder(root.getRoot());
- }
-
- private static Node createBst(int[] array, int start, int end) {
- // No element left.
- if (start > end) {
- return null;
- }
- int mid = start + (end - start) / 2;
-
- // middle element will be the root
- Node root = new Node(array[mid]);
- root.left = createBst(array, start, mid - 1);
- root.right = createBst(array, mid + 1, end);
- return root;
- }
-}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java
new file mode 100644
index 000000000000..83458f6f8d79
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java
@@ -0,0 +1,47 @@
+package com.thealgorithms.datastructures.trees;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * @author Albina Gimaletdinova on 20/04/2023
+ */
+public class BSTFromSortedArrayTest {
+ @Test
+ public void testNullArray() {
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(null);
+ Assertions.assertNull(actualBST);
+ }
+
+ @Test
+ public void testEmptyArray() {
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{});
+ Assertions.assertNull(actualBST);
+ }
+
+ @Test
+ public void testSingleElementArray() {
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{Integer.MIN_VALUE});
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
+ }
+
+ @Test
+ public void testCreateBSTFromSmallArray() {
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(new int[]{1, 2, 3});
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
+ }
+
+ @Test
+ public void testCreateBSTFromLongerArray() {
+ int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(array);
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(actualBST));
+ }
+
+ @Test
+ public void testShouldNotCreateBSTFromNonSortedArray() {
+ int[] array = {10, 2, 3, 4, 5, 6, 7, 8, 9, 1};
+ BinaryTree.Node actualBST = BSTFromSortedArray.createBST(array);
+ Assertions.assertFalse(CheckBinaryTreeIsValidBST.isBST(actualBST));
+ }
+}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/ValidBSTOrNotTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java
similarity index 79%
rename from src/test/java/com/thealgorithms/datastructures/trees/ValidBSTOrNotTest.java
rename to src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java
index b3189a805dbe..041b2eea20b2 100644
--- a/src/test/java/com/thealgorithms/datastructures/trees/ValidBSTOrNotTest.java
+++ b/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java
@@ -8,16 +8,16 @@
/**
* @author Albina Gimaletdinova on 17/02/2023
*/
-public class ValidBSTOrNotTest {
+public class CheckBinaryTreeIsValidBSTTest {
@Test
public void testRootNull() {
- assertTrue(ValidBSTOrNot.isBST(null));
+ assertTrue(CheckBinaryTreeIsValidBST.isBST(null));
}
@Test
public void testOneNode() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{Integer.MIN_VALUE});
- assertTrue(ValidBSTOrNot.isBST(root));
+ assertTrue(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
@@ -30,7 +30,7 @@ public void testOneNode() {
@Test
public void testBinaryTreeIsBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 20});
- assertTrue(ValidBSTOrNot.isBST(root));
+ assertTrue(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
@@ -43,7 +43,7 @@ public void testBinaryTreeIsBST() {
@Test
public void testBinaryTreeWithDuplicatedNodesIsNotBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 13});
- assertFalse(ValidBSTOrNot.isBST(root));
+ assertFalse(CheckBinaryTreeIsValidBST.isBST(root));
}
/*
@@ -56,6 +56,6 @@ public void testBinaryTreeWithDuplicatedNodesIsNotBST() {
@Test
public void testBinaryTreeIsNotBST() {
final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[]{9, 7, 13, 3, 8, 10, 12});
- assertFalse(ValidBSTOrNot.isBST(root));
+ assertFalse(CheckBinaryTreeIsValidBST.isBST(root));
}
}
From f69cd7cfa211f0847b9b4d67f04c37499bff31c4 Mon Sep 17 00:00:00 2001
From: Albina Gimaletdinova
Date: Mon, 24 Apr 2023 17:52:38 +0600
Subject: [PATCH 0024/1457] Remove redundant code and add tests for
BSTIterative (#4164)
---
.../datastructures/trees/BSTIterative.java | 128 +-----------------
.../trees/BSTIterativeTest.java | 61 +++++++++
2 files changed, 65 insertions(+), 124 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java
index 200a108a1c86..db3d0438f4fe 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java
@@ -1,5 +1,7 @@
package com.thealgorithms.datastructures.trees;
+import com.thealgorithms.datastructures.trees.BinaryTree.Node;
+
/**
*
*
@@ -13,7 +15,6 @@
*
* @author [Lakhan Nad](https://github.com/Lakhan-Nad)
*/
-import java.util.Stack;
public class BSTIterative {
@@ -29,30 +30,8 @@ public class BSTIterative {
root = null;
}
- /**
- * main function for tests
- */
- public static void main(String[] args) {
- BSTIterative tree = new BSTIterative();
- tree.add(3);
- tree.add(2);
- tree.add(9);
- assert !tree.find(4) : "4 is not yet present in BST";
- assert tree.find(2) : "2 should be present in BST";
- tree.remove(2);
- assert !tree.find(2) : "2 was just deleted from BST";
- tree.remove(1);
- assert !tree.find(
- 1
- ) : "Since 1 was not present so find deleting would do no change";
- tree.add(30);
- tree.add(40);
- assert tree.find(40) : "40 was inserted but not found";
- /*
- Will print following order
- 3 9 30 40
- */
- tree.inorder();
+ public Node getRoot() {
+ return root;
}
/**
@@ -184,86 +163,6 @@ public void remove(int data) {
}
}
- /**
- * A method for inorder traversal of BST.
- */
- public void inorder() {
- if (this.root == null) {
- System.out.println("This BST is empty.");
- return;
- }
- System.out.println("Inorder traversal of this tree is:");
- Stack st = new Stack();
- Node cur = this.root;
- while (cur != null || !st.empty()) {
- while (cur != null) {
- st.push(cur);
- cur = cur.left;
- }
- cur = st.pop();
- System.out.print(cur.data + " ");
- cur = cur.right;
- }
- System.out.println(); // for next line
- }
-
- /**
- * A method used to print postorder traversal of BST.
- */
- public void postorder() {
- if (this.root == null) {
- System.out.println("This BST is empty.");
- return;
- }
- System.out.println("Postorder traversal of this tree is:");
- Stack st = new Stack();
- Node cur = this.root, temp2;
- while (cur != null || !st.empty()) {
- if (cur != null) {
- st.push(cur);
- cur = cur.left;
- } else {
- temp2 = st.peek();
- if (temp2.right != null) {
- cur = temp2.right;
- } else {
- st.pop();
- while (!st.empty() && st.peek().right == temp2) {
- System.out.print(temp2.data + " ");
- temp2 = st.pop();
- }
- System.out.print(temp2.data + " ");
- }
- }
- }
- System.out.println(); // for next line
- }
-
- /**
- * Method used to display preorder traversal of BST.
- */
- public void preorder() {
- if (this.root == null) {
- System.out.println("This BST is empty.");
- return;
- }
- System.out.println("Preorder traversal of this tree is:");
- Stack st = new Stack();
- st.push(this.root);
- Node temp;
- while (!st.empty()) {
- temp = st.pop();
- System.out.print(temp.data + " ");
- if (temp.right != null) {
- st.push(temp.right);
- }
- if (temp.left != null) {
- st.push(temp.left);
- }
- }
- System.out.println(); // for next line
- }
-
/**
* A method to check if given data exists in out Binary Search Tree.
*
@@ -289,23 +188,4 @@ public boolean find(int data) {
System.out.println(data + " not found.");
return false;
}
-
- /**
- * The Node class used for building binary search tree
- */
- private static class Node {
-
- int data;
- Node left;
- Node right;
-
- /**
- * Constructor with data as parameter
- */
- Node(int d) {
- data = d;
- left = null;
- right = null;
- }
- }
}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java
new file mode 100644
index 000000000000..f47e2ad5285d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java
@@ -0,0 +1,61 @@
+package com.thealgorithms.datastructures.trees;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * @author Albina Gimaletdinova on 23/04/2023
+ */
+public class BSTIterativeTest {
+ @Test
+ public void testBSTIsCorrectlyConstructedFromOneNode() {
+ BSTIterative tree = new BSTIterative();
+ tree.add(6);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+
+ @Test
+ public void testBSTIsCorrectlyCleanedAndEmpty() {
+ BSTIterative tree = new BSTIterative();
+
+ tree.add(6);
+ tree.remove(6);
+
+ tree.add(12);
+ tree.add(1);
+ tree.add(2);
+
+ tree.remove(1);
+ tree.remove(2);
+ tree.remove(12);
+
+ Assertions.assertNull(tree.getRoot());
+ }
+
+ @Test
+ public void testBSTIsCorrectlyCleanedAndNonEmpty() {
+ BSTIterative tree = new BSTIterative();
+
+ tree.add(6);
+ tree.remove(6);
+
+ tree.add(12);
+ tree.add(1);
+ tree.add(2);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+
+ @Test
+ public void testBSTIsCorrectlyConstructedFromMultipleNodes() {
+ BSTIterative tree = new BSTIterative();
+ tree.add(7);
+ tree.add(1);
+ tree.add(5);
+ tree.add(100);
+ tree.add(50);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+}
From b55fc972ace3007c17c7e16d1ad899f57aecf640 Mon Sep 17 00:00:00 2001
From: Lieu Chi Tung <67320227+LieuChiTung@users.noreply.github.com>
Date: Tue, 25 Apr 2023 18:04:15 +0700
Subject: [PATCH 0025/1457] Add tests for HorspoolSearch (#4165)
---
.../thealgorithms/strings/HorspoolSearch.java | 4 +
.../strings/HorspoolSearchTest.java | 88 +++++++++++++++++++
2 files changed, 92 insertions(+)
create mode 100644 src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java
diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
index cc35dbbbf26f..9ac0d50ca8fe 100644
--- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
+++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
@@ -100,6 +100,10 @@ private static int firstOccurrence(
shiftValues = calcShiftValues(pattern); // build the bad symbol table
comparisons = 0; // reset comparisons
+ if (pattern.length() == 0) { // return failure, if pattern empty
+ return -1;
+ }
+
int textIndex = pattern.length() - 1; // align pattern with text start and get index of the last character
// while pattern is not out of text bounds
diff --git a/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java
new file mode 100644
index 000000000000..9240ac8a51b9
--- /dev/null
+++ b/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java
@@ -0,0 +1,88 @@
+package com.thealgorithms.strings;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class HorspoolSearchTest {
+
+ @Test
+ void testFindFirstMatch() {
+ int index = HorspoolSearch.findFirst("World", "Hello World");
+ assertEquals(6, index);
+ }
+
+ @Test
+ void testFindFirstNotMatch() {
+ int index = HorspoolSearch.findFirst("hell", "Hello World");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testFindFirstPatternLongerText() {
+ int index = HorspoolSearch.findFirst("Hello World!!!", "Hello World");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testFindFirstPatternEmpty() {
+ int index = HorspoolSearch.findFirst("", "Hello World");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testFindFirstTextEmpty() {
+ int index = HorspoolSearch.findFirst("Hello", "");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testFindFirstPatternAndTextEmpty() {
+ int index = HorspoolSearch.findFirst("", "");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testFindFirstSpecialCharacter() {
+ int index = HorspoolSearch.findFirst("$3**", "Hello $3**$ World");
+ assertEquals(6, index);
+ }
+
+ @Test
+ void testFindFirstInsensitiveMatch() {
+ int index = HorspoolSearch.findFirstInsensitive("hello", "Hello World");
+ assertEquals(0, index);
+ }
+
+ @Test
+ void testFindFirstInsensitiveNotMatch() {
+ int index = HorspoolSearch.findFirstInsensitive("helo", "Hello World");
+ assertEquals(-1, index);
+ }
+
+ @Test
+ void testGetLastComparisons() {
+ HorspoolSearch.findFirst("World", "Hello World");
+ int lastSearchNumber = HorspoolSearch.getLastComparisons();
+ assertEquals(7, lastSearchNumber);
+ }
+
+ @Test
+ void testGetLastComparisonsNotMatch() {
+ HorspoolSearch.findFirst("Word", "Hello World");
+ int lastSearchNumber = HorspoolSearch.getLastComparisons();
+ assertEquals(3, lastSearchNumber);
+ }
+
+ @Test
+ void testFindFirstPatternNull() {
+ assertThrows(NullPointerException.class,
+ () -> HorspoolSearch.findFirst(null, "Hello World"));
+ }
+
+ @Test
+ void testFindFirstTextNull() {
+ assertThrows(NullPointerException.class,
+ () -> HorspoolSearch.findFirst("Hello", null));
+ }
+}
\ No newline at end of file
From 7ed65b0a1e47aeb961f10ae769d3d808998d5af8 Mon Sep 17 00:00:00 2001
From: Rutikpatil0123 <71816232+Rutikpatil0123@users.noreply.github.com>
Date: Fri, 28 Apr 2023 23:04:15 +0530
Subject: [PATCH 0026/1457] Add climbing stairs (#4168)
---
.../dynamicprogramming/ClimbingStairs.java | 30 +++++++++++++++++++
.../dynamicprogramming/climbStairsTest.java | 24 +++++++++++++++
2 files changed, 54 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
create mode 100644 src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
new file mode 100644
index 000000000000..376a6532c102
--- /dev/null
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
@@ -0,0 +1,30 @@
+package com.thealgorithms.dynamicprogramming;
+
+/* A DynamicProgramming solution for Climbing Stairs' problem Returns the
+ distinct ways can you climb to the staircase by either climbing 1 or 2 steps.
+
+ Link : https://medium.com/analytics-vidhya/leetcode-q70-climbing-stairs-easy-444a4aae54e8
+*/
+public class ClimbingStairs {
+
+ public static int numberOfWays(int n) {
+
+ if(n == 1 || n == 0){
+ return n;
+ }
+ int prev = 1;
+ int curr = 1;
+
+ int next;
+
+ for(int i = 2; i <= n; i++){
+ next = curr+prev;
+ prev = curr;
+
+ curr = next;
+ }
+
+ return curr;
+
+ }
+}
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java
new file mode 100644
index 000000000000..bc6b4adb8486
--- /dev/null
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java
@@ -0,0 +1,24 @@
+package com.thealgorithms.dynamicprogramming;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+
+public class climbStairsTest {
+
+ @Test
+ void climbStairsTestForTwo(){assertEquals(2, ClimbingStairs.numberOfWays(2));}
+
+ @Test
+ void climbStairsTestForZero(){assertEquals(0, ClimbingStairs.numberOfWays(0));}
+
+ @Test
+ void climbStairsTestForOne(){assertEquals(1, ClimbingStairs.numberOfWays(1));}
+
+ @Test
+ void climbStairsTestForFive(){assertEquals(8, ClimbingStairs.numberOfWays(5));}
+
+ @Test
+ void climbStairsTestForThree(){assertEquals(3, ClimbingStairs.numberOfWays(3));}
+}
From db9c78a59899ceaaec8702323031e73a2491e1c7 Mon Sep 17 00:00:00 2001
From: Rutikpatil0123 <71816232+Rutikpatil0123@users.noreply.github.com>
Date: Sat, 29 Apr 2023 12:47:00 +0530
Subject: [PATCH 0027/1457] Remove duplicated ThreeSum problem (fixes #4169)
(#4170)
---
.../com/thealgorithms/others/ThreeSum.java | 53 -------------------
1 file changed, 53 deletions(-)
delete mode 100644 src/main/java/com/thealgorithms/others/ThreeSum.java
diff --git a/src/main/java/com/thealgorithms/others/ThreeSum.java b/src/main/java/com/thealgorithms/others/ThreeSum.java
deleted file mode 100644
index 299eaf4eeae6..000000000000
--- a/src/main/java/com/thealgorithms/others/ThreeSum.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.thealgorithms.others;
-
-import java.util.Arrays;
-import java.util.Scanner;
-
-/**
- * To find triplet equals to given sum in complexity O(n*log(n))
- *
- *
- * Array must be sorted
- *
- * @author Ujjawal Joshi
- * @date 2020.05.18
- *
- * Test Cases: Input: 6 //Length of array 12 3 4 1 6 9 target=24 Output:3 9 12
- * Explanation: There is a triplet (12, 3 and 9) present in the array whose sum
- * is 24.
- */
-class ThreeSum {
-
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt(); // Length of an array
-
- int[] a = new int[n];
-
- for (int i = 0; i < n; i++) {
- a[i] = sc.nextInt();
- }
- System.out.println("Target");
- int n_find = sc.nextInt();
-
- Arrays.sort(a); // Sort the array if array is not sorted
-
- for (int i = 0; i < n; i++) {
- int l = i + 1, r = n - 1;
-
- while (l < r) {
- if (a[i] + a[l] + a[r] == n_find) {
- System.out.println(a[i] + " " + a[l] + " " + a[r]);
- break;
- } // if you want all the triplets write l++;r--; insted of break;
- else if (a[i] + a[l] + a[r] < n_find) {
- l++;
- } else {
- r--;
- }
- }
- }
-
- sc.close();
- }
-}
From 19bd2408ff50a8bcc835d51eff576a70a228e37f Mon Sep 17 00:00:00 2001
From: Aditya Pal
Date: Sun, 30 Apr 2023 20:19:14 +0530
Subject: [PATCH 0028/1457] Des (#4172)
* Update directory
* Add DES Encryption algorithm
* Update directory
---------
Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
---
DIRECTORY.md | 18 +-
.../java/com/thealgorithms/ciphers/DES.java | 344 ++++++++++++++++++
.../com/thealgorithms/ciphers/DESTest.java | 51 +++
3 files changed, 407 insertions(+), 6 deletions(-)
create mode 100644 src/main/java/com/thealgorithms/ciphers/DES.java
create mode 100644 src/test/java/com/thealgorithms/ciphers/DESTest.java
diff --git a/DIRECTORY.md b/DIRECTORY.md
index fb49d163e745..6f246ff12592 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -30,6 +30,7 @@
* [Blowfish](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/Blowfish.java)
* [Caesar](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/Caesar.java)
* [ColumnarTranspositionCipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java)
+ * [DES](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/DES.java)
* [HillCipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/HillCipher.java)
* [Polybius](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/Polybius.java)
* [ProductCipher](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/ciphers/ProductCipher.java)
@@ -151,14 +152,15 @@
* [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)
+ * [BSTFromSortedArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java)
* [BSTIterative](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java)
* [BSTRecursive](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java)
* [BSTRecursiveGeneric](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java)
* [CeilInBinarySearchTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java)
+ * [CheckBinaryTreeIsValidBST](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java)
* [CheckIfBinaryTreeBalanced](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java)
* [CheckTreeIsSymmetric](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java)
* [CreateBinaryTreeFromInorderPreorder](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java)
- * [CreateBSTFromSortedArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/CreateBSTFromSortedArray.java)
* [FenwickTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java)
* [GenericTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java)
* [InorderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java)
@@ -166,7 +168,6 @@
* [LazySegmentTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java)
* [LCA](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LCA.java)
* [LevelOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java)
- * [LevelOrderTraversalHelper](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversalHelper.java)
* [nearestRightKey](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java)
* [PostOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java)
* [PreOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java)
@@ -175,9 +176,7 @@
* [SameTreesCheck](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java)
* [SegmentTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java)
* [TreeRandomNode](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java)
- * [TreeTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeTraversal.java)
* [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java)
- * [ValidBSTOrNot](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/ValidBSTOrNot.java)
* [VerticalOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java)
* [ZigzagTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java)
* devutils
@@ -202,6 +201,7 @@
* [BoundaryFill](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java)
* [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)
+ * [ClimbingStairs](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.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)
@@ -382,6 +382,7 @@
* [KochSnowflake](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/KochSnowflake.java)
* [Krishnamurthy](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Krishnamurthy.java)
* [LinearCongruentialGenerator](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/LinearCongruentialGenerator.java)
+ * [LineSweep](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/LineSweep.java)
* [LowestBasePalindrome](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java)
* [Luhn](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Luhn.java)
* [Mandelbrot](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Mandelbrot.java)
@@ -403,7 +404,6 @@
* [StackPostfixNotation](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/StackPostfixNotation.java)
* [StringMatchFiniteAutomata](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/StringMatchFiniteAutomata.java)
* [Sudoku](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/Sudoku.java)
- * [ThreeSum](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/ThreeSum.java)
* [TopKWords](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TopKWords.java)
* [TowerOfHanoi](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TowerOfHanoi.java)
* [TwoPointers](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/others/TwoPointers.java)
@@ -526,6 +526,7 @@
* [LFSRTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/a5/LFSRTest.java)
* [BlowfishTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/BlowfishTest.java)
* [CaesarTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/CaesarTest.java)
+ * [DESTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/DESTest.java)
* [PolybiusTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/PolybiusTest.java)
* [RSATest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/RSATest.java)
* [SimpleSubCipherTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/ciphers/SimpleSubCipherTest.java)
@@ -575,7 +576,10 @@
* [PriorityQueuesTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/queues/PriorityQueuesTest.java)
* trees
* [BinaryTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeTest.java)
+ * [BSTFromSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTFromSortedArrayTest.java)
+ * [BSTIterativeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/BSTIterativeTest.java)
* [CeilInBinarySearchTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTreeTest.java)
+ * [CheckBinaryTreeIsValidBSTTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBSTTest.java)
* [CheckTreeIsSymmetricTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetricTest.java)
* [InorderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/InorderTraversalTest.java)
* [KDTreeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/KDTreeTest.java)
@@ -585,7 +589,6 @@
* [PreOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/PreOrderTraversalTest.java)
* [SameTreesCheckTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/SameTreesCheckTest.java)
* [TreeTestUtils](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/TreeTestUtils.java)
- * [ValidBSTOrNotTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ValidBSTOrNotTest.java)
* [VerticalOrderTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversalTest.java)
* [ZigzagTraversalTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/trees/ZigzagTraversalTest.java)
* divideandconquer
@@ -593,6 +596,7 @@
* [StrassenMatrixMultiplicationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java)
* dynamicprogramming
* [CatalanNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/CatalanNumberTest.java)
+ * [climbStairsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/climbStairsTest.java)
* [EggDroppingTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/EggDroppingTest.java)
* [KnapsackMemoizationTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/KnapsackMemoizationTest.java)
* [LevenshteinDistanceTests](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/dynamicprogramming/LevenshteinDistanceTests.java)
@@ -674,6 +678,7 @@
* [CRCAlgorithmTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/CRCAlgorithmTest.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)
+ * [LineSweepTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LineSweepTest.java)
* [LinkListSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/others/LinkListSortTest.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)
@@ -731,6 +736,7 @@
* [CheckAnagramsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/CheckAnagramsTest.java)
* [CheckVowelsTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/CheckVowelsTest.java)
* [HammingDistanceTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/HammingDistanceTest.java)
+ * [HorspoolSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/HorspoolSearchTest.java)
* [IsomorphicTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/IsomorphicTest.java)
* [LetterCombinationsOfPhoneNumberTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumberTest.java)
* [longestNonRepeativeSubstringTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/strings/longestNonRepeativeSubstringTest.java)
diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java
new file mode 100644
index 000000000000..8b226e284a25
--- /dev/null
+++ b/src/main/java/com/thealgorithms/ciphers/DES.java
@@ -0,0 +1,344 @@
+package com.thealgorithms.ciphers;
+
+/**
+ * This class is build to demonstrate the application of the DES-algorithm on a
+ * plain English message. The supplied key must be in form of a 64 bit binary String.
+ */
+public class DES {
+
+ private String key;
+ private String subKeys[];
+
+ private void sanitize(String key) {
+ int length = key.length();
+ if (length != 64) {
+ throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string");
+ }
+ }
+
+ DES(String key) {
+ sanitize(key);
+ this.key = key;
+ subKeys = getSubkeys(key);
+ }
+
+ public String getKey() {
+ return this.key;
+ }
+
+ public void setKey(String key) {
+ sanitize(key);
+ this.key = key;
+ }
+
+ //Permutation table to convert initial 64 bit key to 56 bit key
+ private static int[] PC1 =
+ {
+ 57, 49, 41, 33, 25, 17, 9,
+ 1, 58, 50, 42, 34, 26, 18,
+ 10, 2, 59, 51, 43, 35, 27,
+ 19, 11, 3, 60, 52, 44, 36,
+ 63, 55, 47, 39, 31, 23, 15,
+ 7, 62, 54, 46, 38, 30, 22,
+ 14, 6, 61, 53, 45, 37, 29,
+ 21, 13, 5, 28, 20, 12, 4
+ };
+
+ //Lookup table used to shift the initial key, in order to generate the subkeys
+ private static int[] KEY_SHIFTS =
+ {
+ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
+ };
+
+ //Table to convert the 56 bit subkeys to 48 bit subkeys
+ private static int[] PC2 =
+ {
+ 14, 17, 11, 24, 1, 5,
+ 3, 28, 15, 6, 21, 10,
+ 23, 19, 12, 4, 26, 8,
+ 16, 7, 27, 20, 13, 2,
+ 41, 52, 31, 37, 47, 55,
+ 30, 40, 51, 45, 33, 48,
+ 44, 49, 39, 56, 34, 53,
+ 46, 42, 50, 36, 29, 32
+ };
+
+ //Initial permutatation of each 64 but message block
+ private static int[] IP =
+ {
+ 58, 50, 42, 34, 26, 18, 10 , 2,
+ 60, 52, 44, 36, 28, 20, 12, 4,
+ 62, 54, 46, 38, 30, 22, 14, 6,
+ 64, 56, 48, 40, 32, 24, 16, 8,
+ 57, 49, 41, 33, 25, 17, 9, 1,
+ 59, 51, 43, 35, 27, 19, 11, 3,
+ 61, 53, 45, 37, 29, 21, 13, 5,
+ 63, 55, 47, 39, 31, 23, 15, 7
+ };
+
+ //Expansion table to convert right half of message blocks from 32 bits to 48 bits
+ private static int[] expansion =
+ {
+ 32, 1, 2, 3, 4, 5,
+ 4, 5, 6, 7, 8, 9,
+ 8, 9, 10, 11, 12, 13,
+ 12, 13, 14, 15, 16, 17,
+ 16, 17, 18, 19, 20, 21,
+ 20, 21, 22, 23, 24, 25,
+ 24, 25, 26, 27, 28, 29,
+ 28, 29, 30, 31, 32, 1
+ };
+
+ //The eight substitution boxes are defined below
+ private static int[][] s1 = {
+ {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
+ {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
+ {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
+ {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}
+ };
+
+ private static int[][] s2 = {
+ {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
+ {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
+ {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
+ {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}
+ };
+
+ private static int[][] s3 = {
+ {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
+ {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
+ {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
+ {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}
+ };
+
+ private static int[][] s4 = {
+ {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
+ {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
+ {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
+ {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}
+ };
+
+ private static int[][] s5 = {
+ {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
+ {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
+ {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
+ {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}
+ };
+
+ private static int[][] s6 = {
+ {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
+ {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
+ {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
+ {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}
+ };
+
+ private static int[][] s7 = {
+ {4, 11, 2, 14, 15, 0, 8, 13 , 3, 12, 9 , 7, 5, 10, 6, 1},
+ {13 , 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
+ {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
+ {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}
+ };
+
+ private static int[][] s8 = {
+ {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
+ {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6 ,11, 0, 14, 9, 2},
+ {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10 ,13, 15, 3, 5, 8},
+ {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6 ,11}
+ };
+
+ private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
+
+ //Permutation table, used in the feistel function post s-box usage
+ static int[] permutation =
+ {
+ 16, 7, 20, 21,
+ 29, 12, 28, 17,
+ 1, 15, 23, 26,
+ 5, 18, 31, 10,
+ 2, 8, 24, 14,
+ 32, 27, 3, 9,
+ 19, 13, 30, 6,
+ 22, 11, 4, 25
+ };
+
+ //Table used for final inversion of the message box after 16 rounds of Feistel Function
+ static int[] IPinverse =
+ {
+ 40, 8, 48, 16, 56, 24, 64, 32,
+ 39, 7, 47, 15, 55, 23, 63, 31,
+ 38, 6, 46, 14, 54, 22, 62, 30,
+ 37, 5, 45, 13, 53, 21, 61, 29,
+ 36, 4, 44, 12, 52, 20, 60, 28,
+ 35, 3, 43 ,11, 51, 19, 59, 27,
+ 34, 2, 42, 10, 50, 18, 58, 26,
+ 33, 1, 41, 9, 49, 17, 57, 25
+ };
+
+ private String[] getSubkeys(String originalKey) {
+ StringBuilder permutedKey = new StringBuilder(); //Initial permutation of keys via PC1
+ int i, j;
+ for (i = 0; i < 56; i++) {
+ permutedKey.append(originalKey.charAt(PC1[i] - 1));
+ }
+ String subKeys[] = new String[16];
+ String initialPermutedKey = permutedKey.toString();
+ String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28);
+
+ //We will now operate on the left and right halves of the permutedKey
+ for (i = 0; i < 16; i++) {
+ String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]);
+ String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]);
+ subKeys[i] = Cn + Dn;
+ C0 = Cn; //Re-assign the values to create running permutation
+ D0 = Dn;
+ }
+
+ //Let us shrink the keys to 48 bits (well, characters here) using PC2
+ for (i = 0; i < 16; i++) {
+ String key = subKeys[i];
+ permutedKey.setLength(0);
+ for (j = 0; j < 48; j++) {
+ permutedKey.append(key.charAt(PC2[j] - 1));
+ }
+ subKeys[i] = permutedKey.toString();
+ }
+
+ return subKeys;
+ }
+
+ private String XOR(String a, String b) {
+ int i, l = a.length();
+ StringBuilder xor = new StringBuilder();
+ for (i = 0; i < l; i++) {
+ int firstBit = a.charAt(i) - 48; // 48 is '0' in ascii
+ int secondBit = b.charAt(i) - 48;
+ xor.append((firstBit ^ secondBit));
+ }
+ return xor.toString();
+ }
+
+ private String createPaddedString(String s, int desiredLength, char pad) {
+ int i, l = s.length();
+ StringBuilder paddedString = new StringBuilder();
+ int diff = desiredLength - l;
+ for (i = 0; i < diff; i++) {
+ paddedString.append(pad);
+ }
+ return paddedString.toString();
+ }
+
+ private String pad(String s, int desiredLength) {
+ return createPaddedString(s, desiredLength, '0') + s;
+ }
+
+ private String padLast(String s, int desiredLength) {
+ return s + createPaddedString(s, desiredLength, '\u0000');
+ }
+
+ private String feistel(String messageBlock, String key) {
+ int i;
+ StringBuilder expandedKey = new StringBuilder();
+ for (i = 0; i < 48; i++) {
+ expandedKey.append(messageBlock.charAt(expansion[i] - 1));
+ }
+ String mixedKey = XOR(expandedKey.toString(), key);
+ StringBuilder substitutedString = new StringBuilder();
+
+ //Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
+ for (i = 0; i < 48; i += 6) {
+ String block = mixedKey.substring(i, i + 6);
+ int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
+ int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
+ String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
+ substitutedString.append(substitutedBlock);
+ }
+
+ StringBuilder permutedString = new StringBuilder();
+ for (i = 0; i < 32; i++) {
+ permutedString.append(substitutedString.charAt(permutation[i] - 1));
+ }
+
+ return permutedString.toString();
+ }
+
+ private String encryptBlock(String message, String keys[]) {
+ StringBuilder permutedMessage = new StringBuilder();
+ int i;
+ for (i = 0; i < 64; i++) {
+ permutedMessage.append(message.charAt(IP[i] - 1));
+ }
+ String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32);
+
+ //Iterate 16 times
+ for (i = 0; i < 16; i++) {
+ String Ln = R0; // Previous Right block
+ String Rn = XOR(L0, feistel(R0, keys[i]));
+ L0 = Ln;
+ R0 = Rn;
+ }
+
+ String combinedBlock = R0 + L0; //Reverse the 16th block
+ permutedMessage.setLength(0);
+ for (i = 0; i < 64; i++) {
+ permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1));
+ }
+ return permutedMessage.toString();
+ }
+
+ //To decode, we follow the same process as encoding, but with reversed keys
+ private String decryptBlock(String message, String keys[]) {
+ String reversedKeys[] = new String[keys.length];
+ for (int i = 0; i < keys.length; i++) {
+ reversedKeys[i] = keys[keys.length - i - 1];
+ }
+ return encryptBlock(message, reversedKeys);
+ }
+
+ /**
+ * @param message Message to be encrypted
+ * @return The encrypted message, as a binary string
+ */
+ public String encrypt(String message) {
+ StringBuilder encryptedMessage = new StringBuilder();
+ int l = message.length(), i, j;
+ if (l % 8 != 0) {
+ int desiredLength = (l / 8 + 1) * 8;
+ l = desiredLength;
+ message = padLast(message, desiredLength);
+ }
+
+ for (i = 0; i < l; i+= 8) {
+ String block = message.substring(i, i + 8);
+ StringBuilder bitBlock = new StringBuilder();
+ byte[] bytes = block.getBytes();
+ for (j = 0; j < 8; j++) {
+ bitBlock.append(pad(Integer.toBinaryString(bytes[j]), 8));
+ }
+ encryptedMessage.append(encryptBlock(bitBlock.toString(), subKeys));
+ }
+ return encryptedMessage.toString();
+ }
+
+ /**
+ * @param message The encrypted string. Expects it to be a multiple of 64 bits, in binary format
+ * @return The decrypted String, in plain English
+ */
+ public String decrypt(String message) {
+ StringBuilder decryptedMessage = new StringBuilder();
+ int l = message.length(), i, j;
+ if (l % 64 != 0) {
+ throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
+ }
+ for (i = 0; i < l; i+= 64) {
+ String block = message.substring(i, i + 64);
+ String result = decryptBlock(block.toString(), subKeys);
+ byte res[] = new byte[8];
+ for (j = 0; j < 64; j+=8) {
+ res[j / 8] = (byte)Integer.parseInt(result.substring(j, j + 8), 2);
+ }
+ decryptedMessage.append(new String(res));
+ }
+ return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/thealgorithms/ciphers/DESTest.java b/src/test/java/com/thealgorithms/ciphers/DESTest.java
new file mode 100644
index 000000000000..a0c529d5f268
--- /dev/null
+++ b/src/test/java/com/thealgorithms/ciphers/DESTest.java
@@ -0,0 +1,51 @@
+package com.thealgorithms.ciphers;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+//Test example taken from https://page.math.tu-berlin.de/~kant/teaching/hess/krypto-ws2006/des.htm
+public class DESTest {
+
+ DES des;
+
+ @BeforeEach
+ public void setUp() {
+ des = new DES("0000111000110010100100100011001011101010011011010000110101110011");
+ }
+
+ @Test
+ void testEncrypt() {
+ //given
+ String plainText = "Your lips are smoother than vaseline\r\n";
+ //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal
+ String expectedOutput = "11000000100110011001111111011101111000110111100011010111111" +
+ "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" +
+ "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" +
+ "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011";
+
+ //when
+ String cipherText = des.encrypt(plainText);
+
+ //then
+ assertEquals(expectedOutput, cipherText);
+ }
+
+ @Test
+ void testDecrypt() {
+ //given
+ //This is equal to c0999fdde378d7ed727da00bca5a84ee47f269a4d6438190d9d52f78f5358499828ac9b453e0e653 in hexadecimal
+ String cipherText = "11000000100110011001111111011101111000110111100011010111111" +
+ "011010111001001111101101000000000101111001010010110101000010011101110010001111111001" +
+ "001101001101001001101011001000011100000011001000011011001110101010010111101111000111" +
+ "101010011010110000100100110011000001010001010110010011011010001010011111000001110011001010011";
+ String expectedOutput = "Your lips are smoother than vaseline\r\n";;
+
+ //when
+ String plainText = des.decrypt(cipherText);
+
+ //then
+ assertEquals(expectedOutput, plainText);
+ }
+}
From fb18c27905ce136967da707cf014a1f07ba64ab9 Mon Sep 17 00:00:00 2001
From: Aditya Pal
Date: Mon, 1 May 2023 00:52:19 +0530
Subject: [PATCH 0029/1457] Add wiki link for DES (#4173)
---
src/main/java/com/thealgorithms/ciphers/DES.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java
index 8b226e284a25..aae8282eae42 100644
--- a/src/main/java/com/thealgorithms/ciphers/DES.java
+++ b/src/main/java/com/thealgorithms/ciphers/DES.java
@@ -1,7 +1,7 @@
package com.thealgorithms.ciphers;
/**
- * This class is build to demonstrate the application of the DES-algorithm on a
+ * This class is build to demonstrate the application of the DES-algorithm (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a
* plain English message. The supplied key must be in form of a 64 bit binary String.
*/
public class DES {
@@ -341,4 +341,4 @@ public String decrypt(String message) {
return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
}
-}
\ No newline at end of file
+}
From bb830e9559648659697f17f449c51c6dc0661275 Mon Sep 17 00:00:00 2001
From: Rutikpatil0123 <71816232+Rutikpatil0123@users.noreply.github.com>
Date: Tue, 2 May 2023 22:33:21 +0530
Subject: [PATCH 0030/1457] Add tests for TwoSumProblem and reduce duplication
(fixes #4177) (#4176)
---
.../com/thealgorithms/misc/TwoSumProblem.java | 109 ------------------
.../com/thealgorithms/others/TwoPointers.java | 17 +--
.../thealgorithms/others/TwoPointersTest.java | 44 +++++++
3 files changed, 45 insertions(+), 125 deletions(-)
delete mode 100644 src/main/java/com/thealgorithms/misc/TwoSumProblem.java
create mode 100644 src/test/java/com/thealgorithms/others/TwoPointersTest.java
diff --git a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java b/src/main/java/com/thealgorithms/misc/TwoSumProblem.java
deleted file mode 100644
index e355cec02f77..000000000000
--- a/src/main/java/com/thealgorithms/misc/TwoSumProblem.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package com.thealgorithms.misc;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-public class TwoSumProblem {
-
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter the target sum ");
- int ts = scan.nextInt();
- System.out.print("Enter the number of elements in the array ");
- int n = scan.nextInt();
- System.out.println("Enter all your array elements:");
- int[] arr = new int[n];
- for (int i = 0; i < n; i++) {
- arr[i] = scan.nextInt();
- }
- TwoSumProblem t = new TwoSumProblem();
- System.out.println(
- "Brute Force Approach\n" +
- Arrays.toString(t.BruteForce(arr, ts)) +
- "\n"
- );
- System.out.println(
- "Two Pointer Approach\n" +
- Arrays.toString(t.TwoPointer(arr, ts)) +
- "\n"
- );
- System.out.println(
- "Hashmap Approach\n" + Arrays.toString(t.HashMap(arr, ts))
- );
- }
-
- public int[] BruteForce(int[] nums, int target) {
- //Brute Force Approach
- int[] ans = new int[2];
- for (int i = 0; i < nums.length; i++) {
- for (int j = i + 1; j < nums.length; j++) {
- if (nums[i] + nums[j] == target) {
- ans[0] = i;
- ans[1] = j;
-
- break;
- }
- }
- }
-
- return ans;
- }
-
- public int[] TwoPointer(int[] nums, int target) {
- // HashMap Approach
- int[] ans = new int[2];
- HashMap hm = new HashMap();
- for (int i = 0; i < nums.length; i++) {
- hm.put(i, nums[i]);
- }
- HashMap temp = hm
- .entrySet()
- .stream()
- .sorted((i1, i2) -> i1.getValue().compareTo(i2.getValue()))
- .collect(
- Collectors.toMap(
- Map.Entry::getKey,
- Map.Entry::getValue,
- (e1, e2) -> e1,
- LinkedHashMap::new
- )
- );
-
- int start = 0;
- int end = nums.length - 1;
- while (start < end) {
- int currSum = (Integer) temp.values().toArray()[start] +
- (Integer) temp.values().toArray()[end];
-
- if (currSum == target) {
- ans[0] = (Integer) temp.keySet().toArray()[start];
- ans[1] = (Integer) temp.keySet().toArray()[end];
- break;
- } else if (currSum > target) {
- end -= 1;
- } else if (currSum < target) {
- start += 1;
- }
- }
- return ans;
- }
-
- public int[] HashMap(int[] nums, int target) {
- //Using Hashmaps
- int[] ans = new int[2];
- HashMap hm = new HashMap();
- for (int i = 0; i < nums.length; i++) {
- hm.put(nums[i], i);
- }
- for (int i = 0; i < nums.length; i++) {
- int t = target - nums[i];
- if (hm.containsKey(t) && hm.get(t) != i) {
- ans[0] = i;
- ans[1] = hm.get(t);
- break;
- }
- }
-
- return ans;
- }
-}
diff --git a/src/main/java/com/thealgorithms/others/TwoPointers.java b/src/main/java/com/thealgorithms/others/TwoPointers.java
index c5b57f344c28..de44354a6602 100644
--- a/src/main/java/com/thealgorithms/others/TwoPointers.java
+++ b/src/main/java/com/thealgorithms/others/TwoPointers.java
@@ -11,21 +11,6 @@
*/
class TwoPointers {
- public static void main(String[] args) {
- int[] arr = { 10, 20, 35, 50, 75, 80 };
- int key = 70;
- assert isPairedSum(arr, key);
- /* 20 + 60 == 70 */
-
- arr = new int[] { 1, 2, 3, 4, 5, 6, 7 };
- key = 13;
- assert isPairedSum(arr, key);
- /* 6 + 7 == 13 */
-
- key = 14;
- assert !isPairedSum(arr, key);
- }
-
/**
* Given a sorted array arr (sorted in ascending order). Find if there
* exists any pair of elements such that their sum is equal to key.
@@ -35,7 +20,7 @@ public static void main(String[] args) {
* @return {@code true} if there exists a pair of elements, {@code false}
* otherwise.
*/
- private static boolean isPairedSum(int[] arr, int key) {
+ public static boolean isPairedSum(int[] arr, int key) {
/* array sorting is necessary for this algorithm to function correctly */
Arrays.sort(arr);
int i = 0;
diff --git a/src/test/java/com/thealgorithms/others/TwoPointersTest.java b/src/test/java/com/thealgorithms/others/TwoPointersTest.java
new file mode 100644
index 000000000000..7241140c7246
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/TwoPointersTest.java
@@ -0,0 +1,44 @@
+package com.thealgorithms.others;
+
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+
+public class TwoPointersTest {
+
+
+ @Test
+ void twoPointersFirstTestCase(){
+ int[] arr = {2,6,9,22,121};
+ int key = 28;
+ assertEquals(true, TwoPointers.isPairedSum(arr,key));
+ }
+
+ @Test
+ void twoPointersSecondTestCase(){
+ int[] arr = {-1,-12,12,0,8};
+ int key = 0;
+ assertEquals(true, TwoPointers.isPairedSum(arr,key));
+ }
+
+ @Test
+ void twoPointersThirdTestCase(){
+ int[] arr = {12,35,12,152,0};
+ int key = 13;
+ assertEquals(false, TwoPointers.isPairedSum(arr,key));
+ }
+
+ @Test
+ void twoPointersFourthTestCase(){
+ int[] arr = {-2,5,-1,52,31};
+ int key = -3;
+ assertEquals(true, TwoPointers.isPairedSum(arr,key));
+ }
+
+ @Test
+ void twoPointersFiftiethTestCase(){
+ int[] arr = {25,1,0,61,21};
+ int key = 12;
+ assertEquals(false, TwoPointers.isPairedSum(arr,key));
+ }
+}
From 89b7ee42e6010323e4b4c0556c3005620f1d9845 Mon Sep 17 00:00:00 2001
From: Manoj Kumar <52065298+manojCode94@users.noreply.github.com>
Date: Fri, 5 May 2023 23:20:47 +0530
Subject: [PATCH 0031/1457] Add one more solution for anagrams check (#4175)
---
.../com/thealgorithms/strings/Anagrams.java | 25 +++++++++++++++++++
.../thealgorithms/strings/AnagramsTest.java | 1 +
2 files changed, 26 insertions(+)
diff --git a/src/main/java/com/thealgorithms/strings/Anagrams.java b/src/main/java/com/thealgorithms/strings/Anagrams.java
index 5a9487da678d..33ea900e3d06 100644
--- a/src/main/java/com/thealgorithms/strings/Anagrams.java
+++ b/src/main/java/com/thealgorithms/strings/Anagrams.java
@@ -43,6 +43,8 @@ public static void main(String[] args) {
* Auxiliary Space Complexity : O(1)
* 4th approach Time Complexity : O(n)
* Auxiliary Space Complexity : O(n)
+ * 5th approach Time Complexity: O(n)
+ * Auxiliary Space Complexity: O(1)
*/
}
@@ -122,4 +124,27 @@ boolean approach4(String s, String t) {
return nm.equals(kk);
}
}
+
+ boolean approach5(String s, String t) {
+ if(s.length() != t.length()){
+ return false;
+ }
+ // Approach is different from above 4 aproaches.
+ // Here we initialize an array of size 26 where each element corresponds to the frequency of a character.
+ int[] freq = new int[26];
+ // iterate through both strings, incrementing the frequency of each character in the first string and decrementing the frequency of each character in the second string.
+ for(int i=0; i
Date: Sat, 6 May 2023 21:10:33 +0300
Subject: [PATCH 0032/1457] Cover BSTRecursive with tests (#4180)
---
.../datastructures/trees/BSTRecursive.java | 134 +-----------------
.../trees/BSTRecursiveTest.java | 61 ++++++++
2 files changed, 68 insertions(+), 127 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java
index 4dd32f415f01..34959556a0c3 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java
@@ -1,15 +1,17 @@
package com.thealgorithms.datastructures.trees;
+import com.thealgorithms.datastructures.trees.BinaryTree.Node;
+
/**
*
*
* Binary Search Tree (Recursive)
*
* An implementation of BST recursively. In recursive implementation the checks
- * are down the tree First root is checked if not found then its childs are
+ * are down the tree First root is checked if not found then its children are
* checked Binary Search Tree is a binary tree which satisfies three properties:
* left child is less than root node, right child is grater than root node, both
- * left and right childs must themselves be a BST.
+ * left and right children must themselves be a BST.
*
*
* I have made public functions as methods and to actually implement recursive
@@ -31,30 +33,8 @@ public class BSTRecursive {
root = null;
}
- /**
- * main function for tests
- */
- public static void main(String[] args) {
- BSTRecursive tree = new BSTRecursive();
- tree.add(5);
- tree.add(10);
- tree.add(9);
- assert !tree.find(4) : "4 is not yet present in BST";
- assert tree.find(10) : "10 should be present in BST";
- tree.remove(9);
- assert !tree.find(9) : "9 was just deleted from BST";
- tree.remove(1);
- assert !tree.find(
- 1
- ) : "Since 1 was not present so find deleting would do no change";
- tree.add(20);
- tree.add(70);
- assert tree.find(70) : "70 was inserted but not found";
- /*
- Will print in following order
- 5 10 20 70
- */
- tree.inorder();
+ public Node getRoot() {
+ return root;
}
/**
@@ -82,7 +62,7 @@ private Node delete(Node node, int data) {
Node temp = node.left;
node.left = null;
node = temp;
- } else { // both child are present
+ } else { // both children are present
Node temp = node.right;
// Find leftmost child of right subtree
while (temp.left != null) {
@@ -114,60 +94,6 @@ private Node insert(Node node, int data) {
return node;
}
- /**
- * Recursively print Preorder traversal of the BST
- *
- * @param node the root node
- */
- private void preOrder(Node node) {
- if (node == null) {
- return;
- }
- System.out.print(node.data + " ");
- if (node.left != null) {
- preOrder(node.left);
- }
- if (node.right != null) {
- preOrder(node.right);
- }
- }
-
- /**
- * Recursively print Postorder travesal of BST.
- *
- * @param node the root node
- */
- private void postOrder(Node node) {
- if (node == null) {
- return;
- }
- if (node.left != null) {
- postOrder(node.left);
- }
- if (node.right != null) {
- postOrder(node.right);
- }
- System.out.print(node.data + " ");
- }
-
- /**
- * Recursively print Inorder traversal of BST.
- *
- * @param node the root node
- */
- private void inOrder(Node node) {
- if (node == null) {
- return;
- }
- if (node.left != null) {
- inOrder(node.left);
- }
- System.out.print(node.data + " ");
- if (node.right != null) {
- inOrder(node.right);
- }
- }
-
/**
* Serach recursively if the given value is present in BST or not.
*
@@ -206,33 +132,6 @@ public void remove(int data) {
this.root = delete(this.root, data);
}
- /**
- * To call inorder traversal on tree
- */
- public void inorder() {
- System.out.println("Inorder traversal of this tree is:");
- inOrder(this.root);
- System.out.println(); // for next line
- }
-
- /**
- * To call postorder traversal on tree
- */
- public void postorder() {
- System.out.println("Postorder traversal of this tree is:");
- postOrder(this.root);
- System.out.println(); // for next li
- }
-
- /**
- * To call preorder traversal on tree.
- */
- public void preorder() {
- System.out.println("Preorder traversal of this tree is:");
- preOrder(this.root);
- System.out.println(); // for next li
- }
-
/**
* To check if given value is present in tree or not.
*
@@ -246,23 +145,4 @@ public boolean find(int data) {
System.out.println(data + " not found.");
return false;
}
-
- /**
- * The Node class used for building binary search tree
- */
- private static class Node {
-
- int data;
- Node left;
- Node right;
-
- /**
- * Constructor with data as parameter
- */
- Node(int d) {
- data = d;
- left = null;
- right = null;
- }
- }
}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java
new file mode 100644
index 000000000000..07bcd2aa15b6
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/trees/BSTRecursiveTest.java
@@ -0,0 +1,61 @@
+package com.thealgorithms.datastructures.trees;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * @author Albina Gimaletdinova on 06/05/2023
+ */
+public class BSTRecursiveTest {
+ @Test
+ public void testBSTIsCorrectlyConstructedFromOneNode() {
+ BSTRecursive tree = new BSTRecursive();
+ tree.add(6);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+
+ @Test
+ public void testBSTIsCorrectlyCleanedAndEmpty() {
+ BSTRecursive tree = new BSTRecursive();
+
+ tree.add(6);
+ tree.remove(6);
+
+ tree.add(12);
+ tree.add(1);
+ tree.add(2);
+
+ tree.remove(1);
+ tree.remove(2);
+ tree.remove(12);
+
+ Assertions.assertNull(tree.getRoot());
+ }
+
+ @Test
+ public void testBSTIsCorrectlyCleanedAndNonEmpty() {
+ BSTRecursive tree = new BSTRecursive();
+
+ tree.add(6);
+ tree.remove(6);
+
+ tree.add(12);
+ tree.add(1);
+ tree.add(2);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+
+ @Test
+ public void testBSTIsCorrectlyConstructedFromMultipleNodes() {
+ BSTRecursive tree = new BSTRecursive();
+ tree.add(7);
+ tree.add(1);
+ tree.add(5);
+ tree.add(100);
+ tree.add(50);
+
+ Assertions.assertTrue(CheckBinaryTreeIsValidBST.isBST(tree.getRoot()));
+ }
+}
From 3109c11c599e4139e431f3b0f00051e017abf6d6 Mon Sep 17 00:00:00 2001
From: "Md. Asif Joardar"
Date: Tue, 9 May 2023 16:21:11 +0600
Subject: [PATCH 0033/1457] Add Partition Problem (#4182)
---
.../dynamicprogramming/PartitionProblem.java | 40 +++++++++++++++++++
.../dynamicprogramming/SubsetSum.java | 2 +-
.../PartitionProblemTest.java | 24 +++++++++++
3 files changed, 65 insertions(+), 1 deletion(-)
create mode 100644 src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
create mode 100644 src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
new file mode 100644
index 000000000000..1fbbaf469342
--- /dev/null
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
@@ -0,0 +1,40 @@
+/**
+ * @author Md Asif Joardar
+ *
+ * Description: The partition problem is a classic problem in computer science
+ * that asks whether a given set can be partitioned into two subsets such that
+ * the sum of elements in each subset is the same.
+ *
+ * Example:
+ * Consider nums = {1, 2, 3}
+ * We can split the array "nums" into two partitions, where each having a sum of 3.
+ * nums1 = {1, 2}
+ * nums2 = {3}
+ *
+ * The time complexity of the solution is O(n × sum) and requires O(n × sum) space
+ */
+
+package com.thealgorithms.dynamicprogramming;
+
+import java.util.Arrays;
+
+public class PartitionProblem {
+
+ /**
+ * Test if a set of integers can be partitioned into two subsets such that the sum of elements
+ * in each subset is the same.
+ *
+ * @param nums the array contains integers.
+ * @return {@code true} if two subset exists, otherwise {@code false}.
+ */
+ public static boolean partition(int[] nums)
+ {
+ // calculate the sum of all the elements in the array
+ int sum = Arrays.stream(nums).sum();
+
+ // it will return true if the sum is even and the array can be divided into two subarrays/subset with equal sum.
+ // and here i reuse the SubsetSum class from dynamic programming section to check if there is exists a
+ // subsetsum into nums[] array same as the given sum
+ return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum/2);
+ }
+}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
index 89544266c9b3..07cb448a8353 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
@@ -22,7 +22,7 @@ public static void main(String[] args) {
* @param sum target sum of subset.
* @return {@code true} if subset exists, otherwise {@code false}.
*/
- private static boolean subsetSum(int[] arr, int sum) {
+ public static boolean subsetSum(int[] arr, int sum) {
int n = arr.length;
boolean[][] isSum = new boolean[n + 2][sum + 1];
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java
new file mode 100644
index 000000000000..ad0aac266c8d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/PartitionProblemTest.java
@@ -0,0 +1,24 @@
+package com.thealgorithms.dynamicprogramming;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class PartitionProblemTest {
+ @Test
+ public void testIfSumOfTheArrayIsOdd(){
+ assertFalse(PartitionProblem.partition(new int[]{1, 2, 2}));
+ }
+ @Test
+ public void testIfSizeOfTheArrayIsOne(){
+ assertFalse(PartitionProblem.partition(new int[]{2}));
+ }
+ @Test
+ public void testIfSumOfTheArrayIsEven1(){
+ assertTrue(PartitionProblem.partition(new int[]{1, 2, 3, 6}));
+ }
+ @Test
+ public void testIfSumOfTheArrayIsEven2(){
+ assertFalse(PartitionProblem.partition(new int[]{1, 2, 3, 8}));
+ }
+}
\ No newline at end of file
From 122f5e5556fa33853d8c73a4aecc1e0f3cda53ca Mon Sep 17 00:00:00 2001
From: "Md. Asif Joardar"
Date: Wed, 10 May 2023 19:04:55 +0600
Subject: [PATCH 0034/1457] Add Round Robin scheduling (#4184)
---
.../scheduling/RRScheduling.java | 99 +++++++++++++++++++
.../scheduling/RRSchedulingTest.java | 65 ++++++++++++
2 files changed, 164 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/scheduling/RRScheduling.java
create mode 100644 src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java
diff --git a/src/main/java/com/thealgorithms/scheduling/RRScheduling.java b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
new file mode 100644
index 000000000000..6d26bfd7f34b
--- /dev/null
+++ b/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
@@ -0,0 +1,99 @@
+/**
+ * @author Md Asif Joardar
+ */
+
+package com.thealgorithms.scheduling;
+
+import com.thealgorithms.devutils.entities.ProcessDetails;
+
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+
+/**
+ * The Round-robin scheduling algorithm is a kind of preemptive First come, First Serve CPU Scheduling algorithm.
+ * This can be understood here - https://www.scaler.com/topics/round-robin-scheduling-in-os/
+ */
+
+public class RRScheduling {
+ private List processes;
+ private int quantumTime;
+
+ RRScheduling(final List processes, int quantumTime) {
+ this.processes = processes;
+ this.quantumTime = quantumTime;
+ }
+
+ public void scheduleProcesses() {
+ evaluateTurnAroundTime();
+ evaluateWaitingTime();
+ }
+
+ private void evaluateTurnAroundTime() {
+ int processesNumber = processes.size();
+
+ if(processesNumber == 0) {
+ return;
+ }
+
+ Queue queue = new LinkedList<>();
+ queue.add(0);
+ int currentTime = 0; // keep track of the time
+ int completed = 0;
+ int[] mark = new int[processesNumber];
+ Arrays.fill(mark, 0);
+ mark[0] = 1;
+
+ // a copy of burst time to store the remaining burst time
+ int[] remainingBurstTime = new int[processesNumber];
+ for (int i = 0; i < processesNumber; i++) {
+ remainingBurstTime[i] = processes.get(i).getBurstTime();
+ }
+
+ while (completed != processesNumber){
+ int index = queue.poll();
+
+ if(remainingBurstTime[index] == processes.get(index).getBurstTime()){
+ currentTime = Math.max(currentTime, processes.get(index).getArrivalTime());
+ }
+
+ if(remainingBurstTime[index] - quantumTime > 0){
+ remainingBurstTime[index] -= quantumTime;
+ currentTime += quantumTime;
+ } else {
+ currentTime += remainingBurstTime[index];
+ processes.get(index).setTurnAroundTimeTime(currentTime - processes.get(index).getArrivalTime());
+ completed++;
+ remainingBurstTime[index]=0;
+ }
+
+ // If some process has arrived when this process was executing, insert them into the queue.
+ for (int i=1; i < processesNumber; i++){
+ if(remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime && mark[i] == 0){
+ mark[i]=1;
+ queue.add(i);
+ }
+ }
+
+ // If the current process has burst time remaining, push the process into the queue again.
+ if(remainingBurstTime[index] > 0) queue.add(index);
+
+ // If the queue is empty, pick the first process from the list that is not completed.
+ if(queue.isEmpty()){
+ for (int i=1; i 0){
+ mark[i] = 1;
+ queue.add(i);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ private void evaluateWaitingTime() {
+ for (int i = 0; i < processes.size(); i++)
+ processes.get(i).setWaitingTime(processes.get(i).getTurnAroundTimeTime() - processes.get(i).getBurstTime());
+ }
+}
diff --git a/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java
new file mode 100644
index 000000000000..935ff733562f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/scheduling/RRSchedulingTest.java
@@ -0,0 +1,65 @@
+package com.thealgorithms.scheduling;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import com.thealgorithms.devutils.entities.ProcessDetails;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+class RRSchedulingTest {
+ @Test
+ public void testingProcesses() {
+ List processes = addProcessesForRR();
+ final RRScheduling rrScheduling = new RRScheduling(processes, 4); // for sending to RR with quantum value 4
+
+ rrScheduling.scheduleProcesses();
+
+ assertEquals(6, processes.size());
+
+ assertEquals("P1", processes.get(0).getProcessId());
+ assertEquals(12, processes.get(0).getWaitingTime());
+ assertEquals(17, processes.get(0).getTurnAroundTimeTime());
+
+ assertEquals("P2", processes.get(1).getProcessId());
+ assertEquals(16, processes.get(1).getWaitingTime());
+ assertEquals(22, processes.get(1).getTurnAroundTimeTime());
+
+ assertEquals("P3", processes.get(2).getProcessId());
+ assertEquals(6, processes.get(2).getWaitingTime());
+ assertEquals(9, processes.get(2).getTurnAroundTimeTime());
+
+ assertEquals("P4", processes.get(3).getProcessId());
+ assertEquals(8, processes.get(3).getWaitingTime());
+ assertEquals(9, processes.get(3).getTurnAroundTimeTime());
+
+ assertEquals("P5", processes.get(4).getProcessId());
+ assertEquals(15, processes.get(4).getWaitingTime());
+ assertEquals(20, processes.get(4).getTurnAroundTimeTime());
+
+ assertEquals("P6", processes.get(5).getProcessId());
+ assertEquals(11, processes.get(5).getWaitingTime());
+ assertEquals(15, processes.get(5).getTurnAroundTimeTime());
+
+ }
+
+ private List addProcessesForRR() {
+ final ProcessDetails process1 = new ProcessDetails("P1", 0, 5);
+ final ProcessDetails process2 = new ProcessDetails("P2", 1, 6);
+ final ProcessDetails process3 = new ProcessDetails("P3", 2, 3);
+ final ProcessDetails process4 = new ProcessDetails("P4", 3, 1);
+ final ProcessDetails process5 = new ProcessDetails("P5", 4, 5);
+ final ProcessDetails process6 = new ProcessDetails("P6", 6, 4);
+
+ final List processDetails = new ArrayList<>();
+ processDetails.add(process1);
+ processDetails.add(process2);
+ processDetails.add(process3);
+ processDetails.add(process4);
+ processDetails.add(process5);
+ processDetails.add(process6);
+
+ return processDetails;
+ }
+}
\ No newline at end of file
From de2696d0c5036183739c1617b7384e608a7e6c27 Mon Sep 17 00:00:00 2001
From: Anirudh Pathak
Date: Wed, 10 May 2023 17:30:41 +0100
Subject: [PATCH 0035/1457] Add Null/Empty check for param in average method
(#4185)
---
src/main/java/com/thealgorithms/maths/Average.java | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/src/main/java/com/thealgorithms/maths/Average.java b/src/main/java/com/thealgorithms/maths/Average.java
index 6f2c27a91bba..ad37b78718c3 100644
--- a/src/main/java/com/thealgorithms/maths/Average.java
+++ b/src/main/java/com/thealgorithms/maths/Average.java
@@ -12,6 +12,9 @@ public class Average {
* @return mean of given numbers
*/
public static double average(double[] numbers) {
+ if (numbers == null || numbers.length == 0) {
+ throw new IllegalArgumentException("Numbers array cannot be empty or null");
+ }
double sum = 0;
for (double number : numbers) {
sum += number;
@@ -27,6 +30,9 @@ public static double average(double[] numbers) {
* @return average value
*/
public static int average(int[] numbers) {
+ if (numbers == null || numbers.length == 0) {
+ throw new IllegalArgumentException("Numbers array cannot be empty or null");
+ }
long sum = 0;
for (int number : numbers) {
sum += number;
From 02557053884690f407ae2b8308f23ce445ac9f64 Mon Sep 17 00:00:00 2001
From: Anirudh Pathak
Date: Fri, 12 May 2023 20:44:16 +0100
Subject: [PATCH 0036/1457] Add WordSearch (#4189)
---
.../backtracking/WordSearch.java | 79 +++++++++++++++++++
.../backtracking/WordSearchTest.java | 32 ++++++++
2 files changed, 111 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/backtracking/WordSearch.java
create mode 100644 src/test/java/com/thealgorithms/backtracking/WordSearchTest.java
diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
new file mode 100644
index 000000000000..affac0ee6ac2
--- /dev/null
+++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
@@ -0,0 +1,79 @@
+package com.thealgorithms.backtracking;
+
+
+/*
+Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
+
+Given an m x n grid of characters board and a string word, return true if word exists in the grid.
+
+The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or
+vertically neighboring. The same letter cell may not be used more than once.
+
+For example,
+Given board =
+
+[
+ ['A','B','C','E'],
+ ['S','F','C','S'],
+ ['A','D','E','E']
+]
+word = "ABCCED", -> returns true,
+word = "SEE", -> returns true,
+word = "ABCB", -> returns false.
+*/
+
+/*
+ Solution
+ Depth First Search in matrix (as multiple sources possible) with backtracking
+ like finding cycle in a directed graph. Maintain a record of path
+
+ Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times
+ Sx = O(L) : stack size is max L
+*/
+
+public class WordSearch {
+ private final int[] dx = {0, 0, 1, -1};
+ private final int[] dy = {1, -1, 0, 0};
+ private boolean[][] visited;
+ private char[][] board;
+ private String word;
+
+ private boolean isValid(int x, int y) {
+ return x >= 0 && x < board.length && y >= 0 && y < board[0].length;
+ }
+
+ private boolean doDFS(int x, int y, int nextIdx) {
+ visited[x][y] = true;
+ if (nextIdx == word.length()) {
+ return true;
+ }
+ for (int i = 0; i < 4; ++i) {
+ int xi = x + dx[i];
+ int yi = y + dy[i];
+ if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
+ boolean exists = doDFS(xi, yi, nextIdx + 1);
+ if (exists)
+ return true;
+ }
+ }
+ visited[x][y] = false;
+ return false;
+ }
+
+ public boolean exist(char[][] board, String word) {
+ this.board = board;
+ this.word = word;
+ for (int i = 0; i < board.length; ++i) {
+ for (int j = 0; j < board[0].length; ++j) {
+ if (board[i][j] == word.charAt(0)) {
+ visited = new boolean[board.length][board[0].length];
+ boolean exists = doDFS(i, j, 1);
+ if (exists)
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
+
diff --git a/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java
new file mode 100644
index 000000000000..198217bba0e3
--- /dev/null
+++ b/src/test/java/com/thealgorithms/backtracking/WordSearchTest.java
@@ -0,0 +1,32 @@
+package com.thealgorithms.backtracking;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class WordSearchTest {
+ @Test
+ void test1() {
+ WordSearch ws = new WordSearch();
+ char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
+ String word = "ABCCED";
+ assertTrue(ws.exist(board, word));
+ }
+
+ @Test
+ void test2() {
+ WordSearch ws = new WordSearch();
+ char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
+ String word = "SEE";
+ assertTrue(ws.exist(board, word));
+ }
+
+ @Test
+ void test3() {
+ WordSearch ws = new WordSearch();
+ char[][] board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
+ String word = "ABCB";
+ Assertions.assertFalse(ws.exist(board, word));
+ }
+}
\ No newline at end of file
From deef2ae4456c24a21c56d4cc9d5680c0f76dbdad Mon Sep 17 00:00:00 2001
From: Albina Gimaletdinova
Date: Sun, 14 May 2023 14:52:30 +0300
Subject: [PATCH 0037/1457] Refactor CreateBinaryTreeFromInorderPreorder
(#4190)
---
.../CreateBinaryTreeFromInorderPreorder.java | 137 +++++++-----------
...eateBinaryTreeFromInorderPreorderTest.java | 103 +++++++++++++
2 files changed, 156 insertions(+), 84 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
index d99d167b96fd..99b1fb4efe97 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
@@ -1,6 +1,7 @@
package com.thealgorithms.datastructures.trees;
import com.thealgorithms.datastructures.trees.BinaryTree.Node;
+
import java.util.HashMap;
import java.util.Map;
@@ -11,66 +12,37 @@
* subtree. Based on that index create left and right subtree. Complexity: Time:
* O(n^2) for each node there is iteration to find index in inorder array Space:
* Stack size = O(height) = O(lg(n))
- *
+ *
* Optimized Solution: Instead of iterating over inorder array to find index of
* root value, create a hashmap and find out the index of root value.
* Complexity: Time: O(n) hashmap reduced iteration to find index in inorder
* array Space: O(n) space taken by hashmap
- *
*/
public class CreateBinaryTreeFromInorderPreorder {
-
- public static void main(String[] args) {
- test(new Integer[] {}, new Integer[] {}); // empty tree
- test(new Integer[] { 1 }, new Integer[] { 1 }); // single node tree
- test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 1, 2, 3, 4 }); // right skewed tree
- test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 4, 3, 2, 1 }); // left skewed tree
- test(
- new Integer[] { 3, 9, 20, 15, 7 },
- new Integer[] { 9, 3, 15, 20, 7 }
- ); // normal tree
+ public static Node createTree(final Integer[] preorder, final Integer[] inorder) {
+ if (preorder == null || inorder == null) {
+ return null;
+ }
+ return createTree(preorder, inorder, 0, 0, inorder.length);
}
- private static void test(
- final Integer[] preorder,
- final Integer[] inorder
- ) {
- System.out.println(
- "\n===================================================="
- );
- System.out.println("Naive Solution...");
- BinaryTree root = new BinaryTree(
- createTree(preorder, inorder, 0, 0, inorder.length)
- );
- System.out.println("Preorder Traversal: ");
- root.preOrder(root.getRoot());
- System.out.println("\nInorder Traversal: ");
- root.inOrder(root.getRoot());
- System.out.println("\nPostOrder Traversal: ");
- root.postOrder(root.getRoot());
-
- Map map = new HashMap<>();
+ public static Node createTreeOptimized(final Integer[] preorder, final Integer[] inorder) {
+ if (preorder == null || inorder == null) {
+ return null;
+ }
+ Map inorderMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
- map.put(inorder[i], i);
+ inorderMap.put(inorder[i], i);
}
- BinaryTree optimizedRoot = new BinaryTree(
- createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map)
- );
- System.out.println("\n\nOptimized solution...");
- System.out.println("Preorder Traversal: ");
- optimizedRoot.preOrder(root.getRoot());
- System.out.println("\nInorder Traversal: ");
- optimizedRoot.inOrder(root.getRoot());
- System.out.println("\nPostOrder Traversal: ");
- optimizedRoot.postOrder(root.getRoot());
+ return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length);
}
private static Node createTree(
- final Integer[] preorder,
- final Integer[] inorder,
- final int preStart,
- final int inStart,
- final int size
+ final Integer[] preorder,
+ final Integer[] inorder,
+ final int preStart,
+ final int inStart,
+ final int size
) {
if (size == 0) {
return null;
@@ -78,37 +50,36 @@ private static Node createTree(
Node root = new Node(preorder[preStart]);
int i = inStart;
- while (preorder[preStart] != inorder[i]) {
+ while (!preorder[preStart].equals(inorder[i])) {
i++;
}
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left =
- createTree(
- preorder,
- inorder,
- preStart + 1,
- inStart,
- leftNodesCount
- );
+ createTree(
+ preorder,
+ inorder,
+ preStart + 1,
+ inStart,
+ leftNodesCount
+ );
root.right =
- createTree(
- preorder,
- inorder,
- preStart + leftNodesCount + 1,
- i + 1,
- rightNodesCount
- );
+ createTree(
+ preorder,
+ inorder,
+ preStart + leftNodesCount + 1,
+ i + 1,
+ rightNodesCount
+ );
return root;
}
private static Node createTreeOptimized(
- final Integer[] preorder,
- final Integer[] inorder,
- final int preStart,
- final int inStart,
- final int size,
- final Map inorderMap
+ final Integer[] preorder,
+ final Map inorderMap,
+ final int preStart,
+ final int inStart,
+ final int size
) {
if (size == 0) {
return null;
@@ -119,23 +90,21 @@ private static Node createTreeOptimized(
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left =
- createTreeOptimized(
- preorder,
- inorder,
- preStart + 1,
- inStart,
- leftNodesCount,
- inorderMap
- );
+ createTreeOptimized(
+ preorder,
+ inorderMap,
+ preStart + 1,
+ inStart,
+ leftNodesCount
+ );
root.right =
- createTreeOptimized(
- preorder,
- inorder,
- preStart + leftNodesCount + 1,
- i + 1,
- rightNodesCount,
- inorderMap
- );
+ createTreeOptimized(
+ preorder,
+ inorderMap,
+ preStart + leftNodesCount + 1,
+ i + 1,
+ rightNodesCount
+ );
return root;
}
}
diff --git a/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java
new file mode 100644
index 000000000000..59352f543914
--- /dev/null
+++ b/src/test/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorderTest.java
@@ -0,0 +1,103 @@
+package com.thealgorithms.datastructures.trees;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+
+/**
+ * @author Albina Gimaletdinova on 14/05/2023
+ */
+public class CreateBinaryTreeFromInorderPreorderTest {
+ @Test
+ public void testOnNullArraysShouldReturnNullTree() {
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(null, null);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(null, null);
+
+ // then
+ Assertions.assertNull(root);
+ Assertions.assertNull(rootOpt);
+ }
+
+ @Test
+ public void testOnEmptyArraysShouldCreateNullTree() {
+ // given
+ Integer[] preorder = {};
+ Integer[] inorder = {};
+
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
+
+ // then
+ Assertions.assertNull(root);
+ Assertions.assertNull(rootOpt);
+ }
+
+ @Test
+ public void testOnSingleNodeTreeShouldCreateCorrectTree() {
+ // given
+ Integer[] preorder = {1};
+ Integer[] inorder = {1};
+
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
+
+ // then
+ checkTree(preorder, inorder, root);
+ checkTree(preorder, inorder, rootOpt);
+ }
+
+ @Test
+ public void testOnRightSkewedTreeShouldCreateCorrectTree() {
+ // given
+ Integer[] preorder = {1, 2, 3, 4};
+ Integer[] inorder = {1, 2, 3, 4};
+
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
+
+ // then
+ checkTree(preorder, inorder, root);
+ checkTree(preorder, inorder, rootOpt);
+ }
+
+ @Test
+ public void testOnLeftSkewedTreeShouldCreateCorrectTree() {
+ // given
+ Integer[] preorder = {1, 2, 3, 4};
+ Integer[] inorder = {4, 3, 2, 1};
+
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
+
+ // then
+ checkTree(preorder, inorder, root);
+ checkTree(preorder, inorder, rootOpt);
+ }
+
+ @Test
+ public void testOnNormalTreeShouldCreateCorrectTree() {
+ // given
+ Integer[] preorder = {3, 9, 20, 15, 7};
+ Integer[] inorder = {9, 3, 15, 20, 7};
+
+ // when
+ BinaryTree.Node root = CreateBinaryTreeFromInorderPreorder.createTree(preorder, inorder);
+ BinaryTree.Node rootOpt = CreateBinaryTreeFromInorderPreorder.createTreeOptimized(preorder, inorder);
+
+ // then
+ checkTree(preorder, inorder, root);
+ checkTree(preorder, inorder, rootOpt);
+ }
+
+ private static void checkTree(Integer[] preorder, Integer[] inorder, BinaryTree.Node root) {
+ Assertions.assertNotNull(root);
+ Assertions.assertEquals(PreOrderTraversal.iterativePreOrder(root), Arrays.asList(preorder));
+ Assertions.assertEquals(InorderTraversal.iterativeInorder(root), Arrays.asList(inorder));
+ }
+}
From 9ce275c16d9657622e0329c79ec3aecd2d4289c8 Mon Sep 17 00:00:00 2001
From: Indrranil Pawar <112892653+Indrranil@users.noreply.github.com>
Date: Sun, 21 May 2023 11:08:54 +0530
Subject: [PATCH 0038/1457] Update FibonacciNumber.java (#4195)
---
.../thealgorithms/maths/FibonacciNumber.java | 17 ++++++++---------
1 file changed, 8 insertions(+), 9 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/FibonacciNumber.java b/src/main/java/com/thealgorithms/maths/FibonacciNumber.java
index 17a8de61d1c9..c39f2a8bcad9 100644
--- a/src/main/java/com/thealgorithms/maths/FibonacciNumber.java
+++ b/src/main/java/com/thealgorithms/maths/FibonacciNumber.java
@@ -17,8 +17,8 @@ public static void main(String[] args) {
* Check if a number is perfect square number
*
* @param number the number to be checked
- * @return true if {@code number} is perfect square, otherwise
- * false
+ * @return true if {@code number} is a perfect square, otherwise
+ * false
*/
public static boolean isPerfectSquare(int number) {
int sqrt = (int) Math.sqrt(number);
@@ -26,18 +26,17 @@ public static boolean isPerfectSquare(int number) {
}
/**
- * Check if a number is fibonacci number This is true if and only if at
+ * Check if a number is a Fibonacci number. This is true if and only if at
* least one of 5x^2+4 or 5x^2-4 is a perfect square
*
* @param number the number
- * @return true if {@code number} is fibonacci number, otherwise
- * false
+ * @return true if {@code number} is a Fibonacci number, otherwise
+ * false
* @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
*/
public static boolean isFibonacciNumber(int number) {
- return (
- isPerfectSquare(5 * number * number + 4) ||
- isPerfectSquare(5 * number * number - 4)
- );
+ int value1 = 5 * number * number + 4;
+ int value2 = 5 * number * number - 4;
+ return isPerfectSquare(value1) || isPerfectSquare(value2);
}
}
From 36232a8373264319cdb893bf9da1615fea05999d Mon Sep 17 00:00:00 2001
From: Glib <71976818+GLEF1X@users.noreply.github.com>
Date: Tue, 23 May 2023 02:38:44 -0400
Subject: [PATCH 0039/1457] Fix typo (#4197)
---
src/main/java/com/thealgorithms/sorts/QuickSort.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/main/java/com/thealgorithms/sorts/QuickSort.java b/src/main/java/com/thealgorithms/sorts/QuickSort.java
index 94ed869a901d..c0fe66e24565 100644
--- a/src/main/java/com/thealgorithms/sorts/QuickSort.java
+++ b/src/main/java/com/thealgorithms/sorts/QuickSort.java
@@ -40,7 +40,7 @@ private static > void doSort(
}
/**
- * Ramdomize the array to avoid the basically ordered sequences
+ * Randomize the array to avoid the basically ordered sequences
*
* @param array The array to be sorted
* @param left The first index of an array
From e14b30b88c0de95186fe1937f795b7d8fd3fa8aa Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sat, 27 May 2023 16:58:56 +0200
Subject: [PATCH 0040/1457] Fix empty input handling in GCD (#4199)
---
src/main/java/com/thealgorithms/maths/GCD.java | 14 +++++++-------
.../java/com/thealgorithms/maths/GCDTest.java | 15 +++++++++++++++
2 files changed, 22 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/GCD.java b/src/main/java/com/thealgorithms/maths/GCD.java
index c05f96332e55..96a2b47dc99d 100644
--- a/src/main/java/com/thealgorithms/maths/GCD.java
+++ b/src/main/java/com/thealgorithms/maths/GCD.java
@@ -33,15 +33,15 @@ public static int gcd(int num1, int num2) {
}
/**
- * get greatest common divisor in array
+ * @brief computes gcd of an array of numbers
*
- * @param number contains number
- * @return gcd
+ * @param numbers the input array
+ * @return gcd of all of the numbers in the input array
*/
- public static int gcd(int[] number) {
- int result = number[0];
- for (int i = 1; i < number.length; i++) { // call gcd function (input two value)
- result = gcd(result, number[i]);
+ public static int gcd(int[] numbers) {
+ int result = 0;
+ for (final var number : numbers) {
+ result = gcd(result, number);
}
return result;
diff --git a/src/test/java/com/thealgorithms/maths/GCDTest.java b/src/test/java/com/thealgorithms/maths/GCDTest.java
index e18d3ea82951..bbf10cad0bdb 100644
--- a/src/test/java/com/thealgorithms/maths/GCDTest.java
+++ b/src/test/java/com/thealgorithms/maths/GCDTest.java
@@ -48,4 +48,19 @@ void test6() {
void test7() {
Assertions.assertEquals(GCD.gcd(9, 6), 3);
}
+
+ @Test
+ void testArrayGcd1() {
+ Assertions.assertEquals(GCD.gcd(new int[]{9, 6}), 3);
+ }
+
+ @Test
+ void testArrayGcd2() {
+ Assertions.assertEquals(GCD.gcd(new int[]{2*3*5*7, 2*5*5*5, 2*5*11, 5*5*5*13}), 5);
+ }
+
+ @Test
+ void testArrayGcdForEmptyInput() {
+ Assertions.assertEquals(GCD.gcd(new int[]{}), 0);
+ }
}
From 4f1514980495c4daaae2eb060228a87e14cbae11 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sun, 28 May 2023 13:08:44 +0200
Subject: [PATCH 0041/1457] style: handle empty input array in
`FindMin.findMin` (#4205)
* tests: add test case with mininum not being at the beginning
* style: throw IllegalArgumentException when input is empty
* style: use enhanced for loop
* docs: update doc-str
---
.../java/com/thealgorithms/maths/FindMin.java | 18 +++++++++++-------
.../com/thealgorithms/maths/FindMinTest.java | 14 ++++++++++++++
2 files changed, 25 insertions(+), 7 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/FindMin.java b/src/main/java/com/thealgorithms/maths/FindMin.java
index e3be09e34644..7764c1c049b4 100644
--- a/src/main/java/com/thealgorithms/maths/FindMin.java
+++ b/src/main/java/com/thealgorithms/maths/FindMin.java
@@ -24,16 +24,20 @@ public static void main(String[] args) {
}
/**
- * Find the minimum number of an array of numbers.
+ * @brief finds the minimum value stored in the input array
*
- * @param array the array contains element
- * @return min value
+ * @param array the input array
+ * @exception IllegalArgumentException input array is empty
+ * @return the mimum value stored in the input array
*/
public static int findMin(int[] array) {
- int min = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] < min) {
- min = array[i];
+ if (array.length == 0) {
+ throw new IllegalArgumentException("array must be non-empty.");
+ }
+ int min = Integer.MAX_VALUE;
+ for (final var value : array) {
+ if (value < min) {
+ min = value;
}
}
return min;
diff --git a/src/test/java/com/thealgorithms/maths/FindMinTest.java b/src/test/java/com/thealgorithms/maths/FindMinTest.java
index 48fcb277d96f..dc9835475a08 100644
--- a/src/test/java/com/thealgorithms/maths/FindMinTest.java
+++ b/src/test/java/com/thealgorithms/maths/FindMinTest.java
@@ -1,6 +1,7 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@@ -23,4 +24,17 @@ public void test1() {
public void test2() {
assertEquals(0, FindMin.findMin(new int[] { 0, 192, 384, 576 }));
}
+
+ @Test
+ public void test3() {
+ assertEquals(0, FindMin.findMin(new int[] { 10, 10, 0, 10 }));
+ }
+
+ @Test
+ public void testFindMinThrowsExceptionForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> FindMin.findMin(new int[]{})
+ );
+ }
}
From 96c1a96647c947f8f0c531ade3bc18967359e0ea Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Sun, 28 May 2023 22:45:13 +0200
Subject: [PATCH 0042/1457] Fix empty input handling in FindMax (#4206)
---
.../java/com/thealgorithms/maths/FindMax.java | 18 ++++++++-----
.../com/thealgorithms/maths/FindMaxTest.java | 27 ++++++++++++++++++-
2 files changed, 37 insertions(+), 8 deletions(-)
diff --git a/src/main/java/com/thealgorithms/maths/FindMax.java b/src/main/java/com/thealgorithms/maths/FindMax.java
index a7be8690952b..559424fe15df 100644
--- a/src/main/java/com/thealgorithms/maths/FindMax.java
+++ b/src/main/java/com/thealgorithms/maths/FindMax.java
@@ -24,16 +24,20 @@ public static void main(String[] args) {
}
/**
- * find max of array
+ * @brief finds the maximum value stored in the input array
*
- * @param array the array contains element
- * @return max value of given array
+ * @param array the input array
+ * @exception IllegalArgumentException input array is empty
+ * @return the maximum value stored in the input array
*/
public static int findMax(int[] array) {
- int max = array[0];
- for (int i = 1; i < array.length; ++i) {
- if (array[i] > max) {
- max = array[i];
+ if (array.length == 0) {
+ throw new IllegalArgumentException("array must be non-empty.");
+ }
+ int max = Integer.MIN_VALUE;
+ for (final var value : array) {
+ if (value > max) {
+ max = value;
}
}
return max;
diff --git a/src/test/java/com/thealgorithms/maths/FindMaxTest.java b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
index 43daaeac0f49..a7a18fe198f1 100644
--- a/src/test/java/com/thealgorithms/maths/FindMaxTest.java
+++ b/src/test/java/com/thealgorithms/maths/FindMaxTest.java
@@ -1,16 +1,41 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class FindMaxTest {
@Test
- public void testFindMaxValue() {
+ public void testFindMax0() {
assertEquals(
10,
FindMax.findMax(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
);
}
+
+ @Test
+ public void testFindMax1() {
+ assertEquals(
+ 7,
+ FindMax.findMax(new int[] { 6, 3, 5, 1, 7, 4, 1 })
+ );
+ }
+
+ @Test
+ public void testFindMax2() {
+ assertEquals(
+ 10,
+ FindMax.findMax(new int[] { 10, 0 })
+ );
+ }
+
+ @Test
+ public void testFindMaxThrowsExceptionForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> FindMax.findMax(new int[]{})
+ );
+ }
}
From 5d7a59654fc4394162b69ee220c6c079c71a039b Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Mon, 29 May 2023 22:05:23 +0200
Subject: [PATCH 0043/1457] Refactor LowestBasePalindrome (#4207)
---
.../others/LowestBasePalindrome.java | 200 ++++++------------
.../others/LowestBasePalindromeTest.java | 87 ++++++++
2 files changed, 157 insertions(+), 130 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
diff --git a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
index 3d50b4840f17..addf82554470 100644
--- a/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
+++ b/src/main/java/com/thealgorithms/others/LowestBasePalindrome.java
@@ -1,153 +1,93 @@
package com.thealgorithms.others;
-import java.util.InputMismatchException;
-import java.util.Scanner;
+import java.util.ArrayList;
/**
- * Class for finding the lowest base in which a given integer is a palindrome.
- * Includes auxiliary methods for converting between bases and reversing
- * strings.
- *
- *
- * NOTE: There is potential for error, see note at line 63.
- *
- * @author RollandMichael
- * @version 2017.09.28
+ * @brief Class for finding the lowest base in which a given integer is a palindrome.
+ cf. https://oeis.org/A016026
*/
-public class LowestBasePalindrome {
+final public class LowestBasePalindrome {
+ private LowestBasePalindrome() {
+ }
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int n = 0;
- while (true) {
- try {
- System.out.print("Enter number: ");
- n = in.nextInt();
- break;
- } catch (InputMismatchException e) {
- System.out.println("Invalid input!");
- in.next();
- }
+ private static void checkBase(int base) {
+ if (base <= 1) {
+ throw new IllegalArgumentException("base must be greater than 1.");
+ }
+ }
+
+ private static void checkNumber(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("number must be nonnegative.");
}
- System.out.println(
- n + " is a palindrome in base " + lowestBasePalindrome(n)
- );
- System.out.println(
- base2base(Integer.toString(n), 10, lowestBasePalindrome(n))
- );
- in.close();
}
/**
- * Given a number in base 10, returns the lowest base in which the number is
- * represented by a palindrome (read the same left-to-right and
- * right-to-left).
- *
- * @param num A number in base 10.
- * @return The lowest base in which num is a palindrome.
+ * @brief computes the representation of the input number in given base
+ * @param number the input number
+ * @param base the given base
+ * @exception IllegalArgumentException number is negative or base is less than 2
+ * @return the list containing the digits of the input number in the given base, the most significant digit is at the end of the array
*/
- public static int lowestBasePalindrome(int num) {
- int base, num2 = num;
- int digit;
- char digitC;
- boolean foundBase = false;
- String newNum = "";
- String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
- while (!foundBase) {
- // Try from bases 2 to num-1
- for (base = 2; base < num2; base++) {
- newNum = "";
- while (num > 0) {
- // Obtain the first digit of n in the current base,
- // which is equivalent to the integer remainder of (n/base).
- // The next digit is obtained by dividing n by the base and
- // continuing the process of getting the remainder. This is done
- // until n is <=0 and the number in the new base is obtained.
- digit = (num % base);
- num /= base;
- // If the digit isn't in the set of [0-9][A-Z] (beyond base 36), its character
- // form is just its value in ASCII.
+ public static ArrayList computeDigitsInBase(int number, int base) {
+ checkNumber(number);
+ checkBase(base);
+ var result = new ArrayList();
+ while (number > 0) {
+ result.add(number % base);
+ number /= base;
+ }
+ return result;
+ }
- // NOTE: This may cause problems, as the capital letters are ASCII values
- // 65-90. It may cause false positives when one digit is, for instance 10 and assigned
- // 'A' from the character array and the other is 65 and also assigned 'A'.
- // Regardless, the character is added to the representation of n
- // in the current base.
- if (digit >= digits.length()) {
- digitC = (char) (digit);
- newNum += digitC;
- continue;
- }
- newNum += digits.charAt(digit);
- }
- // Num is assigned back its original value for the next iteration.
- num = num2;
- // Auxiliary method reverses the number.
- String reverse = reverse(newNum);
- // If the number is read the same as its reverse, then it is a palindrome.
- // The current base is returned.
- if (reverse.equals(newNum)) {
- foundBase = true;
- return base;
- }
+ /**
+ * @brief checks if the input array is a palindrome
+ * @brief list the input array
+ * @return true, if the input array is a palindrome, false otherwise
+ */
+ public static boolean isPalindromic(ArrayList list) {
+ for (int pos = 0; pos < list.size()/2; ++pos) {
+ if(list.get(pos) != list.get(list.size()-1-pos)) {
+ return false;
}
}
- // If all else fails, n is always a palindrome in base n-1. ("11")
- return num - 1;
+ return true;
}
- private static String reverse(String str) {
- String reverse = "";
- for (int i = str.length() - 1; i >= 0; i--) {
- reverse += str.charAt(i);
+ /**
+ * @brief checks if representation of the input number in given base is a palindrome
+ * @param number the input number
+ * @param base the given base
+ * @exception IllegalArgumentException number is negative or base is less than 2
+ * @return true, if the input number represented in the given base is a palindrome, false otherwise
+ */
+ public static boolean isPalindromicInBase(int number, int base) {
+ checkNumber(number);
+ checkBase(base);
+
+ if (number <= 1) {
+ return true;
}
- return reverse;
- }
- private static String base2base(String n, int b1, int b2) {
- // Declare variables: decimal value of n,
- // character of base b1, character of base b2,
- // and the string that will be returned.
- int decimalValue = 0, charB2;
- char charB1;
- String output = "";
- // Go through every character of n
- for (int i = 0; i < n.length(); i++) {
- // store the character in charB1
- charB1 = n.charAt(i);
- // if it is a non-number, convert it to a decimal value >9 and store it in charB2
- if (charB1 >= 'A' && charB1 <= 'Z') {
- charB2 = 10 + (charB1 - 'A');
- } // Else, store the integer value in charB2
- else {
- charB2 = charB1 - '0';
- }
- // Convert the digit to decimal and add it to the
- // decimalValue of n
- decimalValue = decimalValue * b1 + charB2;
+ if (number % base == 0) {
+ // the last digit of number written in base is 0
+ return false;
}
- // Converting the decimal value to base b2:
- // A number is converted from decimal to another base
- // by continuously dividing by the base and recording
- // the remainder until the quotient is zero. The number in the
- // new base is the remainders, with the last remainder
- // being the left-most digit.
- // While the quotient is NOT zero:
- while (decimalValue != 0) {
- // If the remainder is a digit < 10, simply add it to
- // the left side of the new number.
- if (decimalValue % b2 < 10) {
- output = decimalValue % b2 + output;
- } // If the remainder is >= 10, add a character with the
- // corresponding value to the new number. (A = 10, B = 11, C = 12, ...)
- else {
- output = (char) ((decimalValue % b2) + 55) + output;
- }
- // Divide by the new base again
- decimalValue /= b2;
+ return isPalindromic(computeDigitsInBase(number, base));
+ }
+
+ /**
+ * @brief finds the smallest base for which the representation of the input number is a palindrome
+ * @param number the input number
+ * @exception IllegalArgumentException number is negative
+ * @return the smallest base for which the representation of the input number is a palindrome
+ */
+ public static int lowestBasePalindrome(int number) {
+ int base = 2;
+ while(!isPalindromicInBase(number, base)) {
+ ++base;
}
- return output;
+ return base;
}
}
diff --git a/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
new file mode 100644
index 000000000000..3124d7b0224f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
@@ -0,0 +1,87 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import org.junit.jupiter.api.Test;
+
+public class LowestBasePalindromeTest {
+ @Test
+ public void testIsPalindromicPositive() {
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList()));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1))));
+ assertTrue(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 2, 1))));
+ }
+
+ @Test
+ public void testIsPalindromicNegative() {
+ assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2))));
+ assertFalse(LowestBasePalindrome.isPalindromic(new ArrayList(Arrays.asList(1, 2, 1, 1))));
+ }
+
+ @Test
+ public void testIsPalindromicInBasePositive() {
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(101, 10));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(1, 190));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(0, 11));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(10101, 10));
+ assertTrue(LowestBasePalindrome.isPalindromicInBase(23, 22));
+ }
+
+ @Test
+ public void testIsPalindromicInBaseNegative() {
+ assertFalse(LowestBasePalindrome.isPalindromicInBase(1010, 10));
+ assertFalse(LowestBasePalindrome.isPalindromicInBase(123, 10));
+ }
+
+ @Test
+ public void testIsPalindromicInBaseThrowsExceptionForNegativeNumbers() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LowestBasePalindrome.isPalindromicInBase(-1, 5)
+ );
+ }
+
+ @Test
+ public void testIsPalindromicInBaseThrowsExceptionForWrongBases() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> LowestBasePalindrome.isPalindromicInBase(10, 1)
+ );
+ }
+
+ @Test
+ public void testLowestBasePalindrome() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 2);
+ testCases.put(1, 2);
+ testCases.put(2, 3);
+ testCases.put(3, 2);
+ testCases.put(10, 3);
+ testCases.put(11, 10);
+ testCases.put(15, 2);
+ testCases.put(39, 12);
+ testCases.put(44, 10);
+ testCases.put(58, 28);
+ testCases.put(69, 22);
+ testCases.put(79, 78);
+ testCases.put(87, 28);
+ testCases.put(90, 14);
+ testCases.put(5591, 37);
+ testCases.put(5895, 130);
+ testCases.put(9950, 198);
+ testCases.put(9974, 4986);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(LowestBasePalindrome.lowestBasePalindrome(tc.getKey()), tc.getValue());
+ }
+ }
+}
From b6e78a45ac007570df4da7574b111a05000204d3 Mon Sep 17 00:00:00 2001
From: Bama Charan Chhandogi
Date: Tue, 30 May 2023 13:07:50 +0530
Subject: [PATCH 0044/1457] Add Octal To Binary Converter (#4202)
---
.../conversions/OctalToBinary.java | 42 +++++++++++++++++++
.../conversions/OctalToBinaryTest.java | 15 +++++++
2 files changed, 57 insertions(+)
create mode 100644 src/main/java/com/thealgorithms/conversions/OctalToBinary.java
create mode 100644 src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
diff --git a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java
new file mode 100644
index 000000000000..711381d82a8e
--- /dev/null
+++ b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java
@@ -0,0 +1,42 @@
+package com.thealgorithms.conversions;
+import java.util.Scanner;
+
+/**
+ * Converts any Octal Number to a Binary Number
+ *
+ * @author Bama Charan Chhandogi
+ */
+
+public class OctalToBinary {
+ public static long convertOctalToBinary(int octalNumber) {
+ long binaryNumber = 0;
+ int digitPosition = 1;
+
+ while (octalNumber != 0) {
+ int octalDigit = octalNumber % 10;
+ long binaryDigit = convertOctalDigitToBinary(octalDigit);
+
+ binaryNumber += binaryDigit * digitPosition;
+
+ octalNumber /= 10;
+ digitPosition *= 1000; // Move to the next group of 3 binary digits
+ }
+
+ return binaryNumber;
+ }
+
+ public static long convertOctalDigitToBinary(int octalDigit) {
+ long binaryDigit = 0;
+ int binaryMultiplier = 1;
+
+ while (octalDigit != 0) {
+ int octalDigitRemainder = octalDigit % 2;
+ binaryDigit += octalDigitRemainder * binaryMultiplier;
+
+ octalDigit /= 2;
+ binaryMultiplier *= 10;
+ }
+
+ return binaryDigit;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
new file mode 100644
index 000000000000..6c7fe8702b68
--- /dev/null
+++ b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java
@@ -0,0 +1,15 @@
+package com.thealgorithms.conversions;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+public class OctalToBinaryTest {
+ @Test
+ public void testConvertOctalToBinary() {
+ assertEquals(101, OctalToBinary.convertOctalToBinary(5));
+ assertEquals(1001, OctalToBinary.convertOctalToBinary(11));
+ assertEquals(101010, OctalToBinary.convertOctalToBinary(52));
+ assertEquals(110, OctalToBinary.convertOctalToBinary(6));
+ }
+}
From 4bbc4bd69f2a68963ba733df744c6ea356aba109 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Wed, 31 May 2023 08:07:55 +0200
Subject: [PATCH 0045/1457] Refactor ReverseNumber (#4208)
---
.../thealgorithms/maths/ReverseNumber.java | 43 ++++++++++---------
.../maths/ReverseNumberTest.java | 33 ++++++++++++++
2 files changed, 55 insertions(+), 21 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
diff --git a/src/main/java/com/thealgorithms/maths/ReverseNumber.java b/src/main/java/com/thealgorithms/maths/ReverseNumber.java
index a78c4de82163..8c74bfdf2132 100644
--- a/src/main/java/com/thealgorithms/maths/ReverseNumber.java
+++ b/src/main/java/com/thealgorithms/maths/ReverseNumber.java
@@ -1,30 +1,31 @@
package com.thealgorithms.maths;
-import java.lang.IllegalStateException;
-import java.util.NoSuchElementException;
-import java.util.Scanner;
+import java.lang.IllegalArgumentException;
-public class ReverseNumber {
-
- public static void main(String[] args) {
- int number;
- int reverse = 0;
+/**
+ * @brief utility class reversing numbers
+ */
+final public class ReverseNumber {
+ private ReverseNumber() {
+ }
- try (Scanner sc = new Scanner(System.in)) {
- System.out.println("Enter a number:");
- number = sc.nextInt();
- } catch (NoSuchElementException | IllegalStateException e) {
- System.out.println("ERROR: Invalid input");
- return;
+ /**
+ * @brief reverses the input number
+ * @param number the input number
+ * @exception IllegalArgumentException number is negative
+ * @return the number created by reversing the order of digits of the input number
+ */
+ public static int reverseNumber(int number) {
+ if (number < 0) {
+ throw new IllegalArgumentException("number must be nonnegative.");
}
- while (number != 0) {
- int remainder = number % 10;
-
- reverse = reverse * 10 + remainder;
- number = number / 10;
+ int result = 0;
+ while (number > 0) {
+ result *= 10;
+ result += number % 10;
+ number /= 10;
}
-
- System.out.println("The reverse of the given number is: " + reverse);
+ return result;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
new file mode 100644
index 000000000000..a6c25df5a541
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/ReverseNumberTest.java
@@ -0,0 +1,33 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+
+import org.junit.jupiter.api.Test;
+
+public class ReverseNumberTest {
+
+ @Test
+ public void testReverseNumber() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 0);
+ testCases.put(1, 1);
+ testCases.put(10, 1);
+ testCases.put(123, 321);
+ testCases.put(7890, 987);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(ReverseNumber.reverseNumber(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testReverseNumberThrowsExceptionForNegativeInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> ReverseNumber.reverseNumber(-1)
+ );
+ }
+}
From 22002c9939fdeff1d7ef659a688ad7f396dd564a Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Fri, 2 Jun 2023 13:17:26 +0200
Subject: [PATCH 0046/1457] Generalize NthUglyNumber (#4209)
---
.../thealgorithms/maths/NthUglyNumber.java | 113 +++++++++++-------
.../maths/NthUglyNumberTest.java | 87 ++++++++++++++
2 files changed, 156 insertions(+), 44 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
diff --git a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
index 4c040f570448..6daeb2673cd7 100644
--- a/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
+++ b/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
@@ -1,57 +1,82 @@
-// Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers.
-// By convention, 1 is included.
-// A program to find the nth Ugly number
-// Algorithm :
-// Initialize three-pointers two, three, and five pointing to zero.
-// Take 3 variables nm2, nm3, and nm5 to keep track of next multiple of 2,3 and 5.
-// Make an array of size n to store the ugly numbers with 1 at 0th index.
-// Initialize a variable next which stores the value of the last element in the array.
-// Run a loop n-1 times and perform steps 6,7 and 8.
-// Update the values of nm2, nm3, nm5 as ugly[two]*2, ugly[three]*3, ugly[5]*5 respectively.
-// Select the minimum value from nm2, nm3, and nm5 and increment the pointer related to it.
-// Store the minimum value in variable next and array.
-// Return next.
package com.thealgorithms.maths;
-import java.util.*;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.lang.IllegalArgumentException;
-class NthUglyNumber {
- /* Function to get the nth ugly number*/
- public long getNthUglyNo(int n) {
- long[] ugly = new long[n];
- int two = 0, three = 0, five = 0;
- long nm2 = 2, nm3 = 3, nm5 = 5;
- long next = 1;
+/**
+ * @brief class computing the n-th ugly number (when they are sorted)
+ * @details the ugly numbers with base [2, 3, 5] are all numbers of the form 2^a*3^b^5^c,
+ * where the exponents a, b, c are non-negative integers.
+ * Some properties of ugly numbers:
+ * - base [2, 3, 5] ugly numbers are the 5-smooth numbers, cf. https://oeis.org/A051037
+ * - base [2, 3, 5, 7] ugly numbers are 7-smooth numbers, cf. https://oeis.org/A002473
+ * - base [2] ugly numbers are the non-negative powers of 2,
+ * - the base [2, 3, 5] ugly numbers are the same as base [5, 6, 2, 3, 5] ugly numbers
+ */
+public class NthUglyNumber {
+ ArrayList uglyNumbers = new ArrayList<>(Arrays.asList(1L));
+ final int[] baseNumbers;
+ HashMap positions = new HashMap<>();
- ugly[0] = 1;
+ /**
+ * @brief initialized the object allowing to compute ugly numbers with given base
+ * @param baseNumbers the given base of ugly numbers
+ * @exception IllegalArgumentException baseNumber is empty
+ */
+ NthUglyNumber(int[] baseNumbers) {
+ if (baseNumbers.length == 0) {
+ throw new IllegalArgumentException("baseNumbers must be non-empty.");
+ }
- for (int i = 1; i < n; i++) {
- next = Math.min(nm2, Math.min(nm3, nm5));
+ this.baseNumbers = baseNumbers;
+ for (final var baseNumber : baseNumbers) {
+ this.positions.put(baseNumber, 0);
+ }
+ }
- ugly[i] = next;
- if (next == nm2) {
- two = two + 1;
- nm2 = ugly[two] * 2;
- }
- if (next == nm3) {
- three = three + 1;
- nm3 = ugly[three] * 3;
- }
- if (next == nm5) {
- five = five + 1;
- nm5 = ugly[five] * 5;
+ /**
+ * @param n the zero-based-index of the queried ugly number
+ * @exception IllegalArgumentException n is negative
+ * @return the n-th ugly number (starting from index 0)
+ */
+ public Long get(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("n must be non-negative.");
+ }
+
+ while (uglyNumbers.size() <= n) {
+ addUglyNumber();
+ }
+
+ return uglyNumbers.get(n);
+ }
+
+ private void addUglyNumber() {
+ uglyNumbers.add(computeMinimalCandidate());
+ updatePositions();
+ }
+
+ private void updatePositions() {
+ final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1);
+ for (final var baseNumber : baseNumbers) {
+ if (computeCandidate(baseNumber) == lastUglyNumber) {
+ positions.put(baseNumber, positions.get(baseNumber) + 1);
}
}
- return next;
}
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the value of n : ");
- int n = sc.nextInt();
- NthUglyNumber ob = new NthUglyNumber();
- long ugly = ob.getNthUglyNo(n);
- System.out.println("nth Ugly number is : " + ugly);
+ private long computeCandidate(int candidateBase) {
+ return candidateBase * uglyNumbers.get(positions.get(candidateBase));
+ }
+
+ private long computeMinimalCandidate() {
+ long res = Long.MAX_VALUE;
+ for (final var baseNumber : baseNumbers) {
+ res = Math.min(res, computeCandidate(baseNumber));
+ }
+ return res;
}
}
diff --git a/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
new file mode 100644
index 000000000000..597d08922069
--- /dev/null
+++ b/src/test/java/com/thealgorithms/maths/NthUglyNumberTest.java
@@ -0,0 +1,87 @@
+package com.thealgorithms.maths;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.HashMap;
+
+import org.junit.jupiter.api.Test;
+
+public class NthUglyNumberTest {
+ @Test
+ public void testGetWithNewObject() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 1L);
+ testCases.put(1, 2L);
+ testCases.put(2, 3L);
+ testCases.put(3, 4L);
+ testCases.put(4, 5L);
+ testCases.put(5, 6L);
+ testCases.put(9, 12L);
+ testCases.put(19, 36L);
+ testCases.put(52, 270L);
+ testCases.put(1078, 84934656L);
+ testCases.put(1963, 6973568802L);
+
+ for (final var tc : testCases.entrySet()) {
+ var uglyNumbers = new NthUglyNumber(new int[] {2, 3, 5});
+ assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue());
+
+ var otherUglyNumbers = new NthUglyNumber(new int[] {5, 25, 6, 2, 3, 5});
+ assertEquals(otherUglyNumbers.get(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testGetWithSameObject() {
+ HashMap testCases = new HashMap<>();
+ testCases.put(0, 1L);
+ testCases.put(1, 2L);
+ testCases.put(2, 3L);
+ testCases.put(3, 4L);
+ testCases.put(4, 5L);
+ testCases.put(5, 6L);
+ testCases.put(6, 7L);
+ testCases.put(1499, 1984500L);
+ testCases.put(1572, 2449440L);
+ testCases.put(1658, 3072000L);
+ testCases.put(6625, 4300800000L);
+
+ var uglyNumbers = new NthUglyNumber(new int[] {7, 2, 5, 3});
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(uglyNumbers.get(tc.getKey()), tc.getValue());
+ }
+
+ assertEquals(uglyNumbers.get(999), 385875);
+ }
+
+ @Test
+ public void testGetWithBase1() {
+ var uglyNumbers = new NthUglyNumber(new int[] {1});
+ assertEquals(uglyNumbers.get(10), 1);
+ }
+
+ @Test
+ public void testGetWithBase2() {
+ var uglyNumbers = new NthUglyNumber(new int[] {2});
+ assertEquals(uglyNumbers.get(5), 32);
+ }
+
+
+ @Test
+ public void testGetThrowsAnErrorForNegativeInput() {
+ var uglyNumbers = new NthUglyNumber(new int[] {1, 2});
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> uglyNumbers.get(-1)
+ );
+ }
+
+ @Test
+ public void testConstructorThrowsAnErrorForEmptyInput() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> new NthUglyNumber(new int[] {})
+ );
+ }
+}
From ad03086f547854a4c00b1e3a85dde5d315f119b6 Mon Sep 17 00:00:00 2001
From: Piotr Idzik <65706193+vil02@users.noreply.github.com>
Date: Fri, 2 Jun 2023 18:28:33 +0200
Subject: [PATCH 0047/1457] Remove main and add tests for CountWords (#4210)
---
.../com/thealgorithms/others/CountWords.java | 47 +++++++++----------
.../thealgorithms/others/CountWordsTest.java | 38 +++++++++++++++
2 files changed, 59 insertions(+), 26 deletions(-)
create mode 100644 src/test/java/com/thealgorithms/others/CountWordsTest.java
diff --git a/src/main/java/com/thealgorithms/others/CountWords.java b/src/main/java/com/thealgorithms/others/CountWords.java
index 2bbfe08ef356..5117b83b7e57 100644
--- a/src/main/java/com/thealgorithms/others/CountWords.java
+++ b/src/main/java/com/thealgorithms/others/CountWords.java
@@ -3,32 +3,34 @@
import java.util.Scanner;
/**
- * You enter a string into this program, and it will return how many words were
- * in that particular string
- *
* @author Marcus
*/
-public class CountWords {
-
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.println("Enter your text: ");
- String str = input.nextLine();
-
- System.out.println("Your text has " + wordCount(str) + " word(s)");
- System.out.println(
- "Your text has " + secondaryWordCount(str) + " word(s)"
- );
- input.close();
+final public class CountWords {
+ private CountWords() {
}
- private static int wordCount(String s) {
+ /**
+ * @brief counts the number of words in the input string
+ * @param s the input string
+ * @return the number of words in the input string
+ */
+ public static int wordCount(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
return s.trim().split("[\\s]+").length;
}
+ private static String removeSpecialCharacters(String s) {
+ StringBuilder sb = new StringBuilder();
+ for (char c : s.toCharArray()) {
+ if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
/**
* counts the number of words in a sentence but ignores all potential
* non-alphanumeric characters that do not represent a word. runs in O(n)
@@ -37,17 +39,10 @@ private static int wordCount(String s) {
* @param s String: sentence with word(s)
* @return int: number of words
*/
- private static int secondaryWordCount(String s) {
- if (s == null || s.isEmpty()) {
+ public static int secondaryWordCount(String s) {
+ if (s == null) {
return 0;
}
- StringBuilder sb = new StringBuilder();
- for (char c : s.toCharArray()) {
- if (Character.isLetter(c) || Character.isDigit(c)) {
- sb.append(c);
- }
- }
- s = sb.toString();
- return s.trim().split("[\\s]+").length;
+ return wordCount(removeSpecialCharacters(s));
}
}
diff --git a/src/test/java/com/thealgorithms/others/CountWordsTest.java b/src/test/java/com/thealgorithms/others/CountWordsTest.java
new file mode 100644
index 000000000000..a2b0c03df220
--- /dev/null
+++ b/src/test/java/com/thealgorithms/others/CountWordsTest.java
@@ -0,0 +1,38 @@
+package com.thealgorithms.others;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.HashMap;
+import org.junit.jupiter.api.Test;
+
+
+class CountWordsTest {
+ @Test
+ public void testWordCount() {
+ HashMap testCases = new HashMap<>();
+ testCases.put("", 0);
+ testCases.put(null, 0);
+ testCases.put("aaaa bbb cccc", 3);
+ testCases.put("note extra spaces here", 4);
+ testCases.put(" a b c d e ", 5);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(CountWords.wordCount(tc.getKey()), tc.getValue());
+ }
+ }
+
+ @Test
+ public void testSecondaryWordCount() {
+ HashMap testCases = new HashMap<>();
+ testCases.put("", 0);
+ testCases.put(null, 0);
+ testCases.put("aaaa bbb cccc", 3);
+ testCases.put("this-is-one-word!", 1);
+ testCases.put("What, about, this? Hmmm----strange", 4);
+ testCases.put("word1 word-2 word-3- w?o,r.d.@!@#$&*()<>4", 4);
+
+ for (final var tc : testCases.entrySet()) {
+ assertEquals(CountWords.secondaryWordCount(tc.getKey()), tc.getValue());
+ }
+ }
+}
From 00282efd8becbd0612cc710f49bf21a562deb034 Mon Sep 17 00:00:00 2001
From: acbin <44314231+acbin@users.noreply.github.com>
Date: Fri, 9 Jun 2023 18:52:05 +0800
Subject: [PATCH 0048/1457] style: format code (#4212)
close #4204
---
.../thealgorithms/audiofilters/IIRFilter.java | 20 +-
.../AllPathsFromSourceToTarget.java | 33 +-
.../backtracking/ArrayCombination.java | 2 +-
.../backtracking/Combination.java | 6 +-
.../thealgorithms/backtracking/FloodFill.java | 8 +-
.../backtracking/KnightsTour.java | 41 +--
.../backtracking/MazeRecursion.java | 16 +-
.../thealgorithms/backtracking/NQueens.java | 25 +-
.../thealgorithms/backtracking/PowerSum.java | 22 +-
.../backtracking/WordSearch.java | 16 +-
.../java/com/thealgorithms/ciphers/AES.java | 104 ++----
.../thealgorithms/ciphers/AESEncryption.java | 20 +-
.../thealgorithms/ciphers/AffineCipher.java | 19 +-
.../com/thealgorithms/ciphers/Blowfish.java | 57 +--
.../com/thealgorithms/ciphers/Caesar.java | 15 +-
.../ciphers/ColumnarTranspositionCipher.java | 59 +--
.../java/com/thealgorithms/ciphers/DES.java | 266 ++++++--------
.../com/thealgorithms/ciphers/HillCipher.java | 21 +-
.../com/thealgorithms/ciphers/Polybius.java | 13 +-
.../java/com/thealgorithms/ciphers/RSA.java | 10 +-
.../ciphers/SimpleSubCipher.java | 1 -
.../com/thealgorithms/ciphers/Vigenere.java | 28 +-
.../thealgorithms/ciphers/a5/A5Cipher.java | 3 +-
.../ciphers/a5/A5KeyStreamGenerator.java | 15 +-
.../ciphers/a5/CompositeLFSR.java | 8 +-
.../com/thealgorithms/ciphers/a5/Utils.java | 9 +-
.../conversions/AnyBaseToAnyBase.java | 16 +-
.../conversions/DecimalToAnyBase.java | 17 +-
.../conversions/DecimalToBinary.java | 4 +-
.../thealgorithms/conversions/HexToOct.java | 3 +-
.../conversions/RgbHsvConversion.java | 123 ++-----
.../conversions/TurkishToLatinConversion.java | 7 +-
.../buffers/CircularBuffer.java | 11 +-
.../datastructures/caches/LFUCache.java | 3 +-
.../datastructures/caches/LRUCache.java | 12 +-
.../datastructures/caches/MRUCache.java | 12 +-
.../dynamicarray/DynamicArray.java | 18 +-
.../datastructures/graphs/A_Star.java | 170 ++-------
.../datastructures/graphs/BellmanFord.java | 43 ++-
.../graphs/BipartiteGrapfDFS.java | 15 +-
.../graphs/ConnectedComponent.java | 8 +-
.../datastructures/graphs/Cycles.java | 4 +-
.../graphs/DIJSKSTRAS_ALGORITHM.java | 34 +-
.../datastructures/graphs/FloydWarshall.java | 59 +--
.../graphs/HamiltonianCycle.java | 11 +-
.../datastructures/graphs/KahnsAlgorithm.java | 4 +-
.../datastructures/graphs/Kosaraju.java | 73 ++--
.../datastructures/graphs/Kruskal.java | 38 +-
.../datastructures/graphs/MatrixGraphs.java | 26 +-
.../datastructures/graphs/PrimMST.java | 29 +-
.../graphs/TarjansAlgorithm.java | 58 +--
.../hashmap/hashing/HashMapCuckooHashing.java | 65 +---
.../hashmap/hashing/Intersection.java | 7 +-
.../datastructures/hashmap/hashing/Main.java | 46 ++-
.../hashmap/hashing/MainCuckooHashing.java | 88 ++---
.../hashmap/hashing/MajorityElement.java | 29 +-
.../datastructures/hashmap/hashing/Map.java | 1 -
.../datastructures/heaps/FibonacciHeap.java | 61 ++--
.../datastructures/heaps/GenericHeap.java | 14 +-
.../datastructures/heaps/HeapElement.java | 11 +-
.../datastructures/heaps/LeftistHeap.java | 206 ++++++-----
.../datastructures/heaps/MaxHeap.java | 55 +--
.../datastructures/heaps/MinHeap.java | 55 +--
.../heaps/MinPriorityQueue.java | 15 +-
.../lists/CircleLinkedList.java | 8 +-
.../lists/CursorLinkedList.java | 3 +-
.../lists/DoublyLinkedList.java | 20 +-
.../lists/MergeSortedArrayList.java | 6 +-
.../lists/MergeSortedSinglyLinkedList.java | 9 +-
.../lists/Merge_K_SortedLinkedlist.java | 4 +-
.../datastructures/lists/RandomNode.java | 22 +-
.../SearchSinglyLinkedListRecursion.java | 5 +-
.../lists/SinglyLinkedList.java | 34 +-
.../datastructures/lists/SkipList.java | 43 +--
.../datastructures/queues/CircularQueue.java | 7 +-
.../datastructures/queues/LinkedQueue.java | 13 +-
.../datastructures/queues/PriorityQueues.java | 7 +-
.../stacks/BalancedBrackets.java | 44 +--
.../stacks/CalculateMaxOfMin.java | 8 +-
.../stacks/DecimalToAnyUsingStack.java | 7 +-
.../stacks/DuplicateBrackets.java | 3 +-
.../datastructures/stacks/InfixToPostfix.java | 28 +-
.../stacks/LargestRectangle.java | 7 +-
.../stacks/MaximumMinimumWindow.java | 4 +-
.../stacks/NextGraterElement.java | 5 +-
.../stacks/NextSmallerElement.java | 24 +-
.../datastructures/stacks/NodeStack.java | 3 +-
.../datastructures/stacks/PostfixToInfix.java | 22 +-
.../datastructures/stacks/ReverseStack.java | 19 +-
.../stacks/StackOfLinkedList.java | 8 +-
.../datastructures/trees/AVLSimple.java | 46 +--
.../trees/BSTRecursiveGeneric.java | 34 +-
.../datastructures/trees/BinaryTree.java | 6 +-
.../trees/CheckBinaryTreeIsValidBST.java | 4 +-
.../trees/CheckIfBinaryTreeBalanced.java | 17 +-
.../trees/CheckTreeIsSymmetric.java | 6 +-
.../CreateBinaryTreeFromInorderPreorder.java | 59 +--
.../datastructures/trees/GenericTree.java | 4 +-
.../datastructures/trees/KDTree.java | 118 +++---
.../datastructures/trees/LCA.java | 23 +-
.../datastructures/trees/LazySegmentTree.java | 32 +-
.../datastructures/trees/RedBlackBST.java | 20 +-
.../datastructures/trees/SameTreesCheck.java | 5 +-
.../datastructures/trees/SegmentTree.java | 30 +-
.../datastructures/trees/TreeRandomNode.java | 18 +-
.../datastructures/trees/TrieImp.java | 89 +++--
.../trees/VerticalOrderTraversal.java | 38 +-
.../datastructures/trees/ZigzagTraversal.java | 3 +-
.../datastructures/trees/nearestRightKey.java | 2 +-
.../devutils/entities/ProcessDetails.java | 1 -
.../devutils/nodes/LargeTreeNode.java | 5 +-
.../thealgorithms/devutils/nodes/Node.java | 3 +-
.../devutils/nodes/SimpleTreeNode.java | 8 +-
.../BinaryExponentiation.java | 2 +-
.../divideandconquer/ClosestPair.java | 20 +-
.../divideandconquer/SkylineAlgorithm.java | 15 +-
.../StrassenMatrixMultiplication.java | 11 +-
.../dynamicprogramming/BoardPath.java | 20 +-
.../dynamicprogramming/BoundaryFill.java | 124 ++-----
.../BruteForceKnapsack.java | 9 +-
.../dynamicprogramming/CatalanNumber.java | 4 +-
.../dynamicprogramming/ClimbingStairs.java | 7 +-
.../dynamicprogramming/CoinChange.java | 23 +-
.../CountFriendsPairing.java | 6 +-
.../dynamicprogramming/DiceThrow.java | 11 +-
.../DyanamicProgrammingKnapsack.java | 4 +-
.../dynamicprogramming/EditDistance.java | 11 +-
.../dynamicprogramming/EggDropping.java | 4 +-
.../dynamicprogramming/Fibonacci.java | 25 +-
.../dynamicprogramming/FordFulkerson.java | 15 +-
.../dynamicprogramming/KadaneAlgorithm.java | 3 +-
.../dynamicprogramming/Knapsack.java | 13 +-
.../KnapsackMemoization.java | 13 +-
.../LevenshteinDistance.java | 13 +-
.../LongestAlternatingSubsequence.java | 34 +-
.../LongestCommonSubsequence.java | 6 +-
.../LongestIncreasingSubsequence.java | 4 +-
.../LongestPalindromicSubsequence.java | 37 +-
.../LongestValidParentheses.java | 5 +-
.../MatrixChainMultiplication.java | 11 +-
...atrixChainRecursiveTopDownMemoisation.java | 16 +-
.../dynamicprogramming/MinimumPathSum.java | 8 +-
.../MinimumSumPartition.java | 6 +-
.../dynamicprogramming/NewManShanksPrime.java | 3 +-
.../OptimalJobScheduling.java | 58 +--
.../PalindromicPartitioning.java | 26 +-
.../dynamicprogramming/PartitionProblem.java | 12 +-
.../dynamicprogramming/RegexMatching.java | 19 +-
.../dynamicprogramming/RodCutting.java | 2 +-
.../ShortestCommonSupersequenceLength.java | 7 +-
.../dynamicprogramming/SubsetCount.java | 58 ++-
.../dynamicprogramming/SubsetSum.java | 2 +-
.../dynamicprogramming/Sum_Of_Subset.java | 2 +-
.../dynamicprogramming/UniquePaths.java | 18 +-
.../dynamicprogramming/WineProblem.java | 6 +-
.../thealgorithms/geometry/GrahamScan.java | 168 +++++----
.../com/thealgorithms/io/BufferedReader.java | 342 +++++++++---------
.../com/thealgorithms/maths/ADTFraction.java | 10 +-
.../com/thealgorithms/maths/AbsoluteMin.java | 7 +-
.../com/thealgorithms/maths/AliquotSum.java | 20 +-
.../thealgorithms/maths/AmicableNumber.java | 36 +-
.../java/com/thealgorithms/maths/Area.java | 3 +-
.../maths/AutomorphicNumber.java | 12 +-
.../maths/BinomialCoefficient.java | 14 +-
.../maths/CircularConvolutionFFT.java | 10 +-
.../com/thealgorithms/maths/Convolution.java | 5 +-
.../thealgorithms/maths/ConvolutionFFT.java | 11 +-
.../maths/DeterminantOfMatrix.java | 4 +-
.../com/thealgorithms/maths/DigitalRoot.java | 16 +-
.../thealgorithms/maths/DistanceFormula.java | 14 +-
.../thealgorithms/maths/DudeneyNumber.java | 6 +-
.../com/thealgorithms/maths/EulerMethod.java | 47 +--
.../java/com/thealgorithms/maths/FFT.java | 17 +-
.../com/thealgorithms/maths/FFTBluestein.java | 19 +-
.../com/thealgorithms/maths/Factorial.java | 3 +-
.../thealgorithms/maths/FastInverseSqrt.java | 19 +-
.../maths/FibonacciJavaStreams.java | 54 +--
.../thealgorithms/maths/FindMaxRecursion.java | 10 +-
.../thealgorithms/maths/FindMinRecursion.java | 10 +-
.../com/thealgorithms/maths/FrizzyNumber.java | 9 +-
.../java/com/thealgorithms/maths/GCD.java | 8 +-
.../com/thealgorithms/maths/Gaussian.java | 17 +-
.../com/thealgorithms/maths/GenericRoot.java | 3 +-
.../thealgorithms/maths/HarshadNumber.java | 6 +-
.../thealgorithms/maths/JosephusProblem.java | 18 +-
.../thealgorithms/maths/JugglerSequence.java | 5 +-
.../thealgorithms/maths/KaprekarNumbers.java | 39 +-
.../com/thealgorithms/maths/KeithNumber.java | 31 +-
.../maths/KrishnamurthyNumber.java | 34 +-
.../maths/LeastCommonMultiple.java | 4 +-
.../thealgorithms/maths/LeonardoNumber.java | 6 +-
.../LinearDiophantineEquationsSolver.java | 52 +--
.../maths/LiouvilleLambdaFunction.java | 8 +-
.../com/thealgorithms/maths/LongDivision.java | 18 +-
.../com/thealgorithms/maths/LucasSeries.java | 4 +-
.../com/thealgorithms/maths/MagicSquare.java | 10 +-
.../com/thealgorithms/maths/MatrixUtil.java | 173 ++++-----
.../java/com/thealgorithms/maths/Median.java | 5 +-
.../thealgorithms/maths/MobiusFunction.java | 18 +-
.../java/com/thealgorithms/maths/Mode.java | 17 +-
.../maths/NonRepeatingElement.java | 39 +-
.../thealgorithms/maths/NthUglyNumber.java | 5 +-
.../thealgorithms/maths/NumberOfDigits.java | 4 +-
.../com/thealgorithms/maths/ParseInteger.java | 6 +-
.../thealgorithms/maths/PascalTriangle.java | 26 +-
.../com/thealgorithms/maths/PerfectCube.java | 2 +-
.../thealgorithms/maths/PerfectNumber.java | 18 +-
.../com/thealgorithms/maths/Perimeter.java | 17 +-
.../com/thealgorithms/maths/PiNilakantha.java | 14 +-
.../com/thealgorithms/maths/PollardRho.java | 28 +-
.../com/thealgorithms/maths/PrimeCheck.java | 8 +-
.../com/thealgorithms/maths/PronicNumber.java | 9 +-
.../thealgorithms/maths/RomanNumeralUtil.java | 23 +-
.../maths/SimpsonIntegration.java | 10 +-
.../maths/SquareFreeInteger.java | 35 +-
.../SquareRootWithNewtonRaphsonMethod.java | 10 +-
.../maths/SumOfArithmeticSeries.java | 10 +-
.../com/thealgorithms/maths/SumOfDigits.java | 18 +-
.../maths/SumWithoutArithmeticOperators.java | 22 +-
.../maths/TrinomialTriangle.java | 5 +-
.../com/thealgorithms/maths/TwinPrime.java | 31 +-
.../thealgorithms/maths/VampireNumber.java | 26 +-
.../maths/VectorCrossProduct.java | 8 +-
.../matrixexponentiation/Fibonacci.java | 37 +-
.../MinimizingLateness.java | 16 +-
.../misc/ColorContrastRatio.java | 39 +-
.../thealgorithms/misc/InverseOfMatrix.java | 3 +-
.../misc/MedianOfRunningArray.java | 2 +-
.../thealgorithms/misc/PalindromePrime.java | 4 +-
.../misc/RangeInSortedArray.java | 41 +--
.../java/com/thealgorithms/misc/Sort012D.java | 38 +-
.../java/com/thealgorithms/misc/Sparcity.java | 12 +-
.../thealgorithms/misc/ThreeSumProblem.java | 11 +-
.../com/thealgorithms/misc/WordBoggle.java | 93 ++---
.../java/com/thealgorithms/others/BFPRT.java | 3 +-
.../others/BankersAlgorithm.java | 55 +--
.../com/thealgorithms/others/BoyerMoore.java | 3 +-
.../java/com/thealgorithms/others/CRC16.java | 33 +-
.../java/com/thealgorithms/others/Conway.java | 15 +-
.../java/com/thealgorithms/others/Damm.java | 31 +-
.../com/thealgorithms/others/Dijkstra.java | 33 +-
.../thealgorithms/others/FloydTriangle.java | 4 +-
.../thealgorithms/others/HappyNumbersSeq.java | 5 +-
.../com/thealgorithms/others/Huffman.java | 15 +-
...g_auto_completing_features_using_trie.java | 8 +-
.../others/InsertDeleteInArray.java | 4 +-
.../thealgorithms/others/KochSnowflake.java | 44 +--
.../com/thealgorithms/others/LineSweep.java | 22 +-
.../others/LinearCongruentialGenerator.java | 19 +-
.../others/LowestBasePalindrome.java | 15 +-
.../java/com/thealgorithms/others/Luhn.java | 41 +--
.../com/thealgorithms/others/Mandelbrot.java | 97 ++---
.../others/MemoryManagementAlgorithms.java | 106 +++---
.../others/MiniMaxAlgorithm.java | 22 +-
.../com/thealgorithms/others/PageRank.java | 56 +--
.../com/thealgorithms/others/PasswordGen.java | 6 +-
.../com/thealgorithms/others/PerlinNoise.java | 35 +-
.../others/PrintAMatrixInSpiralOrder.java | 3 -
.../others/QueueUsingTwoStacks.java | 3 +-
.../com/thealgorithms/others/RabinKarp.java | 23 +-
.../others/RemoveDuplicateFromString.java | 8 +-
.../others/ReturnSubsequence.java | 18 +-
.../others/SieveOfEratosthenes.java | 6 +-
.../thealgorithms/others/SkylineProblem.java | 10 +-
.../java/com/thealgorithms/others/Sudoku.java | 18 +-
.../com/thealgorithms/others/TopKWords.java | 7 +-
.../thealgorithms/others/TowerOfHanoi.java | 15 +-
.../com/thealgorithms/others/Verhoeff.java | 51 ++-
.../others/cn/HammingDistance.java | 9 +-
.../thealgorithms/others/countSetBits.java | 28 +-
.../scheduling/FCFSScheduling.java | 22 +-
.../scheduling/RRScheduling.java | 43 ++-
.../scheduling/SJFScheduling.java | 92 ++---
.../thealgorithms/searches/BinarySearch.java | 30 +-
.../searches/BinarySearch2dArray.java | 93 ++---
.../searches/DepthFirstSearch.java | 29 +-
.../searches/ExponentalSearch.java | 30 +-
.../searches/FibonacciSearch.java | 14 +-
.../searches/HowManyTimesRotated.java | 20 +-
.../searches/InterpolationSearch.java | 27 +-
.../searches/IterativeBinarySearch.java | 21 +-
.../searches/IterativeTernarySearch.java | 21 +-
.../thealgorithms/searches/JumpSearch.java | 2 +-
.../com/thealgorithms/searches/KMPSearch.java | 8 +-
.../thealgorithms/searches/LinearSearch.java | 15 +-
.../searches/LinearSearchThread.java | 6 +-
.../thealgorithms/searches/LowerBound.java | 30 +-
.../searches/MonteCarloTreeSearch.java | 37 +-
.../searches/OrderAgnosticBinarySearch.java | 69 ++--
.../searches/PerfectBinarySearch.java | 2 +-
.../thealgorithms/searches/QuickSelect.java | 30 +-
.../searches/RabinKarpAlgorithm.java | 2 +-
...owColumnWiseSorted2dArrayBinarySearch.java | 53 +--
.../searches/SaddlebackSearch.java | 2 +-
.../SearchInARowAndColWiseSortedMatrix.java | 3 +-
.../searches/SquareRootBinarySearch.java | 4 +-
.../thealgorithms/searches/TernarySearch.java | 38 +-
.../com/thealgorithms/searches/UnionFind.java | 16 +-
.../thealgorithms/searches/UpperBound.java | 30 +-
.../sortOrderAgnosticBinarySearch.java | 36 +-
.../com/thealgorithms/sorts/BeadSort.java | 45 ++-
.../com/thealgorithms/sorts/BitonicSort.java | 2 +-
.../com/thealgorithms/sorts/BogoSort.java | 4 +-
.../sorts/BubbleSortRecursion.java | 5 +-
.../com/thealgorithms/sorts/BucketSort.java | 2 +-
.../com/thealgorithms/sorts/CircleSort.java | 13 +-
.../sorts/CocktailShakerSort.java | 4 +-
.../com/thealgorithms/sorts/CountingSort.java | 20 +-
.../java/com/thealgorithms/sorts/DNFSort.java | 40 +-
.../sorts/DualPivotQuickSort.java | 20 +-
.../sorts/DutchNationalFlagSort.java | 25 +-
.../thealgorithms/sorts/InsertionSort.java | 18 +-
.../com/thealgorithms/sorts/LinkListSort.java | 181 +++++----
.../com/thealgorithms/sorts/MergeSort.java | 3 +-
.../sorts/MergeSortNoExtraSpace.java | 12 +-
.../sorts/MergeSortRecursive.java | 24 +-
.../com/thealgorithms/sorts/OddEvenSort.java | 2 +-
.../thealgorithms/sorts/PigeonholeSort.java | 2 +-
.../com/thealgorithms/sorts/QuickSort.java | 18 +-
.../com/thealgorithms/sorts/RadixSort.java | 2 +-
.../thealgorithms/sorts/SelectionSort.java | 4 +-
.../com/thealgorithms/sorts/ShellSort.java | 2 +-
.../com/thealgorithms/sorts/SimpleSort.java | 2 +-
.../thealgorithms/sorts/SortAlgorithm.java | 6 +-
.../com/thealgorithms/sorts/SortUtils.java | 4 +-
.../sorts/SortUtilsRandomGenerator.java | 5 +-
.../com/thealgorithms/sorts/StoogeSort.java | 10 +-
.../com/thealgorithms/sorts/StrandSort.java | 21 +-
.../com/thealgorithms/sorts/SwapSort.java | 10 +-
.../java/com/thealgorithms/sorts/TimSort.java | 4 +-
.../thealgorithms/sorts/TopologicalSort.java | 42 +--
.../com/thealgorithms/sorts/TreeSort.java | 16 +-
.../com/thealgorithms/sorts/WiggleSort.java | 35 +-
.../thealgorithms/strings/Alphabetical.java | 5 +-
.../com/thealgorithms/strings/Anagrams.java | 55 +--
.../thealgorithms/strings/CheckVowels.java | 5 +-
.../strings/HammingDistance.java | 7 +-
.../thealgorithms/strings/HorspoolSearch.java | 19 +-
.../LetterCombinationsOfPhoneNumber.java | 25 +-
.../strings/LongestPalindromicSubstring.java | 4 +-
.../java/com/thealgorithms/strings/Lower.java | 7 +-
.../com/thealgorithms/strings/MyAtoi.java | 27 +-
.../com/thealgorithms/strings/Palindrome.java | 4 +-
.../com/thealgorithms/strings/Pangram.java | 2 +-
.../thealgorithms/strings/PermuteString.java | 16 +-
.../strings/ReverseStringRecursive.java | 7 +-
.../strings/StringCompression.java | 104 +++---
.../java/com/thealgorithms/strings/Upper.java | 7 +-
.../strings/ValidParentheses.java | 56 ++-
.../com/thealgorithms/strings/WordLadder.java | 14 +-
.../strings/longestNonRepeativeSubstring.java | 3 +-
.../strings/zigZagPattern/zigZagPattern.java | 12 +-
.../AllPathsFromSourceToTargetTest.java | 41 ++-
.../backtracking/CombinationTest.java | 15 +-
.../backtracking/FloodFillTest.java | 72 ++--
.../backtracking/MazeRecursionTest.java | 34 +-
.../backtracking/PermutationTest.java | 10 +-
.../backtracking/PowerSumTest.java | 4 +-
.../backtracking/WordSearchTest.java | 6 +-
.../thealgorithms/ciphers/BlowfishTest.java | 12 +-
.../com/thealgorithms/ciphers/CaesarTest.java | 5 +-
.../com/thealgorithms/ciphers/DESTest.java | 45 ++-
.../com/thealgorithms/ciphers/RSATest.java | 5 +-
.../ciphers/SimpleSubCipherTest.java | 5 +-
.../ciphers/SimpleSubstitutionCipherTest.java | 4 +-
.../thealgorithms/ciphers/VigenereTest.java | 5 +-
.../thealgorithms/ciphers/a5/LFSRTest.java | 8 +-
.../conversions/BinaryToDecimalTest.java | 4 +-
.../conversions/HexaDecimalToBinaryTest.java | 5 +-
.../conversions/HexaDecimalToDecimalTest.java | 6 +-
.../conversions/RomanToIntegerTest.java | 4 +-
.../buffers/CircularBufferTest.java | 24 +-
.../datastructures/caches/LFUCacheTest.java | 20 +-
.../graphs/HamiltonianCycleTest.java | 34 +-
.../datastructures/graphs/KosarajuTest.java | 12 +-
.../graphs/TarjansAlgorithmTest.java | 14 +-
.../hashmap/HashMapCuckooHashingTest.java | 2 +-
.../hashmap/hashing/MajorityElementTest.java | 13 +-
.../hashmap/hashing/MapTest.java | 5 +-
.../datastructures/heaps/LeftistHeapTest.java | 42 +--
.../lists/SinglyLinkedListTest.java | 120 +++---
.../datastructures/lists/SkipListTest.java | 10 +-
.../queues/LinkedQueueTest.java | 33 +-
.../queues/PriorityQueuesTest.java | 4 +-
.../trees/BSTFromSortedArrayTest.java | 6 +-
.../datastructures/trees/BinaryTreeTest.java | 120 +++---
.../trees/CeilInBinarySearchTreeTest.java | 18 +-
.../trees/CheckBinaryTreeIsValidBSTTest.java | 15 +-
.../trees/CheckTreeIsSymmetricTest.java | 11 +-
...eateBinaryTreeFromInorderPreorderTest.java | 21 +-
.../trees/InorderTraversalTest.java | 10 +-
.../datastructures/trees/KDTreeTest.java | 38 +-
.../trees/LazySegmentTreeTest.java | 21 +-
.../trees/LevelOrderTraversalTest.java | 16 +-
.../trees/PostOrderTraversalTest.java | 10 +-
.../trees/PreOrderTraversalTest.java | 10 +-
.../trees/SameTreesCheckTest.java | 24 +-
.../datastructures/trees/TreeTestUtils.java | 2 +-
.../trees/VerticalOrderTraversalTest.java | 14 +-
.../trees/ZigzagTraversalTest.java | 16 +-
.../BinaryExponentiationTest.java | 1 -
.../StrassenMatrixMultiplicationTest.java | 21 +-
.../dynamicprogramming/EggDroppingTest.java | 20 +-
.../KnapsackMemoizationTest.java | 16 +-
.../LevenshteinDistanceTests.java | 5 +-
.../OptimalJobSchedulingTest.java | 102 ++----
.../PartitionProblemTest.java | 20 +-
.../dynamicprogramming/SubsetCountTest.java | 19 +-
.../dynamicprogramming/climbStairsTest.java | 23 +-
.../geometry/GrahamScanTest.java | 9 +-
.../thealgorithms/io/BufferedReaderTest.java | 177 +++++----
.../thealgorithms/maths/ADTFractionTest.java | 6 +-
.../thealgorithms/maths/AbsoluteMinTest.java | 6 +-
.../maths/AbsoluteValueTest.java | 10 +-
.../com/thealgorithms/maths/AreaTest.java | 70 ++--
.../maths/AutomorphicNumberTest.java | 11 +-
.../com/thealgorithms/maths/AverageTest.java | 1 -
.../maths/CollatzConjectureTest.java | 27 +-
.../maths/DistanceFormulaTest.java | 62 +---
.../maths/DudeneyNumberTest.java | 5 +-
.../com/thealgorithms/maths/FindMaxTest.java | 20 +-
.../com/thealgorithms/maths/FindMinTest.java | 16 +-
.../thealgorithms/maths/FrizzyNumberTest.java | 40 +-
.../java/com/thealgorithms/maths/GCDTest.java | 28 +-
.../maths/HarshadNumberTest.java | 3 +-
.../maths/HeronsFormulaTest.java | 10 +-
.../maths/KaprekarNumbersTest.java | 6 +-
.../maths/LeonardoNumberTest.java | 7 +-
.../maths/LiouvilleLambdaFunctionTest.java | 40 +-
.../thealgorithms/maths/LongDivisionTest.java | 35 +-
.../thealgorithms/maths/LucasSeriesTest.java | 3 +-
.../com/thealgorithms/maths/MedianTest.java | 3 +-
.../maths/MobiusFunctionTest.java | 30 +-
.../maths/NthUglyNumberTest.java | 14 +-
.../maths/PascalTriangleTest.java | 30 +-
.../maths/PerfectNumberTest.java | 5 +-
.../maths/PerfectSquareTest.java | 6 +-
.../thealgorithms/maths/PerimeterTest.java | 2 +-
.../thealgorithms/maths/PollardRhoTest.java | 26 +-
.../maths/PrimeFactorizationTest.java | 10 +-
.../thealgorithms/maths/PronicNumberTest.java | 12 +-
.../maths/ReverseNumberTest.java | 6 +-
.../maths/SquareFreeIntegerTest.java | 181 ++++++---
...SquareRootWithNewtonRaphsonTestMethod.java | 15 +-
.../SquareRootwithBabylonianMethodTest.java | 20 +-
.../maths/StandardDeviationTest.java | 21 +-
.../maths/StandardScoreTest.java | 5 +-
.../SumWithoutArithmeticOperatorsTest.java | 33 +-
.../thealgorithms/maths/TwinPrimeTest.java | 102 +++---
.../com/thealgorithms/maths/VolumeTest.java | 1 +
.../others/ArrayLeftRotationTest.java | 14 +-
.../thealgorithms/others/BestFitCPUTest.java | 30 +-
.../com/thealgorithms/others/CRC16Test.java | 5 +-
.../others/CRCAlgorithmTest.java | 12 +-
.../others/CalculateMaxOfMinTest.java | 14 +-
.../com/thealgorithms/others/ConwayTest.java | 27 +-
.../thealgorithms/others/CountCharTest.java | 7 +-
.../others/CountFriendsPairingTest.java | 16 +-
.../thealgorithms/others/CountWordsTest.java | 1 -
.../thealgorithms/others/FirstFitCPUTest.java | 30 +-
.../others/KadaneAlogrithmTest.java | 16 +-
.../thealgorithms/others/LineSweepTest.java | 21 +-
.../others/LinkListSortTest.java | 16 +-
.../others/LowestBasePalindromeTest.java | 25 +-
.../com/thealgorithms/others/NextFitTest.java | 30 +-
.../thealgorithms/others/PasswordGenTest.java | 16 +-
.../others/TestPrintMatrixInSpiralOrder.java | 21 +-
.../thealgorithms/others/TwoPointersTest.java | 33 +-
.../thealgorithms/others/WorstFitCPUTest.java | 39 +-
.../others/cn/HammingDistanceTest.java | 19 +-
.../scheduling/FCFSSchedulingTest.java | 10 +-
.../scheduling/RRSchedulingTest.java | 7 +-
.../scheduling/SJFSchedulingTest.java | 143 ++++----
.../searches/BinarySearch2dArrayTest.java | 48 +--
.../searches/BreadthFirstSearchTest.java | 27 +-
.../searches/HowManyTimesRotatedTest.java | 5 +-
.../OrderAgnosticBinarySearchTest.java | 119 +++---
.../searches/QuickSelectTest.java | 34 +-
...lumnWiseSorted2dArrayBinarySearchTest.java | 196 +++++-----
...estSearchInARowAndColWiseSortedMatrix.java | 23 +-
.../sortOrderAgnosticBinarySearchTest.java | 19 +-
.../com/thealgorithms/sorts/BeadSortTest.java | 14 +-
.../sorts/BinaryInsertionSortTest.java | 8 +-
.../com/thealgorithms/sorts/BogoSortTest.java | 30 +-
.../thealgorithms/sorts/BubbleSortTest.java | 10 +-
.../thealgorithms/sorts/BucketSortTest.java | 16 +-
.../sorts/CocktailShakerSortTest.java | 14 +-
.../com/thealgorithms/sorts/CombSortTest.java | 62 ++--
.../sorts/DualPivotQuickSortTest.java | 21 +-
.../sorts/DutchNationalFlagSortTest.java | 32 +-
.../sorts/InsertionSortTest.java | 7 +-
.../sorts/IntrospectiveSortTest.java | 9 +-
.../sorts/MergeSortRecursiveTest.java | 46 +--
.../thealgorithms/sorts/OddEvenSortTest.java | 7 +-
.../sorts/SelectionSortTest.java | 14 +-
.../thealgorithms/sorts/ShellSortTest.java | 31 +-
.../thealgorithms/sorts/SimpleSortTest.java | 30 +-
.../com/thealgorithms/sorts/SlowSortTest.java | 6 +-
.../sorts/SortUtilsRandomGeneratorTest.java | 4 +-
.../thealgorithms/sorts/SortUtilsTest.java | 5 +-
.../sorts/SortingAlgorithmTest.java | 31 +-
.../thealgorithms/sorts/StrandSortTest.java | 14 +-
.../com/thealgorithms/sorts/TimSortTest.java | 4 +-
.../sorts/TopologicalSortTest.java | 11 +-
.../com/thealgorithms/sorts/TreeSortTest.java | 56 +--
.../thealgorithms/sorts/WiggleSortTest.java | 28 +-
.../strings/HammingDistanceTest.java | 24 +-
.../strings/HorspoolSearchTest.java | 11 +-
.../LetterCombinationsOfPhoneNumberTest.java | 15 +-
.../com/thealgorithms/strings/LowerTest.java | 6 +-
.../com/thealgorithms/strings/MyAtoiTest.java | 12 +-
.../thealgorithms/strings/PalindromeTest.java | 15 +-
.../thealgorithms/strings/PangramTest.java | 9 +-
.../strings/ReverseStringRecursiveTest.java | 16 +-
.../strings/ReverseStringTest.java | 4 +-
.../thealgorithms/strings/RotationTest.java | 2 +-
.../strings/StringCompressionTest.java | 7 +-
.../strings/ValidParenthesesTest.java | 11 +-
.../thealgorithms/strings/WordLadderTest.java | 8 +-
.../longestNonRepeativeSubstringTest.java | 10 +-
.../zigZagPattern/zigZagPatternTest.java | 10 +-
521 files changed, 5269 insertions(+), 7345 deletions(-)
diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
index 4aca8fb40624..21bb5a123f83 100644
--- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
+++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java
@@ -22,9 +22,7 @@ public class IIRFilter {
*/
public IIRFilter(int order) throws IllegalArgumentException {
if (order < 1) {
- throw new IllegalArgumentException(
- "order must be greater than zero"
- );
+ throw new IllegalArgumentException("order must be greater than zero");
}
this.order = order;
@@ -47,24 +45,19 @@ public IIRFilter(int order) throws IllegalArgumentException {
* @throws IllegalArgumentException if {@code aCoeffs} or {@code bCoeffs} is
* not of size {@code order}, or if {@code aCoeffs[0]} is 0.0
*/
- public void setCoeffs(double[] aCoeffs, double[] bCoeffs)
- throws IllegalArgumentException {
+ public void setCoeffs(double[] aCoeffs, double[] bCoeffs) throws IllegalArgumentException {
if (aCoeffs.length != order) {
throw new IllegalArgumentException(
- "aCoeffs must be of size " + order + ", got " + aCoeffs.length
- );
+ "aCoeffs must be of size " + order + ", got " + aCoeffs.length);
}
if (aCoeffs[0] == 0.0) {
- throw new IllegalArgumentException(
- "aCoeffs.get(0) must not be zero"
- );
+ throw new IllegalArgumentException("aCoeffs.get(0) must not be zero");
}
if (bCoeffs.length != order) {
throw new IllegalArgumentException(
- "bCoeffs must be of size " + order + ", got " + bCoeffs.length
- );
+ "bCoeffs must be of size " + order + ", got " + bCoeffs.length);
}
for (int i = 0; i <= order; i++) {
@@ -84,8 +77,7 @@ public double process(double sample) {
// Process
for (int i = 1; i <= order; i++) {
- result +=
- (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
+ result += (coeffsB[i] * historyX[i - 1] - coeffsA[i] * historyY[i - 1]);
}
result = (result + coeffsB[0] * sample) / coeffsA[0];
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
index 8acaa954ce75..b840f6ad5388 100644
--- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -1,4 +1,5 @@
-/** Author : Siddhant Swarup Mallick
+/**
+ * Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
@@ -15,13 +16,12 @@ public class AllPathsFromSourceToTarget {
private int v;
// To store the paths from source to destination
- static List> nm=new ArrayList<>();
+ static List> nm = new ArrayList<>();
// adjacency list
private ArrayList[] adjList;
// Constructor
- public AllPathsFromSourceToTarget(int vertices)
- {
+ public AllPathsFromSourceToTarget(int vertices) {
// initialise vertex count
this.v = vertices;
@@ -31,8 +31,7 @@ public AllPathsFromSourceToTarget(int vertices)
}
// utility method to initialise adjacency list
- private void initAdjList()
- {
+ private void initAdjList() {
adjList = new ArrayList[v];
for (int i = 0; i < v; i++) {
@@ -41,15 +40,12 @@ private void initAdjList()
}
// add edge from u to v
- public void addEdge(int u, int v)
- {
+ public void addEdge(int u, int v) {
// Add v to u's list.
adjList[u].add(v);
}
-
- public void storeAllPaths(int s, int d)
- {
+ public void storeAllPaths(int s, int d) {
boolean[] isVisited = new boolean[v];
ArrayList pathList = new ArrayList<>();
@@ -61,9 +57,9 @@ public void storeAllPaths(int s, int d)
// A recursive function to print all paths from 'u' to 'd'.
// isVisited[] keeps track of vertices in current path.
- // localPathList<> stores actual vertices in the current path
- private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List localPathList)
- {
+ // localPathList<> stores actual vertices in the current path
+ private void storeAllPathsUtil(
+ Integer u, Integer d, boolean[] isVisited, List localPathList) {
if (u.equals(d)) {
nm.add(new ArrayList<>(localPathList));
@@ -74,7 +70,7 @@ private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination)
- {
+ public static List> allPathsFromSourceToTarget(
+ int vertices, int[][] a, int source, int destination) {
// Create a sample graph
AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices);
- for(int i=0 ; i> combination(int n, int k) {
length = k;
Integer[] arr = new Integer[n];
for (int i = 1; i <= n; i++) {
- arr[i-1] = i;
+ arr[i - 1] = i;
}
return Combination.combination(arr, length);
}
diff --git a/src/main/java/com/thealgorithms/backtracking/Combination.java b/src/main/java/com/thealgorithms/backtracking/Combination.java
index c2d148a270e8..7c45dffb8630 100644
--- a/src/main/java/com/thealgorithms/backtracking/Combination.java
+++ b/src/main/java/com/thealgorithms/backtracking/Combination.java
@@ -38,11 +38,7 @@ public static List> combination(T[] arr, int n) {
* @param the type of elements in the array.
*/
private static void backtracking(
- T[] arr,
- int index,
- TreeSet currSet,
- List> result
- ) {
+ T[] arr, int index, TreeSet currSet, List> result) {
if (index + length - currSet.size() > arr.length) return;
if (length - 1 == currSet.size()) {
for (int i = index; i < arr.length; i++) {
diff --git a/src/main/java/com/thealgorithms/backtracking/FloodFill.java b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
index 6c4446a40bc4..b6b1c5ee19f8 100644
--- a/src/main/java/com/thealgorithms/backtracking/FloodFill.java
+++ b/src/main/java/com/thealgorithms/backtracking/FloodFill.java
@@ -38,13 +38,7 @@ public static void putPixel(int[][] image, int x, int y, int newColor) {
* @param newColor The new color which to be filled in the image
* @param oldColor The old color which is to be replaced in the image
*/
- public static void floodFill(
- int[][] image,
- int x,
- int y,
- int newColor,
- int oldColor
- ) {
+ public static void floodFill(int[][] image, int x, int y, int newColor, int oldColor) {
if (x < 0 || x >= image.length) return;
if (y < 0 || y >= image[x].length) return;
if (getPixel(image, x, y) != oldColor) return;
diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
index a2075fd9d778..882b43537b7f 100644
--- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
+++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
@@ -4,9 +4,10 @@
/*
* Problem Statement: -
-
- Given a N*N board with the Knight placed on the first block of an empty board. Moving according to the rules of
- chess knight must visit each square exactly once. Print the order of each cell in which they are visited.
+
+ Given a N*N board with the Knight placed on the first block of an empty board. Moving according
+ to the rules of chess knight must visit each square exactly once. Print the order of each cell in
+ which they are visited.
Example: -
@@ -27,14 +28,14 @@ public class KnightsTour {
private static final int base = 12;
private static final int[][] moves = {
- { 1, -2 },
- { 2, -1 },
- { 2, 1 },
- { 1, 2 },
- { -1, 2 },
- { -2, 1 },
- { -2, -1 },
- { -1, -2 },
+ {1, -2},
+ {2, -1},
+ {2, 1},
+ {1, 2},
+ {-1, 2},
+ {-2, 1},
+ {-2, -1},
+ {-1, -2},
}; // Possible moves by knight on chess
private static int[][] grid; // chess grid
private static int total; // total squares in chess
@@ -75,23 +76,17 @@ private static boolean solve(int row, int column, int count) {
return false;
}
- Collections.sort(
- neighbor,
- new Comparator() {
- public int compare(int[] a, int[] b) {
- return a[2] - b[2];
- }
+ Collections.sort(neighbor, new Comparator() {
+ public int compare(int[] a, int[] b) {
+ return a[2] - b[2];
}
- );
+ });
for (int[] nb : neighbor) {
row = nb[0];
column = nb[1];
grid[row][column] = count;
- if (
- !orphanDetected(count, row, column) &&
- solve(row, column, count + 1)
- ) {
+ if (!orphanDetected(count, row, column) && solve(row, column, count + 1)) {
return true;
}
grid[row][column] = 0;
@@ -109,7 +104,7 @@ private static List neighbors(int row, int column) {
int y = m[1];
if (grid[row + y][column + x] == 0) {
int num = countNeighbors(row + y, column + x);
- neighbour.add(new int[] { row + y, column + x, num });
+ neighbour.add(new int[] {row + y, column + x, num});
}
}
return neighbour;
diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
index 0e1cd308d6cb..d66d1482d83e 100644
--- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
+++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
@@ -51,9 +51,7 @@ public static void mazeRecursion() {
setWay2(map2, 1, 1);
// Print out the new map1, with the ball footprint
- System.out.println(
- "After the ball goes through the map1,show the current map1 condition"
- );
+ System.out.println("After the ball goes through the map1,show the current map1 condition");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + " ");
@@ -62,9 +60,7 @@ public static void mazeRecursion() {
}
// Print out the new map2, with the ball footprint
- System.out.println(
- "After the ball goes through the map2,show the current map2 condition"
- );
+ System.out.println("After the ball goes through the map2,show the current map2 condition");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map2[i][j] + " ");
@@ -85,7 +81,7 @@ public static void mazeRecursion() {
* means the ball has gone through the path but this path is dead end
* 5. We will need strategy for the ball to pass through the maze for example:
* Down -> Right -> Up -> Left, if the path doesn't work, then backtrack
- *
+ *
* @author OngLipWei
* @version Jun 23, 2021 11:36:14 AM
* @param map The maze
@@ -99,7 +95,8 @@ public static boolean setWay(int[][] map, int i, int j) {
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : down -> right -> up -> left
- map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
+ map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
+ // first。
if (setWay(map, i + 1, j)) { // go down
return true;
} else if (setWay(map, i, j + 1)) { // go right
@@ -129,7 +126,8 @@ public static boolean setWay2(int[][] map, int i, int j) {
}
if (map[i][j] == 0) { // if the ball haven't gone through this point
// then the ball follows the move strategy : up->right->down->left
- map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2 first。
+ map[i][j] = 2; // we assume that this path is feasible first, set the current point to 2
+ // first。
if (setWay2(map, i - 1, j)) { // go up
return true;
} else if (setWay2(map, i, j + 1)) { // go right
diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java
index a567c57b451a..6d45a73a821b 100644
--- a/src/main/java/com/thealgorithms/backtracking/NQueens.java
+++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java
@@ -47,14 +47,8 @@ public static void placeQueens(final int queens) {
List> arrangements = new ArrayList>();
getSolution(queens, arrangements, new int[queens], 0);
if (arrangements.isEmpty()) {
- System.out.println(
- "There is no way to place " +
- queens +
- " queens on board of size " +
- queens +
- "x" +
- queens
- );
+ System.out.println("There is no way to place " + queens + " queens on board of size "
+ + queens + "x" + queens);
} else {
System.out.println("Arrangement for placing " + queens + " queens");
}
@@ -73,11 +67,7 @@ public static void placeQueens(final int queens) {
* @param columnIndex: This is the column in which queen is being placed
*/
private static void getSolution(
- int boardSize,
- List> solutions,
- int[] columns,
- int columnIndex
- ) {
+ int boardSize, List> solutions, int[] columns, int columnIndex) {
if (columnIndex == boardSize) {
// this means that all queens have been placed
List sol = new ArrayList();
@@ -96,7 +86,8 @@ private static void getSolution(
for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) {
columns[columnIndex] = rowIndex;
if (isPlacedCorrectly(columns, rowIndex, columnIndex)) {
- // If queen is placed successfully at rowIndex in column=columnIndex then try placing queen in next column
+ // If queen is placed successfully at rowIndex in column=columnIndex then try
+ // placing queen in next column
getSolution(boardSize, solutions, columns, columnIndex + 1);
}
}
@@ -111,11 +102,7 @@ private static void getSolution(
* @param columnIndex: column in which queen is being placed
* @return true: if queen can be placed safely false: otherwise
*/
- private static boolean isPlacedCorrectly(
- int[] columns,
- int rowIndex,
- int columnIndex
- ) {
+ private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) {
for (int i = 0; i < columnIndex; i++) {
int diff = Math.abs(columns[i] - rowIndex);
if (diff == 0 || columnIndex - i == diff) {
diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
index dc4738583358..72af17d48bd4 100644
--- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java
+++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
@@ -1,11 +1,10 @@
package com.thealgorithms.backtracking;
-
/*
* Problem Statement :
- * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers.
- * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3.
- * Therefore output will be 1.
+ * Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers
+ * of unique, natural numbers. For example, if N=100 and X=3, we have to find all combinations of
+ * unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3. Therefore output will be 1.
*/
public class PowerSum {
@@ -16,26 +15,29 @@ public int powSum(int N, int X) {
return count;
}
- //here i is the natural number which will be raised by X and added in sum.
+ // here i is the natural number which will be raised by X and added in sum.
public void Sum(int N, int X, int i) {
- //if sum is equal to N that is one of our answer and count is increased.
+ // if sum is equal to N that is one of our answer and count is increased.
if (sum == N) {
count++;
return;
- } //we will be adding next natural number raised to X only if on adding it in sum the result is less than N.
+ } // we will be adding next natural number raised to X only if on adding it in sum the
+ // result is less than N.
else if (sum + power(i, X) <= N) {
sum += power(i, X);
Sum(N, X, i + 1);
- //backtracking and removing the number added last since no possible combination is there with it.
+ // backtracking and removing the number added last since no possible combination is
+ // there with it.
sum -= power(i, X);
}
if (power(i, X) < N) {
- //calling the sum function with next natural number after backtracking if when it is raised to X is still less than X.
+ // calling the sum function with next natural number after backtracking if when it is
+ // raised to X is still less than X.
Sum(N, X, i + 1);
}
}
- //creating a separate power function so that it can be used again and again when required.
+ // creating a separate power function so that it can be used again and again when required.
private int power(int a, int b) {
return (int) Math.pow(a, b);
}
diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
index affac0ee6ac2..4ab81bfd7d67 100644
--- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java
+++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
@@ -1,13 +1,12 @@
package com.thealgorithms.backtracking;
-
/*
Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
-The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or
-vertically neighboring. The same letter cell may not be used more than once.
+The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
+those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
@@ -27,8 +26,8 @@ Word Search Problem (https://en.wikipedia.org/wiki/Word_search)
Depth First Search in matrix (as multiple sources possible) with backtracking
like finding cycle in a directed graph. Maintain a record of path
- Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we do it L times
- Sx = O(L) : stack size is max L
+ Tx = O(m * n * 3^L): for each cell, we look at 3 options (not 4 as that one will be visited), we
+ do it L times Sx = O(L) : stack size is max L
*/
public class WordSearch {
@@ -52,8 +51,7 @@ private boolean doDFS(int x, int y, int nextIdx) {
int yi = y + dy[i];
if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) {
boolean exists = doDFS(xi, yi, nextIdx + 1);
- if (exists)
- return true;
+ if (exists) return true;
}
}
visited[x][y] = false;
@@ -68,12 +66,10 @@ public boolean exist(char[][] board, String word) {
if (board[i][j] == word.charAt(0)) {
visited = new boolean[board.length][board[0].length];
boolean exists = doDFS(i, j, 1);
- if (exists)
- return true;
+ if (exists) return true;
}
}
}
return false;
}
}
-
diff --git a/src/main/java/com/thealgorithms/ciphers/AES.java b/src/main/java/com/thealgorithms/ciphers/AES.java
index c5cb286c7772..46886cbcb366 100644
--- a/src/main/java/com/thealgorithms/ciphers/AES.java
+++ b/src/main/java/com/thealgorithms/ciphers/AES.java
@@ -2395,9 +2395,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
// apply S-Box to all 8-Bit Substrings
for (int i = 0; i < 4; i++) {
- StringBuilder currentByteBits = new StringBuilder(
- rBytes.substring(i * 2, (i + 1) * 2)
- );
+ StringBuilder currentByteBits = new StringBuilder(rBytes.substring(i * 2, (i + 1) * 2));
int currentByte = Integer.parseInt(currentByteBits.toString(), 16);
currentByte = SBOX[currentByte];
@@ -2407,8 +2405,7 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
currentByte = currentByte ^ RCON[rconCounter];
}
- currentByteBits =
- new StringBuilder(Integer.toHexString(currentByte));
+ currentByteBits = new StringBuilder(Integer.toHexString(currentByte));
// Add zero padding
while (currentByteBits.length() < 2) {
@@ -2416,12 +2413,8 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
}
// replace bytes in original string
- rBytes =
- new StringBuilder(
- rBytes.substring(0, i * 2) +
- currentByteBits +
- rBytes.substring((i + 1) * 2)
- );
+ rBytes = new StringBuilder(
+ rBytes.substring(0, i * 2) + currentByteBits + rBytes.substring((i + 1) * 2));
}
// t = new BigInteger(rBytes, 16);
@@ -2438,16 +2431,16 @@ public static BigInteger scheduleCore(BigInteger t, int rconCounter) {
public static BigInteger[] keyExpansion(BigInteger initialKey) {
BigInteger[] roundKeys = {
initialKey,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
- BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
+ BigInteger.ZERO,
};
// initialize rcon iteration
@@ -2455,23 +2448,18 @@ public static BigInteger[] keyExpansion(BigInteger initialKey) {
for (int i = 1; i < 11; i++) {
// get the previous 32 bits the key
- BigInteger t =
- roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
+ BigInteger t = roundKeys[i - 1].remainder(new BigInteger("100000000", 16));
// split previous key into 8-bit segments
BigInteger[] prevKey = {
roundKeys[i - 1].remainder(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(
- new BigInteger("10000000000000000", 16)
- )
+ roundKeys[i - 1]
+ .remainder(new BigInteger("10000000000000000", 16))
.divide(new BigInteger("100000000", 16)),
- roundKeys[i - 1].remainder(
- new BigInteger("1000000000000000000000000", 16)
- )
+ roundKeys[i - 1]
+ .remainder(new BigInteger("1000000000000000000000000", 16))
.divide(new BigInteger("10000000000000000", 16)),
- roundKeys[i - 1].divide(
- new BigInteger("1000000000000000000000000", 16)
- ),
+ roundKeys[i - 1].divide(new BigInteger("1000000000000000000000000", 16)),
};
// run schedule core
@@ -2527,9 +2515,7 @@ public static int[] splitBlockIntoCells(BigInteger block) {
public static BigInteger mergeCellsIntoBlock(int[] cells) {
StringBuilder blockBits = new StringBuilder();
for (int i = 0; i < 16; i++) {
- StringBuilder cellBits = new StringBuilder(
- Integer.toBinaryString(cells[i])
- );
+ StringBuilder cellBits = new StringBuilder(Integer.toBinaryString(cells[i]));
// Append leading 0 for full "8-bit" strings
while (cellBits.length() < 8) {
@@ -2545,10 +2531,7 @@ public static BigInteger mergeCellsIntoBlock(int[] cells) {
/**
* @return ciphertext XOR key
*/
- public static BigInteger addRoundKey(
- BigInteger ciphertext,
- BigInteger key
- ) {
+ public static BigInteger addRoundKey(BigInteger ciphertext, BigInteger key) {
return ciphertext.xor(key);
}
@@ -2669,14 +2652,10 @@ public static BigInteger mixColumns(BigInteger ciphertext) {
cells[i * 4 + 3],
};
- outputCells[i * 4] =
- MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3];
- outputCells[i * 4 + 1] =
- row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3];
- outputCells[i * 4 + 2] =
- row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]];
- outputCells[i * 4 + 3] =
- MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]];
+ outputCells[i * 4] = MULT2[row[0]] ^ MULT3[row[1]] ^ row[2] ^ row[3];
+ outputCells[i * 4 + 1] = row[0] ^ MULT2[row[1]] ^ MULT3[row[2]] ^ row[3];
+ outputCells[i * 4 + 2] = row[0] ^ row[1] ^ MULT2[row[2]] ^ MULT3[row[3]];
+ outputCells[i * 4 + 3] = MULT3[row[0]] ^ row[1] ^ row[2] ^ MULT2[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
@@ -2697,26 +2676,13 @@ public static BigInteger mixColumnsDec(BigInteger ciphertext) {
cells[i * 4 + 3],
};
- outputCells[i * 4] =
- MULT14[row[0]] ^
- MULT11[row[1]] ^
- MULT13[row[2]] ^
- MULT9[row[3]];
- outputCells[i * 4 + 1] =
- MULT9[row[0]] ^
- MULT14[row[1]] ^
- MULT11[row[2]] ^
- MULT13[row[3]];
- outputCells[i * 4 + 2] =
- MULT13[row[0]] ^
- MULT9[row[1]] ^
- MULT14[row[2]] ^
- MULT11[row[3]];
- outputCells[i * 4 + 3] =
- MULT11[row[0]] ^
- MULT13[row[1]] ^
- MULT9[row[2]] ^
- MULT14[row[3]];
+ outputCells[i * 4] = MULT14[row[0]] ^ MULT11[row[1]] ^ MULT13[row[2]] ^ MULT9[row[3]];
+ outputCells[i * 4 + 1]
+ = MULT9[row[0]] ^ MULT14[row[1]] ^ MULT11[row[2]] ^ MULT13[row[3]];
+ outputCells[i * 4 + 2]
+ = MULT13[row[0]] ^ MULT9[row[1]] ^ MULT14[row[2]] ^ MULT11[row[3]];
+ outputCells[i * 4 + 3]
+ = MULT11[row[0]] ^ MULT13[row[1]] ^ MULT9[row[2]] ^ MULT14[row[3]];
}
return mergeCellsIntoBlock(outputCells);
}
@@ -2780,9 +2746,7 @@ public static BigInteger decrypt(BigInteger cipherText, BigInteger key) {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
- System.out.println(
- "Enter (e) letter for encrpyt or (d) letter for decrypt :"
- );
+ System.out.println("Enter (e) letter for encrpyt or (d) letter for decrypt :");
char choice = input.nextLine().charAt(0);
String in;
switch (choice) {
diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
index 051b34c2293a..c010d532437f 100644
--- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
+++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java
@@ -1,10 +1,10 @@
package com.thealgorithms.ciphers;
+import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
-import java.security.InvalidAlgorithmParameterException;
/**
* This example program shows how AES encryption and decryption can be done in
@@ -29,12 +29,8 @@ public static void main(String[] args) throws Exception {
String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText);
- System.out.println(
- "AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())
- );
- System.out.println(
- "Encrypted Text (Hex Form):" + bytesToHex(cipherText)
- );
+ System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()));
+ System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText));
System.out.println("Descrypted Text:" + decryptedText);
}
@@ -45,8 +41,7 @@ public static void main(String[] args) throws Exception {
* @return secKey (Secret key that we encrypt using it)
* @throws NoSuchAlgorithmException (from KeyGenrator)
*/
- public static SecretKey getSecretEncryptionKey()
- throws NoSuchAlgorithmException {
+ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
aesKeyGenerator.init(128); // The AES key size in number of bits
return aesKeyGenerator.generateKey();
@@ -63,7 +58,8 @@ public static SecretKey getSecretEncryptionKey()
* @throws IllegalBlockSizeException (from Cipher)
*/
public static byte[] encryptText(String plainText, SecretKey secKey)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
+ throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
+ IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
@@ -76,8 +72,8 @@ public static byte[] encryptText(String plainText, SecretKey secKey)
* @return plainText
*/
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
- IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
+ throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
+ IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
index a6fe0ab9290f..9ff63ddfe7c5 100644
--- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
@@ -15,8 +15,7 @@ static String encryptMessage(char[] msg) {
{here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ') {
- cipher =
- cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
+ cipher = cipher + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else { // else simply append space character
cipher += msg[i];
}
@@ -29,8 +28,8 @@ static String decryptCipher(String cipher) {
int a_inv = 0;
int flag = 0;
- //Find a^-1 (the multiplicative inverse of a
- //in the group of integers modulo m.)
+ // Find a^-1 (the multiplicative inverse of a
+ // in the group of integers modulo m.)
for (int i = 0; i < 26; i++) {
flag = (a * i) % 26;
@@ -45,12 +44,8 @@ static String decryptCipher(String cipher) {
{here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ') {
- msg =
- msg +
- (char) (
- ((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'
- );
- } else { //else simply append space character
+ msg = msg + (char) (((a_inv * ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
+ } else { // else simply append space character
msg += cipher.charAt(i);
}
}
@@ -67,8 +62,6 @@ public static void main(String[] args) {
System.out.println("Encrypted Message is : " + cipherText);
// Calling Decryption function
- System.out.println(
- "Decrypted Message is: " + decryptCipher(cipherText)
- );
+ System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index 8864fc75f342..bce7f699d432 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -10,7 +10,7 @@
public class Blowfish {
- //Initializing substitution boxes
+ // Initializing substitution boxes
String[][] S = {
{
"d1310ba6",
@@ -1046,7 +1046,7 @@ public class Blowfish {
},
};
- //Initializing subkeys with digits of pi
+ // Initializing subkeys with digits of pi
String[] P = {
"243f6a88",
"85a308d3",
@@ -1068,7 +1068,7 @@ public class Blowfish {
"8979fb1b",
};
- //Initializing modVal to 2^32
+ // Initializing modVal to 2^32
long modVal = 4294967296L;
/**
@@ -1098,7 +1098,8 @@ private String hexToBin(String hex) {
* 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
+ * @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);
@@ -1109,7 +1110,8 @@ private String binToHex(String binary) {
}
/**
- * This method returns a string obtained by XOR-ing two strings of same length passed a method parameters
+ * 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
@@ -1118,17 +1120,19 @@ 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');
+ 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
+ * 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
+ * @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 = "";
@@ -1140,20 +1144,17 @@ private String addBin(String a, String b) {
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
- */
+ /*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
- );
+ // 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]);
@@ -1162,30 +1163,30 @@ private String f(String plainText) {
return ans;
}
- //generate subkeys
+ // 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
+ // 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
+ // 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
+ // output from F function
String fOut = f(left);
right = xor(fOut, right);
- //swap left and right
+ // swap left and right
return right + left;
}
@@ -1198,12 +1199,12 @@ private String round(int time, String plainText) {
* @return String cipherText is the encrypted value
*/
String encrypt(String plainText, String key) {
- //generating key
+ // generating key
keyGenerate(key);
for (int i = 0; i < 16; i++) plainText = round(i, plainText);
- //postprocessing
+ // postprocessing
String right = plainText.substring(0, 8);
String left = plainText.substring(8, 16);
right = xor(right, P[16]);
@@ -1220,12 +1221,12 @@ String encrypt(String plainText, String key) {
* @return String plainText is the decrypted text
*/
String decrypt(String cipherText, String key) {
- //generating key
+ // generating key
keyGenerate(key);
for (int i = 17; i > 1; i--) cipherText = round(i, cipherText);
- //postprocessing
+ // postprocessing
String right = cipherText.substring(0, 8);
String left = cipherText.substring(8, 16);
right = xor(right, P[1]);
diff --git a/src/main/java/com/thealgorithms/ciphers/Caesar.java b/src/main/java/com/thealgorithms/ciphers/Caesar.java
index a5f89fba7180..6011909abc33 100644
--- a/src/main/java/com/thealgorithms/ciphers/Caesar.java
+++ b/src/main/java/com/thealgorithms/ciphers/Caesar.java
@@ -23,16 +23,19 @@ public String encode(String message, int shift) {
final int length = message.length();
for (int i = 0; i < length; i++) {
- // int current = message.charAt(i); //using char to shift characters because ascii
+ // int current = message.charAt(i); //using char to shift characters because
+ // ascii
// is in-order latin alphabet
char current = message.charAt(i); // Java law : char + int = char
if (isCapitalLatinLetter(current)) {
current += shift;
- encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
+ encoded.append((
+ char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) {
current += shift;
- encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
+ encoded.append((
+ char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else {
encoded.append(current);
}
@@ -56,10 +59,12 @@ public String decode(String encryptedMessage, int shift) {
char current = encryptedMessage.charAt(i);
if (isCapitalLatinLetter(current)) {
current -= shift;
- decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
+ decoded.append((
+ char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (isSmallLatinLetter(current)) {
current -= shift;
- decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
+ decoded.append((
+ char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else {
decoded.append(current);
}
diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
index 35f15e587d2f..70b1f7ea147b 100644
--- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
@@ -12,9 +12,8 @@ public class ColumnarTranspositionCipher {
private static String keyword;
private static Object[][] table;
private static String abecedarium;
- public static final String ABECEDARIUM =
- "abcdefghijklmnopqrstuvwxyzABCDEFG" +
- "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
+ public static final String ABECEDARIUM = "abcdefghijklmnopqrstuvwxyzABCDEFG"
+ + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
private static final String ENCRYPTION_FIELD = "≈";
private static final char ENCRYPTION_FIELD_CHAR = '≈';
@@ -50,14 +49,10 @@ public static String encrpyter(String word, String keyword) {
* @return a String with the word encrypted by the Columnar Transposition
* Cipher Rule
*/
- public static String encrpyter(
- String word,
- String keyword,
- String abecedarium
- ) {
+ public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword;
- ColumnarTranspositionCipher.abecedarium =
- Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
+ ColumnarTranspositionCipher.abecedarium
+ = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word);
Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder();
@@ -120,9 +115,7 @@ private static Object[][] tableBuilder(String word) {
* order to respect the Columnar Transposition Cipher Rule.
*/
private static int numberOfRows(String word) {
- if (
- word.length() / keyword.length() > word.length() / keyword.length()
- ) {
+ if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else {
return word.length() / keyword.length();
@@ -147,22 +140,12 @@ private static Object[] findElements() {
private static Object[][] sortTable(Object[][] table) {
Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < tableSorted.length; i++) {
- System.arraycopy(
- table[i],
- 0,
- tableSorted[i],
- 0,
- tableSorted[i].length
- );
+ System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
}
for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) {
- Object[] column = getColumn(
- tableSorted,
- tableSorted.length,
- i
- );
+ Object[] column = getColumn(tableSorted, tableSorted.length, i);
switchColumns(tableSorted, j, i, column);
}
}
@@ -182,11 +165,7 @@ private static Object[] getColumn(Object[][] table, int rows, int column) {
}
private static void switchColumns(
- Object[][] table,
- int firstColumnIndex,
- int secondColumnIndex,
- Object[] columnToSwitch
- ) {
+ Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
for (int i = 0; i < table.length; i++) {
table[i][secondColumnIndex] = table[i][firstColumnIndex];
table[i][firstColumnIndex] = columnToSwitch[i];
@@ -217,22 +196,12 @@ private static void showTable() {
public static void main(String[] args) {
String keywordForExample = "asd215";
- String wordBeingEncrypted =
- "This is a test of the Columnar Transposition Cipher";
- System.out.println(
- "### Example of Columnar Transposition Cipher ###\n"
- );
+ String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
+ System.out.println("### Example of Columnar Transposition Cipher ###\n");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
- System.out.println(
- "Word encrypted ->>> " +
- ColumnarTranspositionCipher.encrpyter(
- wordBeingEncrypted,
- keywordForExample
- )
- );
- System.out.println(
- "Word decryped ->>> " + ColumnarTranspositionCipher.decrypter()
- );
+ System.out.println("Word encrypted ->>> "
+ + ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
+ System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###");
showTable();
}
diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java
index aae8282eae42..b6ca8fb8a87d 100644
--- a/src/main/java/com/thealgorithms/ciphers/DES.java
+++ b/src/main/java/com/thealgorithms/ciphers/DES.java
@@ -1,8 +1,9 @@
package com.thealgorithms.ciphers;
/**
- * This class is build to demonstrate the application of the DES-algorithm (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a
- * plain English message. The supplied key must be in form of a 64 bit binary String.
+ * This class is build to demonstrate the application of the DES-algorithm
+ * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied
+ * key must be in form of a 64 bit binary String.
*/
public class DES {
@@ -12,7 +13,8 @@ public class DES {
private void sanitize(String key) {
int length = key.length();
if (length != 64) {
- throw new IllegalArgumentException("DES key must be supplied as a 64 character binary string");
+ throw new IllegalArgumentException(
+ "DES key must be supplied as a 64 character binary string");
}
}
@@ -30,170 +32,102 @@ public void setKey(String key) {
sanitize(key);
this.key = key;
}
-
- //Permutation table to convert initial 64 bit key to 56 bit key
- private static int[] PC1 =
- {
- 57, 49, 41, 33, 25, 17, 9,
- 1, 58, 50, 42, 34, 26, 18,
- 10, 2, 59, 51, 43, 35, 27,
- 19, 11, 3, 60, 52, 44, 36,
- 63, 55, 47, 39, 31, 23, 15,
- 7, 62, 54, 46, 38, 30, 22,
- 14, 6, 61, 53, 45, 37, 29,
- 21, 13, 5, 28, 20, 12, 4
- };
-
- //Lookup table used to shift the initial key, in order to generate the subkeys
- private static int[] KEY_SHIFTS =
- {
- 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
- };
-
- //Table to convert the 56 bit subkeys to 48 bit subkeys
- private static int[] PC2 =
- {
- 14, 17, 11, 24, 1, 5,
- 3, 28, 15, 6, 21, 10,
- 23, 19, 12, 4, 26, 8,
- 16, 7, 27, 20, 13, 2,
- 41, 52, 31, 37, 47, 55,
- 30, 40, 51, 45, 33, 48,
- 44, 49, 39, 56, 34, 53,
- 46, 42, 50, 36, 29, 32
- };
-
- //Initial permutatation of each 64 but message block
- private static int[] IP =
- {
- 58, 50, 42, 34, 26, 18, 10 , 2,
- 60, 52, 44, 36, 28, 20, 12, 4,
- 62, 54, 46, 38, 30, 22, 14, 6,
- 64, 56, 48, 40, 32, 24, 16, 8,
- 57, 49, 41, 33, 25, 17, 9, 1,
- 59, 51, 43, 35, 27, 19, 11, 3,
- 61, 53, 45, 37, 29, 21, 13, 5,
- 63, 55, 47, 39, 31, 23, 15, 7
- };
-
- //Expansion table to convert right half of message blocks from 32 bits to 48 bits
- private static int[] expansion =
- {
- 32, 1, 2, 3, 4, 5,
- 4, 5, 6, 7, 8, 9,
- 8, 9, 10, 11, 12, 13,
- 12, 13, 14, 15, 16, 17,
- 16, 17, 18, 19, 20, 21,
- 20, 21, 22, 23, 24, 25,
- 24, 25, 26, 27, 28, 29,
- 28, 29, 30, 31, 32, 1
- };
-
- //The eight substitution boxes are defined below
- private static int[][] s1 = {
- {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
- {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
- {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
- {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}
- };
-
- private static int[][] s2 = {
- {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
- {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
- {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
- {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}
- };
-
- private static int[][] s3 = {
- {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
- {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
- {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
- {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}
- };
-
- private static int[][] s4 = {
- {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
- {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
- {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
- {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}
- };
-
- private static int[][] s5 = {
- {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
- {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
- {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
- {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}
- };
-
- private static int[][] s6 = {
- {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
- {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
- {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
- {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}
- };
-
- private static int[][] s7 = {
- {4, 11, 2, 14, 15, 0, 8, 13 , 3, 12, 9 , 7, 5, 10, 6, 1},
- {13 , 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
- {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
- {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}
- };
-
- private static int[][] s8 = {
- {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
- {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6 ,11, 0, 14, 9, 2},
- {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10 ,13, 15, 3, 5, 8},
- {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6 ,11}
- };
-
- private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
-
- //Permutation table, used in the feistel function post s-box usage
- static int[] permutation =
- {
- 16, 7, 20, 21,
- 29, 12, 28, 17,
- 1, 15, 23, 26,
- 5, 18, 31, 10,
- 2, 8, 24, 14,
- 32, 27, 3, 9,
- 19, 13, 30, 6,
- 22, 11, 4, 25
- };
-
- //Table used for final inversion of the message box after 16 rounds of Feistel Function
- static int[] IPinverse =
- {
- 40, 8, 48, 16, 56, 24, 64, 32,
- 39, 7, 47, 15, 55, 23, 63, 31,
- 38, 6, 46, 14, 54, 22, 62, 30,
- 37, 5, 45, 13, 53, 21, 61, 29,
- 36, 4, 44, 12, 52, 20, 60, 28,
- 35, 3, 43 ,11, 51, 19, 59, 27,
- 34, 2, 42, 10, 50, 18, 58, 26,
- 33, 1, 41, 9, 49, 17, 57, 25
- };
+
+ // Permutation table to convert initial 64 bit key to 56 bit key
+ private static int[] PC1 = {57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51,
+ 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30,
+ 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4};
+
+ // Lookup table used to shift the initial key, in order to generate the subkeys
+ private static int[] KEY_SHIFTS = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};
+
+ // Table to convert the 56 bit subkeys to 48 bit subkeys
+ private static int[] PC2 = {14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8,
+ 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34,
+ 53, 46, 42, 50, 36, 29, 32};
+
+ // Initial permutatation of each 64 but message block
+ private static int[] IP = {58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54,
+ 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8, 57, 49, 41, 33, 25, 17, 9, 1, 59, 51,
+ 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7};
+
+ // Expansion table to convert right half of message blocks from 32 bits to 48 bits
+ private static int[] expansion = {32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12,
+ 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29,
+ 28, 29, 30, 31, 32, 1};
+
+ // The eight substitution boxes are defined below
+ private static int[][] s1 = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7},
+ {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8},
+ {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0},
+ {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}};
+
+ private static int[][] s2 = {{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10},
+ {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5},
+ {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15},
+ {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}};
+
+ private static int[][] s3 = {{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8},
+ {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1},
+ {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7},
+ {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}};
+
+ private static int[][] s4 = {{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15},
+ {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9},
+ {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4},
+ {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}};
+
+ private static int[][] s5 = {{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9},
+ {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6},
+ {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14},
+ {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}};
+
+ private static int[][] s6 = {{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11},
+ {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8},
+ {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6},
+ {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}};
+
+ private static int[][] s7 = {{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1},
+ {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6},
+ {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2},
+ {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}};
+
+ private static int[][] s8 = {{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7},
+ {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2},
+ {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8},
+ {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
+
+ private static int[][][] s = {s1, s2, s3, s4, s5, s6, s7, s8};
+
+ // Permutation table, used in the feistel function post s-box usage
+ static int[] permutation = {16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10, 2, 8,
+ 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25};
+
+ // Table used for final inversion of the message box after 16 rounds of Feistel Function
+ static int[] IPinverse = {40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31, 38, 6,
+ 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3,
+ 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25};
private String[] getSubkeys(String originalKey) {
- StringBuilder permutedKey = new StringBuilder(); //Initial permutation of keys via PC1
+ StringBuilder permutedKey = new StringBuilder(); // Initial permutation of keys via PC1
int i, j;
for (i = 0; i < 56; i++) {
- permutedKey.append(originalKey.charAt(PC1[i] - 1));
+ permutedKey.append(originalKey.charAt(PC1[i] - 1));
}
String subKeys[] = new String[16];
String initialPermutedKey = permutedKey.toString();
String C0 = initialPermutedKey.substring(0, 28), D0 = initialPermutedKey.substring(28);
-
- //We will now operate on the left and right halves of the permutedKey
+
+ // We will now operate on the left and right halves of the permutedKey
for (i = 0; i < 16; i++) {
String Cn = C0.substring(KEY_SHIFTS[i]) + C0.substring(0, KEY_SHIFTS[i]);
String Dn = D0.substring(KEY_SHIFTS[i]) + D0.substring(0, KEY_SHIFTS[i]);
subKeys[i] = Cn + Dn;
- C0 = Cn; //Re-assign the values to create running permutation
+ C0 = Cn; // Re-assign the values to create running permutation
D0 = Dn;
}
- //Let us shrink the keys to 48 bits (well, characters here) using PC2
+ // Let us shrink the keys to 48 bits (well, characters here) using PC2
for (i = 0; i < 16; i++) {
String key = subKeys[i];
permutedKey.setLength(0);
@@ -244,16 +178,17 @@ private String feistel(String messageBlock, String key) {
String mixedKey = XOR(expandedKey.toString(), key);
StringBuilder substitutedString = new StringBuilder();
- //Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
+ // Let us now use the s-boxes to transform each 6 bit (length here) block to 4 bits
for (i = 0; i < 48; i += 6) {
String block = mixedKey.substring(i, i + 6);
int row = (block.charAt(0) - 48) * 2 + (block.charAt(5) - 48);
- int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4 + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
+ int col = (block.charAt(1) - 48) * 8 + (block.charAt(2) - 48) * 4
+ + (block.charAt(3) - 48) * 2 + (block.charAt(4) - 48);
String substitutedBlock = pad(Integer.toBinaryString(s[i / 6][row][col]), 4);
substitutedString.append(substitutedBlock);
}
- StringBuilder permutedString = new StringBuilder();
+ StringBuilder permutedString = new StringBuilder();
for (i = 0; i < 32; i++) {
permutedString.append(substitutedString.charAt(permutation[i] - 1));
}
@@ -269,7 +204,7 @@ private String encryptBlock(String message, String keys[]) {
}
String L0 = permutedMessage.substring(0, 32), R0 = permutedMessage.substring(32);
- //Iterate 16 times
+ // Iterate 16 times
for (i = 0; i < 16; i++) {
String Ln = R0; // Previous Right block
String Rn = XOR(L0, feistel(R0, keys[i]));
@@ -277,7 +212,7 @@ private String encryptBlock(String message, String keys[]) {
R0 = Rn;
}
- String combinedBlock = R0 + L0; //Reverse the 16th block
+ String combinedBlock = R0 + L0; // Reverse the 16th block
permutedMessage.setLength(0);
for (i = 0; i < 64; i++) {
permutedMessage.append(combinedBlock.charAt(IPinverse[i] - 1));
@@ -285,7 +220,7 @@ private String encryptBlock(String message, String keys[]) {
return permutedMessage.toString();
}
- //To decode, we follow the same process as encoding, but with reversed keys
+ // To decode, we follow the same process as encoding, but with reversed keys
private String decryptBlock(String message, String keys[]) {
String reversedKeys[] = new String[keys.length];
for (int i = 0; i < keys.length; i++) {
@@ -307,7 +242,7 @@ public String encrypt(String message) {
message = padLast(message, desiredLength);
}
- for (i = 0; i < l; i+= 8) {
+ for (i = 0; i < l; i += 8) {
String block = message.substring(i, i + 8);
StringBuilder bitBlock = new StringBuilder();
byte[] bytes = block.getBytes();
@@ -327,18 +262,19 @@ public String decrypt(String message) {
StringBuilder decryptedMessage = new StringBuilder();
int l = message.length(), i, j;
if (l % 64 != 0) {
- throw new IllegalArgumentException("Encrypted message should be a multiple of 64 characters in length");
+ throw new IllegalArgumentException(
+ "Encrypted message should be a multiple of 64 characters in length");
}
- for (i = 0; i < l; i+= 64) {
+ for (i = 0; i < l; i += 64) {
String block = message.substring(i, i + 64);
String result = decryptBlock(block.toString(), subKeys);
byte res[] = new byte[8];
- for (j = 0; j < 64; j+=8) {
- res[j / 8] = (byte)Integer.parseInt(result.substring(j, j + 8), 2);
+ for (j = 0; j < 64; j += 8) {
+ res[j / 8] = (byte) Integer.parseInt(result.substring(j, j + 8), 2);
}
decryptedMessage.append(new String(res));
}
- return decryptedMessage.toString().replace("\0", ""); // Get rid of the null bytes used for padding
+ return decryptedMessage.toString().replace(
+ "\0", ""); // Get rid of the null bytes used for padding
}
-
}
diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
index ffc7e08bedf7..a3226cef7de1 100644
--- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java
@@ -4,10 +4,11 @@
/*
* Java Implementation of Hill Cipher
- * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25.
- * To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26.
- * To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
- * The cipher key and plaintext/ciphertext are user inputs.
+ * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number
+ * belonging to the set Z26 where A=0 , B=1, ..... Z=25. To encrypt a message, each block of n
+ * letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against
+ * modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used
+ * for encryption. The cipher key and plaintext/ciphertext are user inputs.
* @author Ojasva Jain
*/
public class HillCipher {
@@ -28,7 +29,7 @@ static void encrypt(String message) {
keyMatrix[i][j] = userInput.nextInt();
}
}
- //check if det = 0
+ // check if det = 0
validateDeterminant(keyMatrix, matrixSize);
int[][] messageVector = new int[matrixSize][1];
@@ -62,7 +63,7 @@ static void encrypt(String message) {
System.out.println("Ciphertext: " + CipherText);
}
- //Following function decrypts a message
+ // Following function decrypts a message
static void decrypt(String message) {
message = message.toUpperCase();
// Get key matrix
@@ -75,10 +76,10 @@ static void decrypt(String message) {
keyMatrix[i][j] = userInput.nextInt();
}
}
- //check if det = 0
+ // check if det = 0
validateDeterminant(keyMatrix, n);
- //solving for the required plaintext message
+ // solving for the required plaintext message
int[][] messageVector = new int[n][1];
String PlainText = "";
int[][] plainMatrix = new int[n][1];
@@ -157,9 +158,7 @@ static void hillCipher(String message) {
static void validateDeterminant(int[][] keyMatrix, int n) {
if (determinant(keyMatrix, n) % 26 == 0) {
- System.out.println(
- "Invalid key, as determinant = 0. Program Terminated"
- );
+ System.out.println("Invalid key, as determinant = 0. Program Terminated");
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Polybius.java b/src/main/java/com/thealgorithms/ciphers/Polybius.java
index 30eba49807f7..7b5a27807bc4 100644
--- a/src/main/java/com/thealgorithms/ciphers/Polybius.java
+++ b/src/main/java/com/thealgorithms/ciphers/Polybius.java
@@ -7,7 +7,8 @@
* Letters in alphabet takes place to two dimension table.
* Encrypted text is created according to row and column in two dimension table
* Decrypted text is generated by looking at the row and column respectively
- * Additionally, some letters in english alphabet deliberately throws such as U because U is very similar with V
+ * Additionally, some letters in english alphabet deliberately throws such as U because U is very
+ * similar with V
*
* @author Hikmet ÇAKIR
* @since 08-07-2022+03:00
@@ -16,11 +17,11 @@ public class Polybius {
private static final char[][] key = {
// 0 1 2 3 4
- /* 0 */{ 'A', 'B', 'C', 'D', 'E' },
- /* 1 */{ 'F', 'G', 'H', 'I', 'J' },
- /* 2 */{ 'K', 'L', 'M', 'N', 'O' },
- /* 3 */{ 'P', 'Q', 'R', 'S', 'T' },
- /* 4 */{ 'V', 'W', 'X', 'Y', 'Z' },
+ /* 0 */ {'A', 'B', 'C', 'D', 'E'},
+ /* 1 */ {'F', 'G', 'H', 'I', 'J'},
+ /* 2 */ {'K', 'L', 'M', 'N', 'O'},
+ /* 3 */ {'P', 'Q', 'R', 'S', 'T'},
+ /* 4 */ {'V', 'W', 'X', 'Y', 'Z'},
};
private static String findLocationByCharacter(final char character) {
diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java
index 08f4e1980f92..e28eaecb3d1b 100644
--- a/src/main/java/com/thealgorithms/ciphers/RSA.java
+++ b/src/main/java/com/thealgorithms/ciphers/RSA.java
@@ -20,8 +20,7 @@ public RSA(int bits) {
* @return encrypted message
*/
public synchronized String encrypt(String message) {
- return (new BigInteger(message.getBytes())).modPow(publicKey, modulus)
- .toString();
+ return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
@@ -36,9 +35,7 @@ public synchronized BigInteger encrypt(BigInteger message) {
*/
public synchronized String decrypt(String encryptedMessage) {
return new String(
- (new BigInteger(encryptedMessage)).modPow(privateKey, modulus)
- .toByteArray()
- );
+ (new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
@@ -57,8 +54,7 @@ public synchronized void generateKeys(int bits) {
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
- BigInteger m =
- (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
+ BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = BigInteger.valueOf(3L);
diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
index 32b08f0cc38b..f6c88ef730ec 100644
--- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
@@ -82,5 +82,4 @@ public String decode(String encryptedMessage, String cipherSmall) {
return decoded.toString();
}
-
}
diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
index fe7ff8d03dca..1702f1abb94c 100644
--- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java
+++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
@@ -16,21 +16,9 @@ public String encrypt(final String message, final String key) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
- result.append(
- (char) (
- (c + key.toUpperCase().charAt(j) - 2 * 'A') %
- 26 +
- 'A'
- )
- );
+ result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'));
} else {
- result.append(
- (char) (
- (c + key.toLowerCase().charAt(j) - 2 * 'a') %
- 26 +
- 'a'
- )
- );
+ result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'));
}
} else {
result.append(c);
@@ -48,17 +36,9 @@ public String decrypt(final String message, final String key) {
char c = message.charAt(i);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
- result.append(
- (char) (
- 'Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26
- )
- );
+ result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26));
} else {
- result.append(
- (char) (
- 'z' - (25 - (c - key.toLowerCase().charAt(j))) % 26
- )
- );
+ result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26));
}
} else {
result.append(c);
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
index b7d36db5c809..809f85072e48 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
@@ -6,7 +6,8 @@
public class A5Cipher {
private final A5KeyStreamGenerator keyStreamGenerator;
- private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
+ private static final int KEY_STREAM_LENGTH
+ = 228; // 28.5 bytes so we need to pad bytes or something
public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
keyStreamGenerator = new A5KeyStreamGenerator();
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
index 7788efc17774..148a49cf0959 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5KeyStreamGenerator.java
@@ -9,7 +9,8 @@ public class A5KeyStreamGenerator extends CompositeLFSR {
private BitSet frameCounter;
private BitSet sessionKey;
private static final int INITIAL_CLOCKING_CYCLES = 100;
- private static final int KEY_STREAM_LENGTH = 228; // 28.5 bytes so we need to pad bytes or something
+ private static final int KEY_STREAM_LENGTH
+ = 228; // 28.5 bytes so we need to pad bytes or something
@Override
public void initialize(BitSet sessionKey, BitSet frameCounter) {
@@ -17,9 +18,9 @@ public void initialize(BitSet sessionKey, BitSet frameCounter) {
this.frameCounter = (BitSet) frameCounter.clone();
this.initialFrameCounter = (BitSet) frameCounter.clone();
registers.clear();
- LFSR lfsr1 = new LFSR(19, 8, new int[] { 13, 16, 17, 18 });
- LFSR lfsr2 = new LFSR(22, 10, new int[] { 20, 21 });
- LFSR lfsr3 = new LFSR(23, 10, new int[] { 7, 20, 21, 22 });
+ LFSR lfsr1 = new LFSR(19, 8, new int[] {13, 16, 17, 18});
+ LFSR lfsr2 = new LFSR(22, 10, new int[] {20, 21});
+ LFSR lfsr3 = new LFSR(23, 10, new int[] {7, 20, 21, 22});
registers.add(lfsr1);
registers.add(lfsr2);
registers.add(lfsr3);
@@ -31,11 +32,7 @@ public void reInitialize() {
}
public BitSet getNextKeyStream() {
- for (
- int cycle = 1;
- cycle <= INITIAL_CLOCKING_CYCLES;
- ++cycle
- ) this.clock();
+ for (int cycle = 1; cycle <= INITIAL_CLOCKING_CYCLES; ++cycle) this.clock();
BitSet result = new BitSet(KEY_STREAM_LENGTH);
for (int cycle = 1; cycle <= KEY_STREAM_LENGTH; ++cycle) {
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
index 050657166e77..2d0309a98482 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/CompositeLFSR.java
@@ -29,12 +29,8 @@ private boolean getMajorityBit() {
bitCount.put(false, 0);
bitCount.put(true, 0);
- registers.forEach(lfsr ->
- bitCount.put(
- lfsr.getClockBit(),
- bitCount.get(lfsr.getClockBit()) + 1
- )
- );
+ registers.forEach(
+ lfsr -> bitCount.put(lfsr.getClockBit(), bitCount.get(lfsr.getClockBit()) + 1));
return bitCount.get(false) <= bitCount.get(true);
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
index b9220d11f868..abdd11d6b72d 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/Utils.java
@@ -1,8 +1,9 @@
package com.thealgorithms.ciphers.a5;
-// Source http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html
-//package com.java2s;
-//License from project: Open Source License
+// Source
+// http://www.java2s.com/example/java-utility-method/bitset/increment-bitset-bits-int-size-9fd84.html
+// package com.java2s;
+// License from project: Open Source License
import java.util.BitSet;
@@ -11,7 +12,7 @@ public class Utils {
public static boolean increment(BitSet bits, int size) {
int i = size - 1;
while (i >= 0 && bits.get(i)) {
- bits.set(i--, false);/*from w w w . j a v a 2s .c o m*/
+ bits.set(i--, false); /*from w w w . j a v a 2s .c o m*/
}
if (i < 0) {
return false;
diff --git a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
index b5974dd65f3b..c6450a4555ce 100644
--- a/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
+++ b/src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java
@@ -30,13 +30,8 @@ public static void main(String[] args) {
try {
System.out.print("Enter number: ");
n = in.next();
- System.out.print(
- "Enter beginning base (between " +
- MINIMUM_BASE +
- " and " +
- MAXIMUM_BASE +
- "): "
- );
+ System.out.print("Enter beginning base (between " + MINIMUM_BASE + " and "
+ + MAXIMUM_BASE + "): ");
b1 = in.nextInt();
if (b1 > MAXIMUM_BASE || b1 < MINIMUM_BASE) {
System.out.println("Invalid base!");
@@ -47,12 +42,7 @@ public static void main(String[] args) {
continue;
}
System.out.print(
- "Enter end base (between " +
- MINIMUM_BASE +
- " and " +
- MAXIMUM_BASE +
- "): "
- );
+ "Enter end base (between " + MINIMUM_BASE + " and " + MAXIMUM_BASE + "): ");
b2 = in.nextInt();
if (b2 > MAXIMUM_BASE || b2 < MINIMUM_BASE) {
System.out.println("Invalid base!");
diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
index df547ffb5610..a77be2f50e07 100644
--- a/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
+++ b/src/main/java/com/thealgorithms/conversions/DecimalToAnyBase.java
@@ -11,9 +11,7 @@
public class DecimalToAnyBase {
public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(
- new InputStreamReader(System.in)
- );
+ BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal input below: ");
int decInput = Integer.parseInt(br.readLine());
System.out.println();
@@ -22,15 +20,10 @@ public static void main(String[] args) throws Exception {
int base = Integer.parseInt(br.readLine());
System.out.println();
- System.out.println("Decimal Input" + " is: " + decInput);
- System.out.println(
- "Value of " +
- decInput +
- " in base " +
- base +
- " is: " +
- convertToAnyBase(decInput, base)
- );
+ System.out.println("Decimal Input"
+ + " is: " + decInput);
+ System.out.println("Value of " + decInput + " in base " + base
+ + " is: " + convertToAnyBase(decInput, base));
br.close();
}
diff --git a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
index c87508c62e86..a6119cfbc9bc 100644
--- a/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
+++ b/src/main/java/com/thealgorithms/conversions/DecimalToBinary.java
@@ -24,9 +24,7 @@ public static void main(String[] args) {
public static void conventionalConversion() {
int n, b = 0, c = 0, d;
Scanner input = new Scanner(System.in);
- System.out.printf(
- "Conventional conversion.%n Enter the decimal number: "
- );
+ System.out.printf("Conventional conversion.%n Enter the decimal number: ");
n = input.nextInt();
while (n != 0) {
d = n % 2;
diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java
index 2a57fbde5c41..69707c80530a 100644
--- a/src/main/java/com/thealgorithms/conversions/HexToOct.java
+++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java
@@ -61,7 +61,8 @@ public static void main(String[] args) {
hexadecnum = scan.nextLine();
// first convert hexadecimal to decimal
- decnum = hex2decimal(hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
+ decnum = hex2decimal(
+ hexadecnum); // Pass the string to the hex2decimal function and get the decimal form in
// variable decnum
// convert decimal to octal
diff --git a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
index 4fad34ec8844..dc7310061009 100644
--- a/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
+++ b/src/main/java/com/thealgorithms/conversions/RgbHsvConversion.java
@@ -19,69 +19,30 @@ public static void main(String[] args) {
// Expected RGB-values taken from https://www.rapidtables.com/convert/color/hsv-to-rgb.html
// Test hsvToRgb-method
- assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] { 0, 0, 0 });
- assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] { 255, 255, 255 });
- assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] { 255, 0, 0 });
- assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] { 255, 255, 0 });
- assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] { 0, 255, 0 });
- assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] { 0, 0, 255 });
- assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] { 255, 0, 255 });
- assert Arrays.equals(
- hsvToRgb(180, 0.5, 0.5),
- new int[] { 64, 128, 128 }
- );
- assert Arrays.equals(
- hsvToRgb(234, 0.14, 0.88),
- new int[] { 193, 196, 224 }
- );
- assert Arrays.equals(
- hsvToRgb(330, 0.75, 0.5),
- new int[] { 128, 32, 80 }
- );
+ assert Arrays.equals(hsvToRgb(0, 0, 0), new int[] {0, 0, 0});
+ assert Arrays.equals(hsvToRgb(0, 0, 1), new int[] {255, 255, 255});
+ assert Arrays.equals(hsvToRgb(0, 1, 1), new int[] {255, 0, 0});
+ assert Arrays.equals(hsvToRgb(60, 1, 1), new int[] {255, 255, 0});
+ assert Arrays.equals(hsvToRgb(120, 1, 1), new int[] {0, 255, 0});
+ assert Arrays.equals(hsvToRgb(240, 1, 1), new int[] {0, 0, 255});
+ assert Arrays.equals(hsvToRgb(300, 1, 1), new int[] {255, 0, 255});
+ assert Arrays.equals(hsvToRgb(180, 0.5, 0.5), new int[] {64, 128, 128});
+ assert Arrays.equals(hsvToRgb(234, 0.14, 0.88), new int[] {193, 196, 224});
+ assert Arrays.equals(hsvToRgb(330, 0.75, 0.5), new int[] {128, 32, 80});
// Test rgbToHsv-method
// approximate-assertions needed because of small deviations due to converting between
// int-values and double-values.
- assert approximatelyEqualHsv(
- rgbToHsv(0, 0, 0),
- new double[] { 0, 0, 0 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 255, 255),
- new double[] { 0, 0, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 0, 0),
- new double[] { 0, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 255, 0),
- new double[] { 60, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(0, 255, 0),
- new double[] { 120, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(0, 0, 255),
- new double[] { 240, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(255, 0, 255),
- new double[] { 300, 1, 1 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(64, 128, 128),
- new double[] { 180, 0.5, 0.5 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(193, 196, 224),
- new double[] { 234, 0.14, 0.88 }
- );
- assert approximatelyEqualHsv(
- rgbToHsv(128, 32, 80),
- new double[] { 330, 0.75, 0.5 }
- );
+ assert approximatelyEqualHsv(rgbToHsv(0, 0, 0), new double[] {0, 0, 0});
+ assert approximatelyEqualHsv(rgbToHsv(255, 255, 255), new double[] {0, 0, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 0, 0), new double[] {0, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 255, 0), new double[] {60, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(0, 255, 0), new double[] {120, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(0, 0, 255), new double[] {240, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(255, 0, 255), new double[] {300, 1, 1});
+ assert approximatelyEqualHsv(rgbToHsv(64, 128, 128), new double[] {180, 0.5, 0.5});
+ assert approximatelyEqualHsv(rgbToHsv(193, 196, 224), new double[] {234, 0.14, 0.88});
+ assert approximatelyEqualHsv(rgbToHsv(128, 32, 80), new double[] {330, 0.75, 0.5});
}
/**
@@ -94,35 +55,23 @@ assert approximatelyEqualHsv(
*/
public static int[] hsvToRgb(double hue, double saturation, double value) {
if (hue < 0 || hue > 360) {
- throw new IllegalArgumentException(
- "hue should be between 0 and 360"
- );
+ throw new IllegalArgumentException("hue should be between 0 and 360");
}
if (saturation < 0 || saturation > 1) {
- throw new IllegalArgumentException(
- "saturation should be between 0 and 1"
- );
+ throw new IllegalArgumentException("saturation should be between 0 and 1");
}
if (value < 0 || value > 1) {
- throw new IllegalArgumentException(
- "value should be between 0 and 1"
- );
+ throw new IllegalArgumentException("value should be between 0 and 1");
}
double chroma = value * saturation;
double hueSection = hue / 60;
- double secondLargestComponent =
- chroma * (1 - Math.abs(hueSection % 2 - 1));
+ double secondLargestComponent = chroma * (1 - Math.abs(hueSection % 2 - 1));
double matchValue = value - chroma;
- return getRgbBySection(
- hueSection,
- chroma,
- matchValue,
- secondLargestComponent
- );
+ return getRgbBySection(hueSection, chroma, matchValue, secondLargestComponent);
}
/**
@@ -135,21 +84,15 @@ public static int[] hsvToRgb(double hue, double saturation, double value) {
*/
public static double[] rgbToHsv(int red, int green, int blue) {
if (red < 0 || red > 255) {
- throw new IllegalArgumentException(
- "red should be between 0 and 255"
- );
+ throw new IllegalArgumentException("red should be between 0 and 255");
}
if (green < 0 || green > 255) {
- throw new IllegalArgumentException(
- "green should be between 0 and 255"
- );
+ throw new IllegalArgumentException("green should be between 0 and 255");
}
if (blue < 0 || blue > 255) {
- throw new IllegalArgumentException(
- "blue should be between 0 and 255"
- );
+ throw new IllegalArgumentException("blue should be between 0 and 255");
}
double dRed = (double) red / 255;
@@ -172,7 +115,7 @@ public static double[] rgbToHsv(int red, int green, int blue) {
hue = (hue + 360) % 360;
- return new double[] { hue, saturation, value };
+ return new double[] {hue, saturation, value};
}
private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
@@ -184,11 +127,7 @@ private static boolean approximatelyEqualHsv(double[] hsv1, double[] hsv2) {
}
private static int[] getRgbBySection(
- double hueSection,
- double chroma,
- double matchValue,
- double secondLargestComponent
- ) {
+ double hueSection, double chroma, double matchValue, double secondLargestComponent) {
int red;
int green;
int blue;
@@ -219,7 +158,7 @@ private static int[] getRgbBySection(
blue = convertToInt(secondLargestComponent + matchValue);
}
- return new int[] { red, green, blue };
+ return new int[] {red, green, blue};
}
private static int convertToInt(double input) {
diff --git a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
index 81c8d9bd1f3c..39e0c4438a6e 100644
--- a/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
+++ b/src/main/java/com/thealgorithms/conversions/TurkishToLatinConversion.java
@@ -58,11 +58,8 @@ public static String convertTurkishToLatin(String param) {
'G',
};
for (int i = 0; i < turkishChars.length; i++) {
- param =
- param.replaceAll(
- new String(new char[] { turkishChars[i] }),
- new String(new char[] { latinChars[i] })
- );
+ param = param.replaceAll(
+ new String(new char[] {turkishChars[i]}), new String(new char[] {latinChars[i]}));
}
return param;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
index 96c72fc04d6a..5e1c815ff9b3 100644
--- a/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
+++ b/src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
@@ -9,7 +9,7 @@ public class CircularBuffer- {
private final AtomicInteger size = new AtomicInteger(0);
public CircularBuffer(int size) {
- //noinspection unchecked
+ // noinspection unchecked
this.buffer = (Item[]) new Object[size];
this.putPointer = new CircularPointer(0, size);
this.getPointer = new CircularPointer(0, size);
@@ -24,8 +24,7 @@ public boolean isFull() {
}
public Item get() {
- if (isEmpty())
- return null;
+ if (isEmpty()) return null;
Item item = buffer[getPointer.getAndIncrement()];
size.decrementAndGet();
@@ -33,8 +32,7 @@ public Item get() {
}
public boolean put(Item item) {
- if (isFull())
- return false;
+ if (isFull()) return false;
buffer[putPointer.getAndIncrement()] = item;
size.incrementAndGet();
@@ -51,8 +49,7 @@ public CircularPointer(int pointer, int max) {
}
public int getAndIncrement() {
- if (pointer == max)
- pointer = 0;
+ if (pointer == max) pointer = 0;
int tmp = pointer;
pointer++;
return tmp;
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
index de1f6af64de0..03a1d59e1b20 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
@@ -43,7 +43,8 @@ public LFUCache(Integer capacity) {
* This method returns value present in the cache corresponding to the key passed as parameter
*
* @param key for which value is to be retrieved
- * @returns object corresponding to the key passed as parameter, returns null if key is not present in the cache
+ * @returns object corresponding to the key passed as parameter, returns null if key is
+ * not present in the cache
*/
public V get(K key) {
if (this.map.get(key) == null) {
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
index 976a4fef1c29..fcb7d975bdb4 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
@@ -126,14 +126,10 @@ static final class Entry {
private I key;
private J value;
- public Entry() {}
-
- public Entry(
- Entry preEntry,
- Entry nextEntry,
- I key,
- J value
- ) {
+ public Entry() {
+ }
+
+ public Entry(Entry preEntry, Entry nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
index fc55c4e4d730..30f914968c3b 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
@@ -124,14 +124,10 @@ static final class Entry {
private I key;
private J value;
- public Entry() {}
-
- public Entry(
- Entry preEntry,
- Entry nextEntry,
- I key,
- J value
- ) {
+ public Entry() {
+ }
+
+ public Entry(Entry preEntry, Entry nextEntry, I key, J value) {
this.preEntry = preEntry;
this.nextEntry = nextEntry;
this.key = key;
diff --git a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
index 1b6dd0c5470f..fb7783575e57 100644
--- a/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
+++ b/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
@@ -44,8 +44,7 @@ public DynamicArray() {
*/
public void add(final E element) {
if (this.size == this.elements.length) {
- this.elements =
- Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
+ this.elements = Arrays.copyOf(this.elements, newCapacity(2 * this.capacity));
}
this.elements[this.size] = element;
@@ -84,8 +83,7 @@ public E remove(final int index) {
fastRemove(this.elements, index);
if (this.capacity > DEFAULT_CAPACITY && size * 4 <= this.capacity) {
- this.elements =
- Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
+ this.elements = Arrays.copyOf(this.elements, newCapacity(this.capacity / 2));
}
return oldElement;
}
@@ -116,13 +114,7 @@ private void fastRemove(final Object[] elements, final int index) {
final int newSize = this.size - 1;
if (newSize > index) {
- System.arraycopy(
- elements,
- index + 1,
- elements,
- index,
- newSize - index
- );
+ System.arraycopy(elements, index + 1, elements, index, newSize - index);
}
elements[this.size = newSize] = null;
@@ -144,9 +136,7 @@ private int newCapacity(int capacity) {
*/
@Override
public String toString() {
- return Arrays.toString(
- Arrays.stream(this.elements).filter(Objects::nonNull).toArray()
- );
+ return Arrays.toString(Arrays.stream(this.elements).filter(Objects::nonNull).toArray());
}
/**
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
index fe01cecde42e..ea75e067f949 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/A_Star.java
@@ -1,5 +1,5 @@
/*
- Time Complexity = O(E), where E is equal to the number of edges
+ Time Complexity = O(E), where E is equal to the number of edges
*/
package com.thealgorithms.datastructures.graphs;
@@ -64,13 +64,10 @@ private static class PathAndDistance {
private int distance; // distance advanced so far.
private ArrayList path; // list of visited nodes in this path.
- private int estimated; // heuristic value associated to the last node od the path (current node).
+ private int
+ estimated; // heuristic value associated to the last node od the path (current node).
- public PathAndDistance(
- int distance,
- ArrayList path,
- int estimated
- ) {
+ public PathAndDistance(int distance, ArrayList path, int estimated) {
this.distance = distance;
this.path = path;
this.estimated = estimated;
@@ -90,25 +87,16 @@ public int getEstimated() {
private void printSolution() {
if (this.path != null) {
- System.out.println(
- "Optimal path: " +
- this.path +
- ", distance: " +
- this.distance
- );
+ System.out.println("Optimal path: " + this.path + ", distance: " + this.distance);
} else {
- System.out.println(
- "There is no path available to connect the points"
- );
+ System.out.println("There is no path available to connect the points");
}
}
}
private static void initializeGraph(Graph graph, ArrayList data) {
for (int i = 0; i < data.size(); i += 4) {
- graph.addEdge(
- new Edge(data.get(i), data.get(i + 1), data.get(i + 2))
- );
+ graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2)));
}
/*
.x. node
@@ -165,123 +153,24 @@ public static void main(String[] args) {
};
Graph graph = new Graph(20);
- ArrayList graphData = new ArrayList<>(
- Arrays.asList(
- 0,
- 19,
- 75,
- null,
- 0,
- 15,
- 140,
- null,
- 0,
- 16,
- 118,
- null,
- 19,
- 12,
- 71,
- null,
- 12,
- 15,
- 151,
- null,
- 16,
- 9,
- 111,
- null,
- 9,
- 10,
- 70,
- null,
- 10,
- 3,
- 75,
- null,
- 3,
- 2,
- 120,
- null,
- 2,
- 14,
- 146,
- null,
- 2,
- 13,
- 138,
- null,
- 2,
- 6,
- 115,
- null,
- 15,
- 14,
- 80,
- null,
- 15,
- 5,
- 99,
- null,
- 14,
- 13,
- 97,
- null,
- 5,
- 1,
- 211,
- null,
- 13,
- 1,
- 101,
- null,
- 6,
- 1,
- 160,
- null,
- 1,
- 17,
- 85,
- null,
- 17,
- 7,
- 98,
- null,
- 7,
- 4,
- 86,
- null,
- 17,
- 18,
- 142,
- null,
- 18,
- 8,
- 92,
- null,
- 8,
- 11,
- 87
- )
- );
+ ArrayList graphData = new ArrayList<>(Arrays.asList(0, 19, 75, null, 0, 15, 140,
+ null, 0, 16, 118, null, 19, 12, 71, null, 12, 15, 151, null, 16, 9, 111, null, 9, 10,
+ 70, null, 10, 3, 75, null, 3, 2, 120, null, 2, 14, 146, null, 2, 13, 138, null, 2, 6,
+ 115, null, 15, 14, 80, null, 15, 5, 99, null, 14, 13, 97, null, 5, 1, 211, null, 13, 1,
+ 101, null, 6, 1, 160, null, 1, 17, 85, null, 17, 7, 98, null, 7, 4, 86, null, 17, 18,
+ 142, null, 18, 8, 92, null, 8, 11, 87));
initializeGraph(graph, graphData);
PathAndDistance solution = aStar(3, 1, graph, heuristic);
solution.printSolution();
}
- public static PathAndDistance aStar(
- int from,
- int to,
- Graph graph,
- int[] heuristic
- ) {
+ public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) {
// nodes are prioritised by the less value of the current distance of their paths, and the
// estimated value
// given by the heuristic function to reach the destination point from the current point.
PriorityQueue queue = new PriorityQueue<>(
- Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))
- );
+ Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated())));
// dummy data to start the algorithm from the beginning point
queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), 0));
@@ -290,34 +179,25 @@ public static PathAndDistance aStar(
PathAndDistance currentData = new PathAndDistance(-1, null, -1);
while (!queue.isEmpty() && !solutionFound) {
currentData = queue.poll(); // first in the queue, best node so keep exploring.
- int currentPosition = currentData
- .getPath()
- .get(currentData.getPath().size() - 1); // current node.
+ int currentPosition
+ = currentData.getPath().get(currentData.getPath().size() - 1); // current node.
if (currentPosition == to) {
solutionFound = true;
} else {
for (Edge edge : graph.getNeighbours(currentPosition)) {
if (!currentData.getPath().contains(edge.getTo())) { // Avoid Cycles
- ArrayList updatedPath = new ArrayList<>(
- currentData.getPath()
- );
- updatedPath.add(edge.getTo()); // Add the new node to the path, update the distance,
+ ArrayList updatedPath = new ArrayList<>(currentData.getPath());
+ updatedPath.add(
+ edge.getTo()); // Add the new node to the path, update the distance,
// and the heuristic function value associated to that path.
- queue.add(
- new PathAndDistance(
- currentData.getDistance() + edge.getWeight(),
- updatedPath,
- heuristic[edge.getTo()]
- )
- );
+ queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(),
+ updatedPath, heuristic[edge.getTo()]));
}
}
}
}
- return (solutionFound)
- ? currentData
- : new PathAndDistance(-1, null, -1);
- // Out of while loop, if there is a solution, the current Data stores the optimal path, and its
- // distance
+ return (solutionFound) ? currentData : new PathAndDistance(-1, null, -1);
+ // Out of while loop, if there is a solution, the current Data stores the optimal path, and
+ // its distance
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
index aba377329aa0..2998f7e90b52 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
@@ -2,8 +2,10 @@
import java.util.*;
-class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs in form of edges which have
-start vertex, end vertex and weights. Vertices should be labelled with a number between 0 and total number of vertices-1,both inclusive*/{
+class BellmanFord /*Implementation of Bellman ford to detect negative cycles. Graph accepts inputs
+in form of edges which have start vertex, end vertex and weights. Vertices should be labelled with a
+number between 0 and total number of vertices-1,both inclusive*/
+{
int vertex, edge;
private Edge[] edges;
@@ -49,7 +51,8 @@ public static void main(String[] args) {
obj.go();
}
- public void go() { // shows distance to all vertices // Interactive run for understanding the class first time. Assumes source vertex is 0 and
+ public void go() { // shows distance to all vertices // Interactive run for understanding the
+ // class first time. Assumes source vertex is 0 and
Scanner sc = new Scanner(System.in); // Grab scanner object for user input
int i, v, e, u, ve, w, j, neg = 0;
System.out.println("Enter no. of vertices and edges please");
@@ -63,7 +66,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde
w = sc.nextInt();
arr[i] = new Edge(u, ve, w);
}
- int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance between source
+ int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance
+ // between source
// and all vertices
int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
@@ -73,10 +77,8 @@ public void go() { // shows distance to all vertices // Interactive run for unde
p[0] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
- if (
- dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if (dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@@ -84,10 +86,7 @@ public void go() { // shows distance to all vertices // Interactive run for unde
}
// Final cycle for negative checking
for (j = 0; j < e; j++) {
- if (
- dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
@@ -113,9 +112,13 @@ public void go() { // shows distance to all vertices // Interactive run for unde
* @param end Ending vertex
* @param Edge Array of edges
*/
- public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() method // Just shows results of computation, if graph is passed to it. The graph should
+ public void show(int source, int end,
+ Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray()
+ // method // Just shows results of computation, if graph is passed to it. The
+ // graph should
int i, j, v = vertex, e = edge, neg = 0;
- double[] dist = new double[v]; // Distance array for holding the finalized shortest path distance between source
+ double[] dist = new double[v]; // Distance array for holding the finalized shortest path
+ // distance between source
// and all vertices
int[] p = new int[v]; // Parent array for holding the paths
for (i = 0; i < v; i++) {
@@ -125,10 +128,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd
p[source] = -1;
for (i = 0; i < v - 1; i++) {
for (j = 0; j < e; j++) {
- if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if ((int) dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update
p[arr[j].v] = arr[j].u;
}
@@ -136,10 +137,8 @@ public void show(int source, int end, Edge[] arr) { // be created by using addEd
}
// Final cycle for negative checking
for (j = 0; j < e; j++) {
- if (
- (int) dist[arr[j].u] != Integer.MAX_VALUE &&
- dist[arr[j].v] > dist[arr[j].u] + arr[j].w
- ) {
+ if ((int) dist[arr[j].u] != Integer.MAX_VALUE
+ && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) {
neg = 1;
System.out.println("Negative cycle");
break;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
index 651b3e617794..0bdc5340f897 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGrapfDFS.java
@@ -17,11 +17,7 @@
public class BipartiteGrapfDFS {
private static boolean bipartite(
- int V,
- ArrayList> adj,
- int[] color,
- int node
- ) {
+ int V, ArrayList> adj, int[] color, int node) {
if (color[node] == -1) {
color[node] = 1;
}
@@ -38,10 +34,7 @@ private static boolean bipartite(
return true;
}
- public static boolean isBipartite(
- int V,
- ArrayList> adj
- ) {
+ public static boolean isBipartite(int V, ArrayList> adj) {
// Code here
int[] color = new int[V + 1];
Arrays.fill(color, -1);
@@ -57,9 +50,7 @@ public static boolean isBipartite(
}
public static void main(String[] args) throws IOException {
- BufferedReader read = new BufferedReader(
- new InputStreamReader(System.in)
- );
+ BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(read.readLine().trim());
while (t-- > 0) {
String[] S = read.readLine().trim().split(" ");
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
index 306abd7e39df..b0add255f59a 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
@@ -137,11 +137,7 @@ public static void main(String[] args) {
graphInts.addEdge(8, 10);
graphInts.addEdge(10, 8);
- System.out.println(
- "Amount of different char-graphs: " + graphChars.countGraphs()
- );
- System.out.println(
- "Amount of different int-graphs: " + graphInts.countGraphs()
- );
+ System.out.println("Amount of different char-graphs: " + graphChars.countGraphs());
+ System.out.println("Amount of different int-graphs: " + graphInts.countGraphs());
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
index 3d6e8a51ebd6..5d5bd3c7469c 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
@@ -24,9 +24,7 @@ public Cycle() {
visited[i] = false;
}
- System.out.println(
- "Enter the details of each edges "
- );
+ System.out.println("Enter the details of each edges ");
for (int i = 0; i < edges; i++) {
int start, end;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
index 31ed7ef2de2a..1811d4a109ca 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DIJSKSTRAS_ALGORITHM.java
@@ -1,6 +1,6 @@
/*
Refer https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/
-for better understanding
+for better understanding
*/
package com.thealgorithms.datastructures.graphs;
@@ -45,12 +45,8 @@ void dijkstra(int[][] graph, int src) {
Set[u] = true;
for (int v = 0; v < k; v++) {
- if (
- !Set[v] &&
- graph[u][v] != 0 &&
- dist[u] != Integer.MAX_VALUE &&
- dist[u] + graph[u][v] < dist[v]
- ) {
+ if (!Set[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE
+ && dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
@@ -61,23 +57,23 @@ void dijkstra(int[][] graph, int src) {
public static void main(String[] args) {
int[][] graph = new int[][] {
- { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
- { 4, 0, 8, 0, 0, 0, 0, 11, 0 },
- { 0, 8, 0, 7, 0, 4, 0, 0, 2 },
- { 0, 0, 7, 0, 9, 14, 0, 0, 0 },
- { 0, 0, 0, 9, 0, 10, 0, 0, 0 },
- { 0, 0, 4, 14, 10, 0, 2, 0, 0 },
- { 0, 0, 0, 0, 0, 2, 0, 1, 6 },
- { 8, 11, 0, 0, 0, 0, 1, 0, 7 },
- { 0, 0, 2, 0, 0, 0, 6, 7, 0 },
+ {0, 4, 0, 0, 0, 0, 0, 8, 0},
+ {4, 0, 8, 0, 0, 0, 0, 11, 0},
+ {0, 8, 0, 7, 0, 4, 0, 0, 2},
+ {0, 0, 7, 0, 9, 14, 0, 0, 0},
+ {0, 0, 0, 9, 0, 10, 0, 0, 0},
+ {0, 0, 4, 14, 10, 0, 2, 0, 0},
+ {0, 0, 0, 0, 0, 2, 0, 1, 6},
+ {8, 11, 0, 0, 0, 0, 1, 0, 7},
+ {0, 0, 2, 0, 0, 0, 6, 7, 0},
};
dijkstras t = new dijkstras();
t.dijkstra(graph, 0);
- } //main
-} //djikstras
+ } // main
+} // djikstras
/*
OUTPUT :
-Vertex Distance
+Vertex Distance
0 0
1 4
2 12
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
index bf3ef8e6eab9..673b795b1563 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
@@ -9,42 +9,32 @@ public class FloydWarshall {
public static final int INFINITY = 999;
public FloydWarshall(int numberofvertices) {
- DistanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // stores the value of distance from all the possible path form the source
+ DistanceMatrix = new int[numberofvertices + 1][numberofvertices
+ + 1]; // stores the value of distance from all the possible path form the source
// vertex to destination vertex
// The matrix is initialized with 0's by default
this.numberofvertices = numberofvertices;
}
- public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
+ public void floydwarshall(
+ int[][] AdjacencyMatrix) { // calculates all the distances from source to destination vertex
for (int source = 1; source <= numberofvertices; source++) {
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
- DistanceMatrix[source][destination] =
- AdjacencyMatrix[source][destination];
+ for (int destination = 1; destination <= numberofvertices; destination++) {
+ DistanceMatrix[source][destination] = AdjacencyMatrix[source][destination];
}
}
- for (
- int intermediate = 1;
- intermediate <= numberofvertices;
- intermediate++
- ) {
+ for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) {
for (int source = 1; source <= numberofvertices; source++) {
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
- if (
- DistanceMatrix[source][intermediate] +
- DistanceMatrix[intermediate][destination] <
- DistanceMatrix[source][destination]
- ) { // calculated distance it get replaced as new shortest distance // if the new distance calculated is less then the earlier shortest
- DistanceMatrix[source][destination] =
- DistanceMatrix[source][intermediate] +
- DistanceMatrix[intermediate][destination];
+ for (int destination = 1; destination <= numberofvertices; destination++) {
+ if (DistanceMatrix[source][intermediate]
+ + DistanceMatrix[intermediate][destination]
+ < DistanceMatrix[source]
+ [destination]) { // calculated distance it get replaced as
+ // new shortest distance // if the new
+ // distance calculated is less then the
+ // earlier shortest
+ DistanceMatrix[source][destination] = DistanceMatrix[source][intermediate]
+ + DistanceMatrix[intermediate][destination];
}
}
}
@@ -55,11 +45,7 @@ public void floydwarshall(int[][] AdjacencyMatrix) { // calculates all the dista
System.out.println();
for (int source = 1; source <= numberofvertices; source++) {
System.out.print(source + "\t");
- for (
- int destination = 1;
- destination <= numberofvertices;
- destination++
- ) {
+ for (int destination = 1; destination <= numberofvertices; destination++) {
System.out.print(DistanceMatrix[source][destination] + "\t");
}
System.out.println();
@@ -70,15 +56,10 @@ public static void main(String... arg) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int numberOfVertices = scan.nextInt();
- int[][] adjacencyMatrix = new int[numberOfVertices +
- 1][numberOfVertices + 1];
+ int[][] adjacencyMatrix = new int[numberOfVertices + 1][numberOfVertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int source = 1; source <= numberOfVertices; source++) {
- for (
- int destination = 1;
- destination <= numberOfVertices;
- destination++
- ) {
+ for (int destination = 1; destination <= numberOfVertices; destination++) {
adjacencyMatrix[source][destination] = scan.nextInt();
if (source == destination) {
adjacencyMatrix[source][destination] = 0;
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
index 1430f1a246dd..d4d6a381e89e 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
@@ -21,7 +21,7 @@ public int[] findHamiltonianCycle(int[][] graph) {
this.V = graph.length;
this.cycle = new int[this.V + 1];
- //Initialize path array with -1 value
+ // Initialize path array with -1 value
for (int i = 0; i < this.cycle.length; i++) {
this.cycle[i] = -1;
}
@@ -41,13 +41,15 @@ public int[] findHamiltonianCycle(int[][] graph) {
return cycle;
}
- /** function to find paths recursively
+ /**
+ * function to find paths recursively
* Find paths recursively from given vertex
* @param vertex Vertex from which path is to be found
* @returns true if path is found false otherwise
*/
public boolean isPathFound(int vertex) {
- boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.V;
+ boolean isLastVertexConnectedToStart
+ = this.graph[vertex][0] == 1 && this.pathCount == this.V;
if (isLastVertexConnectedToStart) {
return true;
}
@@ -83,7 +85,8 @@ public boolean isPathFound(int vertex) {
return false;
}
- /** function to check if path is already selected
+ /**
+ * function to check if path is already selected
* Check if path is already selected
* @param vertex Starting vertex
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
index 350d7d270b2e..e978ddc1e764 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
@@ -133,7 +133,7 @@ ArrayList topSortOrder() {
public class KahnsAlgorithm {
public static void main(String[] args) {
- //Graph definition and initialization
+ // Graph definition and initialization
AdjacencyList graph = new AdjacencyList<>();
graph.addEdge("a", "b");
graph.addEdge("c", "a");
@@ -144,7 +144,7 @@ public static void main(String[] args) {
TopologicalSort topSort = new TopologicalSort<>(graph);
- //Printing the order
+ // Printing the order
for (String s : topSort.topSortOrder()) {
System.out.print(s + " ");
}
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
index f24791dce596..c24046f510af 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
@@ -7,17 +7,18 @@
/**
* Java program that implements Kosaraju Algorithm.
* @author Shivanagouda S A (https://github.com/shivu2002a)
- *
+ *
*/
/**
- * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
- directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the transpose
- graph (same graph with all the edges reversed) has exactly the same SCCs as the original graph.
-
- * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
- The SCCs of a directed graph form a partition into subgraphs that are themselves strongly connected.
- Single node is always a SCC.
+ * Kosaraju algorithm is a linear time algorithm to find the strongly connected components of a
+ directed graph, which, from here onwards will be referred by SCC. It leverages the fact that the
+ transpose graph (same graph with all the edges reversed) has exactly the same SCCs as the original
+ graph.
+
+ * A graph is said to be strongly connected if every vertex is reachable from every other vertex.
+ The SCCs of a directed graph form a partition into subgraphs that are themselves strongly
+ connected. Single node is always a SCC.
* Example:
@@ -26,19 +27,20 @@
| / | \ /
| / | \ /
v / v \ /
- 1 5 --> 6
+ 1 5 --> 6
For the above graph, the SCC list goes as follows:
- 0, 1, 2
+ 0, 1, 2
3
4, 5, 6
7
-
+
We can also see that order of the nodes in an SCC doesn't matter since they are in cycle.
{@summary}
- * Kosaraju Algorithm:
- 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges sorted by lowest finish time.
+ * Kosaraju Algorithm:
+ 1. Perform DFS traversal of the graph. Push node to stack before returning. This gives edges
+ sorted by lowest finish time.
2. Find the transpose graph by reversing the edges.
3. Pop nodes one by one from the stack and again to DFS on the modified graph.
@@ -48,7 +50,7 @@
| / | \ /
| / | \ /
| v | v v
- 1 5 <--- 6
+ 1 5 <--- 6
We can observe that this graph has the same SCC as that of original graph.
@@ -59,33 +61,33 @@ public class Kosaraju {
// Sort edges according to lowest finish time
Stack stack = new Stack();
- //Store each component
+ // Store each component
private List scc = new ArrayList<>();
- //All the strongly connected components
+ // All the strongly connected components
private List
> sccsList = new ArrayList<>();
/**
- *
+ *
* @param v Node count
* @param list Adjacency list of graph
* @return List of SCCs
*/
- public List> kosaraju(int v, List> list){
-
+ public List> kosaraju(int v, List> list) {
+
sortEdgesByLowestFinishTime(v, list);
-
+
List> transposeGraph = createTransposeMatrix(v, list);
findStronglyConnectedComponents(v, transposeGraph);
-
+
return sccsList;
}
- private void sortEdgesByLowestFinishTime(int v, List> list){
+ private void sortEdgesByLowestFinishTime(int v, List> list) {
int[] vis = new int[v];
for (int i = 0; i < v; i++) {
- if(vis[i] == 0){
+ if (vis[i] == 0) {
dfs(i, vis, list);
}
}
@@ -105,15 +107,15 @@ private List> createTransposeMatrix(int v, List> lis
}
/**
- *
+ *
* @param v Node count
* @param transposeGraph Transpose of the given adjacency list
*/
- public void findStronglyConnectedComponents(int v, List> transposeGraph){
+ public void findStronglyConnectedComponents(int v, List> transposeGraph) {
int[] vis = new int[v];
while (!stack.isEmpty()) {
var node = stack.pop();
- if(vis[node] == 0){
+ if (vis[node] == 0) {
dfs2(node, vis, transposeGraph);
sccsList.add(scc);
scc = new ArrayList<>();
@@ -121,24 +123,21 @@ public void findStronglyConnectedComponents(int v, List> transpose
}
}
- //Dfs to store the nodes in order of lowest finish time
- private void dfs(int node, int[] vis, List