From 7216f28cb318b32eedf420d2fb6274254dd671ff Mon Sep 17 00:00:00 2001 From: DDullahan Date: Mon, 8 Apr 2019 08:57:34 +0800 Subject: [PATCH 01/19] Added FastPower Added FastPower --- src/main/java/com/Others/FastPower.java | 37 +++++++++++++++++++ src/main/java/com/Others/FastPowerTest.java | 40 +++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 src/main/java/com/Others/FastPower.java create mode 100644 src/main/java/com/Others/FastPowerTest.java diff --git a/src/main/java/com/Others/FastPower.java b/src/main/java/com/Others/FastPower.java new file mode 100644 index 00000000..003f1d65 --- /dev/null +++ b/src/main/java/com/Others/FastPower.java @@ -0,0 +1,37 @@ +package src.main.java.com.Others; + +import java.math.BigInteger; + +/** + * We may calculate power with loops, but what if the index is too large ? + * FastPower aims to calculate quickly in this circumstances with time complexity O(log k), + * where k is the index. + * + * @author DDullahan + */ +public class FastPower { + public static BigInteger calculate(BigInteger n, BigInteger k, BigInteger mod) { + BigInteger ans = BigInteger.ONE; + while (!k.equals(BigInteger.ZERO)) { + int odd = k.mod(new BigInteger("2")).compareTo(BigInteger.ZERO); + if(odd == 1){ + ans = ans.multiply(n).mod(mod); + } + k = k.divide(new BigInteger("2")); + n = n.multiply(n).mod(mod); + } + return ans.mod(mod); + } + + public static long calculate(long n, long k, long mod) { + long ans = 1; + while (k != 0) { + if (k % 2 == 1) { + ans = (ans * n) % mod; + } + k >>= 1; + n = (n * n) % mod; + } + return ans % mod; + } +} diff --git a/src/main/java/com/Others/FastPowerTest.java b/src/main/java/com/Others/FastPowerTest.java new file mode 100644 index 00000000..b071c4e4 --- /dev/null +++ b/src/main/java/com/Others/FastPowerTest.java @@ -0,0 +1,40 @@ +package src.main.java.com.Others; + +import org.junit.*; + +import java.math.BigInteger; + +import static org.junit.Assert.*; + +public class FastPowerTest { + + @Test + public void test() { + System.out.println("Long Type:"); + long result; + result = FastPower.calculate(2, 2, 10); + assertEquals(result, 4); + System.out.println("The result of power(2,2) mod 10 is " + result); + + result = FastPower.calculate(100, 1000, 20); + assertEquals(result, 0); + System.out.println("The result of power(100, 1000) mod 20 is " + result); + + result = FastPower.calculate(123456, 123456789, 234); + System.out.println("The result of power(123456, 123456789) mod 234 is " + result); + + + System.out.println("BigInteger Type:"); + BigInteger bigResult; + bigResult = FastPower.calculate(BigInteger.TEN, BigInteger.TEN, new BigInteger("4")); + assertEquals(bigResult, BigInteger.ZERO); + System.out.println("The bigResult of power(10, 10) mod 4 is " + bigResult); + + bigResult = FastPower.calculate(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); + System.out.println("The bigResult of power(123456, 123456789) mod 234 is " + bigResult); + + bigResult = FastPower.calculate(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); + System.out.println("The bigResult of power(123456789101112, 12345678910111213) mod 567890 is " + bigResult); + + } +} \ No newline at end of file From 91c19921ef99ada3cf676afa861bef9483eec0d6 Mon Sep 17 00:00:00 2001 From: nbdgit Date: Sun, 14 Apr 2019 16:55:05 +0530 Subject: [PATCH 02/19] Commit BinaryToGray --- .../java/com/conversions/BinaryToGray.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/java/com/conversions/BinaryToGray.java diff --git a/src/main/java/com/conversions/BinaryToGray.java b/src/main/java/com/conversions/BinaryToGray.java new file mode 100644 index 00000000..7b14c2a1 --- /dev/null +++ b/src/main/java/com/conversions/BinaryToGray.java @@ -0,0 +1,30 @@ +package src.main.java.com.conversions; + +public class BinaryToGray +{ + /* This method convert the binary number into gray code + @param binaryno need to convert binary number into gray code + @return graycode return as string + */ + + public String binaryToGray(String binarycode) + { + + String graycode=Character.toString(binarycode.charAt(0)); + + + for(int i=0;i Date: Sun, 14 Apr 2019 16:56:52 +0530 Subject: [PATCH 03/19] Commit BinaryToGrayTest --- .../com/conversions/BinaryToGrayTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/test/java/com/conversions/BinaryToGrayTest.java diff --git a/src/test/java/com/conversions/BinaryToGrayTest.java b/src/test/java/com/conversions/BinaryToGrayTest.java new file mode 100644 index 00000000..25ededee --- /dev/null +++ b/src/test/java/com/conversions/BinaryToGrayTest.java @@ -0,0 +1,19 @@ +package src.test.java.com.conversions; + +import src.main.java.com.conversions.BinaryToGray; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class BinaryToGrayTest +{ + + + @Test + public void testBinaryToGray() + { + BinaryToGray btog=new BinaryToGray(); + assertEquals("1101",btog.binaryToGray("1001")); + assertEquals("11010011101",btog.binaryToGray("10011101001")); + } + +} From 6938c409f95d85157ffdc716ce3cf4216ca403cf Mon Sep 17 00:00:00 2001 From: Abir Bhushan Date: Mon, 15 Apr 2019 11:14:22 +0100 Subject: [PATCH 04/19] Create DepthFirstSearch.java --- .../java/com/search/DepthFirstSearch.java | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 src/main/java/com/search/DepthFirstSearch.java diff --git a/src/main/java/com/search/DepthFirstSearch.java b/src/main/java/com/search/DepthFirstSearch.java new file mode 100644 index 00000000..fe16e421 --- /dev/null +++ b/src/main/java/com/search/DepthFirstSearch.java @@ -0,0 +1,126 @@ +package src.main.java.com.search; + +/** + * Searching is faster in sorted structures. Binary search is O(log n). + * However, the cost of sorting is O(n · log n). + * What to do when adding or removing elements? Sort again? No. + * Create efficient data structures to maintain sorted sequences, and search in them + * Key example: binary sorted tree, allowing O(log N) insert, remove and lookup. + + In comes, depth-first search + * Worst-case performance O(n) + * Best-case performance O(1) + * Average performance O(n) + * + * @author abir (https://github.com/abircb) + */ + +public class DepthFirstSearch { + + /** + * Depth-first search method + * + * @param tree- Binary tree to be searched + * @param value- Key being searched for + * @return Location of the key + */ + + public static > T find(T key, BinaryTree tree) { + return tree.get(key); + } + +} + +/** + * The BinaryTree class defines the structure of a binary tree + * Also contains a static nested class called TreeNode + * @param + * @author abir + */ +class BinaryTree> { + + private TreeNode root; + + /** + * @author abir + * @param

+ * This class defines what a node in a binary tree looks like + */ + private static class TreeNode

> { + + P key, value; + TreeNode

left, right; + + private TreeNode(P key, P value) { + this.key = key; + this.value = value; + this.left = null; + this.right = null; + } + + /** + * @param node + * adds the specified node + */ + private void add(TreeNode

node) { + if (node.key.compareTo(this.key) < 0) { + if(this.left == null) { + this.left = node; + } + else { + this.left.add(node); + } + } + + else { + if(this.right == null) { + this.right = node; + } + else { + this.right.add(node); + } + } + } + + /** + * @param key + * @return the tree node corresponding to the key + */ + private TreeNode

find(P key) { + if(key.compareTo(this.key) == 0) return this; + + else if(key.compareTo(this.key) < 0) { + if(this.left == null) return null; + else return this.left.find(key); + } + + else { + if(this.right == null) return null; + else return this.right.find(key); + } + } + + } + + public BinaryTree() { + this.root = null; + } + + public void add(T key, T value) { + TreeNode node = new TreeNode(key, value); + if(this.root == null) { + this.root = node; + } + else { + this.root.add(node); + } + } + + public T get(T key) { + if(this.root == null) return null; + + TreeNode node = this.root.find(key); + if(node == null) return null; + return node.value; + } +} From 4d9965cb945d59c5582e1f9cdfc7f59627638beb Mon Sep 17 00:00:00 2001 From: Abir Bhushan Date: Mon, 15 Apr 2019 11:38:59 +0100 Subject: [PATCH 05/19] Create DepthFirstSearchTest.java this test is created for the DepthFirstSearch.java file- that I added- containing the DepthFirstSearch algorithm --- .../java/com/search/DepthFirstSearchTest.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/test/java/com/search/DepthFirstSearchTest.java diff --git a/src/test/java/com/search/DepthFirstSearchTest.java b/src/test/java/com/search/DepthFirstSearchTest.java new file mode 100644 index 00000000..859abfb1 --- /dev/null +++ b/src/test/java/com/search/DepthFirstSearchTest.java @@ -0,0 +1,36 @@ +package src.test.java.com.search; + +import org.junit.Assert; +import org.junit.Test; +import src.main.java.com.search.DepthFirstSearch; +import src.main.java.com.search.BinaryTree; + +public class DepthFirstSearchTest { + @Test + public void testDepthFirstSearch() { + + BinaryTree tree1 = new BinaryTree(); + tree1.add(1,1); + tree1.add(2,2); + tree1.add(3,3); + tree1.add(4,4); + Assert.assertEquals("Incorrect index", 3, DepthFirstSearch.find(3, tree1)); + Assert.assertEquals("Incorrect index", 1, DepthFirstSearch.find(1, tree1)); + Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(0, tree1)); + Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(8, tree1)); + Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(-2, tree1)); + + BinaryTree tree2 = new BinaryTree(); + tree2.add("1","A"); + tree2.add("2","B"); + tree2.add("3","C"); + tree2.add("4","D"); + + Assert.assertEquals("Incorrect index", "C", LinearSearch.findIndex(tree2,"3")); + Assert.assertEquals("Incorrect index", "B", LinearSearch.findIndex(tree2,"2")); + Assert.assertEquals("Incorrect index", null, LinearSearch.findIndex(tree2,"F")); + + BinaryTree tree3 = new BinaryTree(); + Assert.assertEquals("Incorrect index", null, LinearSearch.findIndex(tree3, "")); + } +} From 785b570167f2016b2f49a9deb73106e70e264c87 Mon Sep 17 00:00:00 2001 From: Abir Bhushan Date: Tue, 16 Apr 2019 19:39:26 +0100 Subject: [PATCH 06/19] Update DepthFirstSearch.java --- src/main/java/com/search/DepthFirstSearch.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/search/DepthFirstSearch.java b/src/main/java/com/search/DepthFirstSearch.java index fe16e421..12ce4c11 100644 --- a/src/main/java/com/search/DepthFirstSearch.java +++ b/src/main/java/com/search/DepthFirstSearch.java @@ -10,7 +10,7 @@ package src.main.java.com.search; In comes, depth-first search * Worst-case performance O(n) * Best-case performance O(1) - * Average performance O(n) + * Average performance O(n) * * @author abir (https://github.com/abircb) */ @@ -26,8 +26,8 @@ public class DepthFirstSearch { */ public static > T find(T key, BinaryTree tree) { - return tree.get(key); - } + return tree.get(key); + } } From 230f04f6141565f242c6832ff752d93134a0ac52 Mon Sep 17 00:00:00 2001 From: Havan Agrawal Date: Fri, 3 May 2019 00:31:43 +0530 Subject: [PATCH 07/19] Apply suggestions from code review Co-Authored-By: nbdgit <48550673+nbdgit@users.noreply.github.com> --- src/main/java/com/conversions/BinaryToGray.java | 14 ++++++-------- .../java/com/conversions/BinaryToGrayTest.java | 5 ++--- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/conversions/BinaryToGray.java b/src/main/java/com/conversions/BinaryToGray.java index 7b14c2a1..cf44b82e 100644 --- a/src/main/java/com/conversions/BinaryToGray.java +++ b/src/main/java/com/conversions/BinaryToGray.java @@ -3,28 +3,26 @@ package src.main.java.com.conversions; public class BinaryToGray { /* This method convert the binary number into gray code - @param binaryno need to convert binary number into gray code + @param binarycode need to convert binary number into gray code @return graycode return as string */ public String binaryToGray(String binarycode) { - String graycode=Character.toString(binarycode.charAt(0)); - + String graycode = Character.toString(binarycode.charAt(0)); - for(int i=0;i Date: Fri, 3 May 2019 08:56:07 +0800 Subject: [PATCH 08/19] fixed problems of code review from @havanagrawal https://github.com/TheAlgorithms/Java/pull/731/files/7216f28cb318b32eedf420d2fb6274254dd671ff --- src/main/java/com/Others/FastPower.java | 6 ++-- src/main/java/com/Others/FastPowerTest.java | 40 +++++++++------------ 2 files changed, 19 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/Others/FastPower.java b/src/main/java/com/Others/FastPower.java index 003f1d65..8cc1b8b6 100644 --- a/src/main/java/com/Others/FastPower.java +++ b/src/main/java/com/Others/FastPower.java @@ -13,11 +13,11 @@ public class FastPower { public static BigInteger calculate(BigInteger n, BigInteger k, BigInteger mod) { BigInteger ans = BigInteger.ONE; while (!k.equals(BigInteger.ZERO)) { - int odd = k.mod(new BigInteger("2")).compareTo(BigInteger.ZERO); - if(odd == 1){ + int odd = k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO); + if(odd > 0){ ans = ans.multiply(n).mod(mod); } - k = k.divide(new BigInteger("2")); + k = k.divide(BigInteger.valueOf(2)); n = n.multiply(n).mod(mod); } return ans.mod(mod); diff --git a/src/main/java/com/Others/FastPowerTest.java b/src/main/java/com/Others/FastPowerTest.java index b071c4e4..bd61704b 100644 --- a/src/main/java/com/Others/FastPowerTest.java +++ b/src/main/java/com/Others/FastPowerTest.java @@ -8,33 +8,25 @@ import static org.junit.Assert.*; public class FastPowerTest { + void testLong(long n, long k, long m){ + long result = FastPower.calculate(n,k,m); + assertEquals(result, BigInteger.valueOf(n).modPow(BigInteger.valueOf(k), BigInteger.valueOf(m)).longValue()); + } + + void testBigInteger(BigInteger n, BigInteger k, BigInteger m){ + BigInteger result = FastPower.calculate(n,k,m); + assertEquals(result, n.modPow(k,m)); + } + @Test public void test() { - System.out.println("Long Type:"); - long result; - result = FastPower.calculate(2, 2, 10); - assertEquals(result, 4); - System.out.println("The result of power(2,2) mod 10 is " + result); + testLong(2,2,10); + testLong(100,1000,20); + testLong(123456,123456789,234); - result = FastPower.calculate(100, 1000, 20); - assertEquals(result, 0); - System.out.println("The result of power(100, 1000) mod 20 is " + result); - - result = FastPower.calculate(123456, 123456789, 234); - System.out.println("The result of power(123456, 123456789) mod 234 is " + result); - - - System.out.println("BigInteger Type:"); - BigInteger bigResult; - bigResult = FastPower.calculate(BigInteger.TEN, BigInteger.TEN, new BigInteger("4")); - assertEquals(bigResult, BigInteger.ZERO); - System.out.println("The bigResult of power(10, 10) mod 4 is " + bigResult); - - bigResult = FastPower.calculate(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); - System.out.println("The bigResult of power(123456, 123456789) mod 234 is " + bigResult); - - bigResult = FastPower.calculate(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); - System.out.println("The bigResult of power(123456789101112, 12345678910111213) mod 567890 is " + bigResult); + testBigInteger(BigInteger.TEN,BigInteger.TEN, BigInteger.valueOf(4)); + testBigInteger(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); + testBigInteger(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); } } \ No newline at end of file From f5754d3aefc5c1f7298addb17c02d64e9101d4a6 Mon Sep 17 00:00:00 2001 From: Nilanjan <48550673+nbdgit@users.noreply.github.com> Date: Fri, 3 May 2019 22:16:06 +0530 Subject: [PATCH 09/19] Add StringBuilder class --- src/main/java/com/conversions/BinaryToGray.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/conversions/BinaryToGray.java b/src/main/java/com/conversions/BinaryToGray.java index cf44b82e..1482b8d6 100644 --- a/src/main/java/com/conversions/BinaryToGray.java +++ b/src/main/java/com/conversions/BinaryToGray.java @@ -10,19 +10,19 @@ public class BinaryToGray public String binaryToGray(String binarycode) { - String graycode = Character.toString(binarycode.charAt(0)); + StringBuilder graycode = new StringBuilder(Character.toString(binarycode.charAt(0))); for(int i = 0; i < binarycode.length() - 1; i++) { if (binarycode.charAt(i) == binarycode.charAt(i+1)) - graycode = graycode + "0"; + graycode.append("0"); else - graycode = graycode + "1"; + graycode.append("1"); } - return graycode; + return graycode.toString(); } } From 46e52f43787026feb339270c0f2291492ded599b Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Thu, 9 May 2019 16:34:58 +0800 Subject: [PATCH 10/19] Update SimplexNoiseTest.java --- .../java/com/generation/SimplexNoiseTest.java | 67 +++++++++---------- 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/src/test/java/com/generation/SimplexNoiseTest.java b/src/test/java/com/generation/SimplexNoiseTest.java index a977e8e7..c50cf7b8 100644 --- a/src/test/java/com/generation/SimplexNoiseTest.java +++ b/src/test/java/com/generation/SimplexNoiseTest.java @@ -1,6 +1,5 @@ package src.test.java.com.generation; -import static org.junit.jupiter.api.Assertions.*; import java.awt.Color; import java.awt.image.BufferedImage; @@ -9,42 +8,42 @@ import java.io.InputStream; import javax.imageio.ImageIO; -import org.junit.jupiter.api.Test; +import org.junit.Assert; +import org.junit.Test; import src.main.java.com.generation.SimplexNoise; public class SimplexNoiseTest { - @Test - public void testGenerateHeightMap() { - - final int WIDTH = 256; - final int HEIGHT = 256; - final int X = 0; - final int Y = 0; - final String RESOURCE_NAME = "src/test/java/com/generation/expected-result.png"; - - float[][] heightmap = new SimplexNoise(50, 0.3F, 1111111111111111L).generateHeightMap(X, Y, WIDTH, HEIGHT); - BufferedImage image = null; - - try(InputStream in = this.getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) { - - image = ImageIO.read(in); - - assertEquals(WIDTH, image.getWidth()); - assertEquals(HEIGHT, image.getHeight()); - - } catch(IOException | IllegalArgumentException exception) { - - fail(exception); - } - - for(int x = 0; x < WIDTH; x++) { - - for(int y = 0; y < HEIGHT; y++) { - - assertEquals(new Color(image.getRGB(x, y)).getRed(), (int)(heightmap[x][y] * 255)); - } - } - } + @Test + public void testGenerateHeightMap() { + + final int WIDTH = 256; + final int HEIGHT = 256; + final int X = 0; + final int Y = 0; + final String RESOURCE_NAME = "src/test/java/com/generation/expected-result.png"; + + float[][] heightmap = new SimplexNoise(50, 0.3F, 1111111111111111L).generateHeightMap(X, Y, WIDTH, HEIGHT); + BufferedImage image = null; + + try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) { + + image = ImageIO.read(in); + + Assert.assertEquals(WIDTH, image.getWidth()); + Assert.assertEquals(HEIGHT, image.getHeight()); + + } catch (IOException | IllegalArgumentException exception) { + + } + + for (int x = 0; x < WIDTH; x++) { + + for (int y = 0; y < HEIGHT; y++) { + + Assert.assertEquals(new Color(image.getRGB(x, y)).getRed(), (int) (heightmap[x][y] * 255)); + } + } + } } From 60bb026f8ab64e2a1c16465492e04c9a4f6c3bdf Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Thu, 9 May 2019 20:33:46 +0800 Subject: [PATCH 11/19] Update ExponentialSearch.java --- src/main/java/com/search/ExponentialSearch.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/search/ExponentialSearch.java b/src/main/java/com/search/ExponentialSearch.java index e60940c4..0f30f090 100644 --- a/src/main/java/com/search/ExponentialSearch.java +++ b/src/main/java/com/search/ExponentialSearch.java @@ -20,9 +20,11 @@ public class ExponentialSearch { * @return The index position of the key in the array, returns -1 for empty array */ public > int findIndex(T[] array, T key) { - int size = array.length; - if(size == 0) + if (array == null || array.length == 0) { return -1; + } + int size = array.length; + // If the element is present at first position if (array[0] == key) return 0; @@ -30,10 +32,10 @@ public class ExponentialSearch { // Find the range for binary search by repeated doubling int i = 1; while (i < size && array[i].compareTo(key) <= 0) { - i = i * 2; + i <<= 1; } // Call binary search for the range found - return Arrays.binarySearch(array, i / 2, Math.min(i, size), key); + return Arrays.binarySearch(array, i >> 1, Math.min(i, size), key); } } From 8e8e14d1c2d0aa07df563ddd922ce682e70b88fd Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 10 May 2019 14:49:24 +0800 Subject: [PATCH 12/19] refactor: format code and fix typos --- .../com/conversions/AnyBaseToDecimal.java | 13 +- .../com/conversions/BinaryToHexadecimal.java | 2 +- .../com/conversions/DecimalToAnyBase.java | 14 +- .../com/conversions/DecimalToHexadecimal.java | 5 +- .../java/com/conversions/DecimalToOctal.java | 7 +- .../java/com/dataStructures/BinaryTree.java | 58 ++-- .../java/com/dataStructures/DisjointSet.java | 1 - .../java/com/generation/SimplexNoise.java | 251 +++++++++--------- .../com/generation/SimplexNoiseOctave.java | 2 +- .../matchings/stableMatching/GaleShapley.java | 6 +- src/main/java/com/search/BloomFilter.java | 1 - src/main/java/com/search/LinearSearch.java | 4 +- src/main/java/com/sorts/HeapSort.java | 189 +++++++------ src/main/java/com/sorts/MergeSort.java | 130 ++++----- src/main/java/com/sorts/QuickSort.java | 103 ++++--- src/main/java/com/sorts/SelectionSort.java | 44 +-- src/main/java/com/sorts/ShellSort.java | 42 +-- src/main/java/com/sorts/SortUtils.java | 76 +++--- src/main/java/com/sorts/StoogeSort.java | 50 ++-- src/main/java/com/types/Sort.java | 2 +- .../com/dataStructures/BinaryTreeTest.java | 40 ++- 21 files changed, 524 insertions(+), 516 deletions(-) diff --git a/src/main/java/com/conversions/AnyBaseToDecimal.java b/src/main/java/com/conversions/AnyBaseToDecimal.java index 4267e662..65f89f29 100644 --- a/src/main/java/com/conversions/AnyBaseToDecimal.java +++ b/src/main/java/com/conversions/AnyBaseToDecimal.java @@ -3,6 +3,7 @@ package src.main.java.com.conversions; public class AnyBaseToDecimal { /** * This method produces a decimal value of any given input number of any base + * * @param inpNum String of which we need the decimal value and base in integer format * @return string format of the decimal value */ @@ -12,11 +13,11 @@ public class AnyBaseToDecimal { int num = 0; int pow = 1; - for (int i=len-1; i>=0; i--) { + for (int i = len - 1; i >= 0; i--) { if (valOfChar(inpNum.charAt(i)) >= base) { return "Invalid Number"; } - num += valOfChar(inpNum.charAt(i))*pow; + num += valOfChar(inpNum.charAt(i)) * pow; pow *= base; } return String.valueOf(num); @@ -24,16 +25,16 @@ public class AnyBaseToDecimal { /** * This method produces integer value of the input character and returns it + * * @param c Char of which we need the integer value of * @return integer value of input char */ private static int valOfChar(char c) { if (c >= '0' && c <= '9') { - return (int)c - '0'; - } - else { - return (int)c - 'A' + 10; + return (int) c - '0'; + } else { + return (int) c - 'A' + 10; } } } \ No newline at end of file diff --git a/src/main/java/com/conversions/BinaryToHexadecimal.java b/src/main/java/com/conversions/BinaryToHexadecimal.java index 8497fa22..fc891570 100644 --- a/src/main/java/com/conversions/BinaryToHexadecimal.java +++ b/src/main/java/com/conversions/BinaryToHexadecimal.java @@ -11,7 +11,7 @@ public class BinaryToHexadecimal { * hm to store hexadecimal codes for binary numbers * within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15 */ - private static Map hmHexadecimal = new HashMap<>(16); + private static Map hmHexadecimal = new HashMap<>(16); static { int i; diff --git a/src/main/java/com/conversions/DecimalToAnyBase.java b/src/main/java/com/conversions/DecimalToAnyBase.java index ae675f23..912d423d 100644 --- a/src/main/java/com/conversions/DecimalToAnyBase.java +++ b/src/main/java/com/conversions/DecimalToAnyBase.java @@ -3,23 +3,24 @@ package src.main.java.com.conversions; import java.util.ArrayList; public class DecimalToAnyBase { + /** * This method produces a String value of any given input decimal in any base - * @param inp Decimal of which we need the value in base in String format + * + * @param inp Decimal of which we need the value in base in String format * @param base base in which we want the decimal value to be converted into * @return string format of the converted value in the given base */ - public String convertToAnyBase(int inp, int base) { ArrayList charArr = new ArrayList<>(); while (inp > 0) { - charArr.add(reVal(inp%base)); + charArr.add(reVal(inp % base)); inp /= base; } StringBuilder str = new StringBuilder(charArr.size()); - for(Character ch: charArr) { + for (Character ch : charArr) { str.append(ch); } @@ -28,14 +29,15 @@ public class DecimalToAnyBase { /** * This method produces character value of the input integer and returns it + * * @param num integer of which we need the character value of * @return character value of input integer */ private char reVal(int num) { if (num >= 0 && num <= 9) - return (char)(num + '0'); + return (char) (num + '0'); else - return (char)(num - 10 + 'A'); + return (char) (num - 10 + 'A'); } } diff --git a/src/main/java/com/conversions/DecimalToHexadecimal.java b/src/main/java/com/conversions/DecimalToHexadecimal.java index cce26666..e0e9360d 100644 --- a/src/main/java/com/conversions/DecimalToHexadecimal.java +++ b/src/main/java/com/conversions/DecimalToHexadecimal.java @@ -3,15 +3,16 @@ package src.main.java.com.conversions; import java.math.BigInteger; public class DecimalToHexadecimal { - private static final char hexChars[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + private static final char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static final BigInteger valueHex = new BigInteger("16"); /** * This method converts and decimal number to a Hexadecimal number + * * @param decimalStr * @return hexadecimal number */ - public String decimalToHex(String decimalStr){ + public String decimalToHex(String decimalStr) { BigInteger decimal = new BigInteger(decimalStr); int rem; diff --git a/src/main/java/com/conversions/DecimalToOctal.java b/src/main/java/com/conversions/DecimalToOctal.java index 743b0e0a..6ab6e72b 100644 --- a/src/main/java/com/conversions/DecimalToOctal.java +++ b/src/main/java/com/conversions/DecimalToOctal.java @@ -3,20 +3,21 @@ package src.main.java.com.conversions; import java.math.BigInteger; public class DecimalToOctal { - private static final char octalChars[] = {'0','1','2','3','4','5','6','7'}; + private static final char[] octalChars = {'0', '1', '2', '3', '4', '5', '6', '7'}; private static final BigInteger valueOctal = new BigInteger("8"); /** * This method converts and decimal number to a octal number + * * @param decimalStr * @return octal number */ - public String decimalToOctal(String decimalStr){ + public String decimalToOctal(String decimalStr) { BigInteger decimal = new BigInteger(decimalStr); int rem; String octal = ""; - while(decimal.compareTo(BigInteger.ZERO) > 0) { + while (decimal.compareTo(BigInteger.ZERO) > 0) { rem = decimal.mod(valueOctal).intValueExact(); octal = octalChars[rem] + octal; decimal = decimal.divide(valueOctal); diff --git a/src/main/java/com/dataStructures/BinaryTree.java b/src/main/java/com/dataStructures/BinaryTree.java index 8cdb319c..3542bce5 100644 --- a/src/main/java/com/dataStructures/BinaryTree.java +++ b/src/main/java/com/dataStructures/BinaryTree.java @@ -2,39 +2,42 @@ package src.main.java.com.dataStructures; /** * Binary tree for general value type, without redundancy - * @author RICARDO + * * @param root data */ + public class BinaryTree { private final T data; - private BinaryTree right, // the upper binary tree - left; // the lower binary tree + private BinaryTree right, // the upper binary tree + left; // the lower binary tree public BinaryTree(T data) { this.data = data; } @Override - public String toString(){ + public String toString() { return this.data.toString(); } - + /** * inserts a new value in it's correspondant place - * @param newDataValue value of the new banary tree to add on this tree + * + * @param newDataValue value of the new binary tree to add on this tree */ - public void insert(T newDataValue){ + public void insert(T newDataValue) { this.insert(new BinaryTree(newDataValue)); } - + /** * inserts a new binary tree in it's correspondant place - * @param newData new value to add on this tree + * + * @param newData new value to add on this tree */ - public void insert(BinaryTree newData){ - + public void insert(BinaryTree newData) { + int cpr = newData.data.compareTo(this.data); //new value comparission respect to actual value - + if (cpr < 0) if (this.left == null) this.setLeft(newData); @@ -51,12 +54,13 @@ public class BinaryTree { /** * search and specific value on the tree - * @param data Searched value - * @return Binary tree wich contains the value, null if it doesn't exist + * + * @param data Searched value + * @return Binary tree which contains the value, null if it doesn't exist */ - public BinaryTree search(T data){ + public BinaryTree search(T data) { int cpr = data.compareTo(this.data); //new value comparission respect to actual value - + if (cpr < 0) { if (this.left == null) return null; //the value doesn't exist @@ -65,43 +69,45 @@ public class BinaryTree { if (cpr > 0) { if (this.right == null) return null; //the value doesn't exist - return this.right.search(data); + return this.right.search(data); } return this; } - + /** * Checks if the data value exist in the tree + * * @param data data to be searched * @return true if this tree contains the data value, false if not. */ - public boolean contains(T data){ + public boolean contains(T data) { return this.search(data) != null; } - + /** * uses recursive black magic to print this tree in console + * * @param tabCounter prev tabs */ - private void print(int tabCounter){ + private void print(int tabCounter) { for (int i = 0; i < tabCounter; i++) System.out.print("\t"); - + System.out.println(this); - + if (this.left != null) this.left.print(tabCounter + 1); //it can't be ++ , pls don't change it if (this.right != null) this.right.print(tabCounter + 1); //it can't be ++ , pls don't change it } - + /** * uses black magic to print this tree in console */ - public void print(){ + public void print() { this.print(0); } - + //getters and setters public T getData() { return data; diff --git a/src/main/java/com/dataStructures/DisjointSet.java b/src/main/java/com/dataStructures/DisjointSet.java index c2a59c32..3fb70f6c 100644 --- a/src/main/java/com/dataStructures/DisjointSet.java +++ b/src/main/java/com/dataStructures/DisjointSet.java @@ -15,7 +15,6 @@ import java.util.*; *

* 2. quickly query two elements whether contained in the same set, requiring about O(1) time. * - * @author yangxf */ public class DisjointSet implements Serializable { private static final long serialVersionUID = 3134700471905625636L; diff --git a/src/main/java/com/generation/SimplexNoise.java b/src/main/java/com/generation/SimplexNoise.java index 699e0a2f..a4fcb3f1 100644 --- a/src/main/java/com/generation/SimplexNoise.java +++ b/src/main/java/com/generation/SimplexNoise.java @@ -7,128 +7,131 @@ import java.util.Random; */ public class SimplexNoise { - private SimplexNoiseOctave[] octaves; - private double[] frequencys; - private double[] amplitudes; - private int largestFeature; - private double persistance; - private long seed; - - /** - * @param largestFeature the diameter of the largest possible "cloud". - * @param persistence the persistence. a low persistence causes smoother transition between the features while a high one makes the transition hard. (range = {@code 0.0F} - {@code 1.0F}) - * @param seed the seed this algorithm will use to generate pseudo random numbers. The generation will always look the same if the seed and the other parameters have the same value as in a previous generation - */ - public SimplexNoise(int largestFeature, double persistence, long seed) { - - this.largestFeature = largestFeature; - this.persistance = persistence; - this.seed = seed; - - int octaveCount = (int)Math.ceil(Math.log10(largestFeature) / Math.log10(2.0D)); - this.octaves = new SimplexNoiseOctave[octaveCount]; - this.frequencys = new double[octaveCount]; - this.amplitudes = new double[octaveCount]; - - Random random = new Random(seed); - - for(int index = 0; index < octaveCount; index++) { - - this.octaves[index] = new SimplexNoiseOctave(random.nextInt()); - this.frequencys[index] = Math.pow(2, index); - this.amplitudes[index] = Math.pow(persistence, octaveCount - index); - } - } - - /** - * Generates a height map. - * @param x X coordinate - * @param y Y coordinate - * @param width width - * @param height height - * @return the generated height map - */ - public float[][] generateHeightMap(int x, int y, int width, int height) { - - int xEnd = x + width; - int yEnd = y + height; - - float[][] result = new float[width][height]; - - for(int i = 0; i < width; i++) { - - for(int j = 0; j < height; j++) { - - int posX = x + i * ((xEnd - x) / width); - int posY = y + j * ((yEnd - y) / height); - result[i][j] = Math.min(1.0F, Math.max(0.0F, (float)(0.5D * (1 + this.getNoise(posX, posY))))); - } - } - - return result; - } - - /** - * Generates a two dimensional noise. - * @param x X coordinate - * @param y Y coordinate - * @return the generated noise - */ - public double getNoise(int x, int y) { - - double result = 0; - - for(int index = 0; index < this.octaves.length; index++) { - - result += this.octaves[index].noise(x / this.frequencys[index], y / this.frequencys[index]) * this.amplitudes[index]; - } - - return result; - } - - /** - * Generates a three dimensional noise. - * @param x X coordinate - * @param y Y coordinate - * @param z Z coordinate - * @return the generated noise - */ - public double getNoise(int x, int y, int z) { - - double result = 0; - - for(int index = 0; index < this.octaves.length; index++) { - - double frequency = Math.pow(2, index); - double amplitude = Math.pow(this.persistance, this.octaves.length - index); - - result += this.octaves[index].noise(x / frequency, y / frequency, z / frequency) * amplitude; - } - - return result; - } - - /** - * @return the largest possible feature - */ - public int getLargestFeature() { - - return this.largestFeature; - } - - /** - * @return the persistence - */ - public double getPersistance() { - - return this.persistance; - } - - /** - * @return the seed - */ - public long getSeed() { - - return this.seed; - } + private SimplexNoiseOctave[] octaves; + private double[] frequencys; + private double[] amplitudes; + private int largestFeature; + private double persistance; + private long seed; + + /** + * @param largestFeature the diameter of the largest possible "cloud". + * @param persistence the persistence. a low persistence causes smoother transition between the features while a high one makes the transition hard. (range = {@code 0.0F} - {@code 1.0F}) + * @param seed the seed this algorithm will use to generate pseudo random numbers. The generation will always look the same if the seed and the other parameters have the same value as in a previous generation + */ + public SimplexNoise(int largestFeature, double persistence, long seed) { + + this.largestFeature = largestFeature; + this.persistance = persistence; + this.seed = seed; + + int octaveCount = (int) Math.ceil(Math.log10(largestFeature) / Math.log10(2.0D)); + this.octaves = new SimplexNoiseOctave[octaveCount]; + this.frequencys = new double[octaveCount]; + this.amplitudes = new double[octaveCount]; + + Random random = new Random(seed); + + for (int index = 0; index < octaveCount; index++) { + + this.octaves[index] = new SimplexNoiseOctave(random.nextInt()); + this.frequencys[index] = Math.pow(2, index); + this.amplitudes[index] = Math.pow(persistence, octaveCount - index); + } + } + + /** + * Generates a height map. + * + * @param x X coordinate + * @param y Y coordinate + * @param width width + * @param height height + * @return the generated height map + */ + public float[][] generateHeightMap(int x, int y, int width, int height) { + + int xEnd = x + width; + int yEnd = y + height; + + float[][] result = new float[width][height]; + + for (int i = 0; i < width; i++) { + + for (int j = 0; j < height; j++) { + + int posX = x + i * ((xEnd - x) / width); + int posY = y + j * ((yEnd - y) / height); + result[i][j] = Math.min(1.0F, Math.max(0.0F, (float) (0.5D * (1 + this.getNoise(posX, posY))))); + } + } + + return result; + } + + /** + * Generates a two dimensional noise. + * + * @param x X coordinate + * @param y Y coordinate + * @return the generated noise + */ + public double getNoise(int x, int y) { + + double result = 0; + + for (int index = 0; index < this.octaves.length; index++) { + + result += this.octaves[index].noise(x / this.frequencys[index], y / this.frequencys[index]) * this.amplitudes[index]; + } + + return result; + } + + /** + * Generates a three dimensional noise. + * + * @param x X coordinate + * @param y Y coordinate + * @param z Z coordinate + * @return the generated noise + */ + public double getNoise(int x, int y, int z) { + + double result = 0; + + for (int index = 0; index < this.octaves.length; index++) { + + double frequency = Math.pow(2, index); + double amplitude = Math.pow(this.persistance, this.octaves.length - index); + + result += this.octaves[index].noise(x / frequency, y / frequency, z / frequency) * amplitude; + } + + return result; + } + + /** + * @return the largest possible feature + */ + public int getLargestFeature() { + + return this.largestFeature; + } + + /** + * @return the persistence + */ + public double getPersistance() { + + return this.persistance; + } + + /** + * @return the seed + */ + public long getSeed() { + + return this.seed; + } } diff --git a/src/main/java/com/generation/SimplexNoiseOctave.java b/src/main/java/com/generation/SimplexNoiseOctave.java index 75d979e0..b1e281d2 100644 --- a/src/main/java/com/generation/SimplexNoiseOctave.java +++ b/src/main/java/com/generation/SimplexNoiseOctave.java @@ -14,7 +14,7 @@ public class SimplexNoiseOctave { new Gradient(1, 0, -1), new Gradient(-1, 0, -1), new Gradient(0, 1, 1), new Gradient(0, -1, 1), new Gradient(0, 1, -1), new Gradient(0, -1, -1) }; - private static final short P_SUPPLY[] = { + private static final short[] P_SUPPLY = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, diff --git a/src/main/java/com/matchings/stableMatching/GaleShapley.java b/src/main/java/com/matchings/stableMatching/GaleShapley.java index 3c60e836..18624f9b 100644 --- a/src/main/java/com/matchings/stableMatching/GaleShapley.java +++ b/src/main/java/com/matchings/stableMatching/GaleShapley.java @@ -5,8 +5,8 @@ public class GaleShapley { /** * Return a stable matching between men and women according to their preferences, * following the Gale-Shapley algorithm. - * - * @param menPrefs for each man, for each preference rank, the corresponding woman + * + * @param menPrefs for each man, for each preference rank, the corresponding woman * @param womenPrefs for each woman, for each preference rank, the corresponding man * @return for each man, the associated woman (1-dimensional array) */ @@ -88,7 +88,7 @@ public class GaleShapley { /** * Get a currently unengaged man, if there is one - * + * * @param menMatching the current men matching array (being constructed) * @return the first man that is not engaged, or -1 if all men are engaged */ diff --git a/src/main/java/com/search/BloomFilter.java b/src/main/java/com/search/BloomFilter.java index 122a3029..70a7f1c3 100644 --- a/src/main/java/com/search/BloomFilter.java +++ b/src/main/java/com/search/BloomFilter.java @@ -16,7 +16,6 @@ import java.util.function.Function; *

* The accuracy rate depends on capacity and hash functions. * - * @author yangxf */ public class BloomFilter implements Serializable { private static final long serialVersionUID = -4466610350741278658L; diff --git a/src/main/java/com/search/LinearSearch.java b/src/main/java/com/search/LinearSearch.java index e8e8e3e1..66db8aad 100644 --- a/src/main/java/com/search/LinearSearch.java +++ b/src/main/java/com/search/LinearSearch.java @@ -15,7 +15,7 @@ public final class LinearSearch { * @param is any comparable type * @return index of the element */ - public static > int findIndex(T array[], T key) { + public static > int findIndex(T[] array, T key) { return search(array, key); } @@ -24,7 +24,7 @@ public final class LinearSearch { * @param key The element you are looking for * @return the location of the key or -1 if the element is not found **/ - private static > int search(T array[], T key){ + private static > int search(T[] array, T key){ for(int i = 0; i < array.length;i++) { if (array[i].compareTo(key) == 0){ return i; diff --git a/src/main/java/com/sorts/HeapSort.java b/src/main/java/com/sorts/HeapSort.java index a1cefd09..4135e5ba 100644 --- a/src/main/java/com/sorts/HeapSort.java +++ b/src/main/java/com/sorts/HeapSort.java @@ -9,107 +9,106 @@ import static src.main.java.com.sorts.SortUtils.swap; public class HeapSort { + private static class Heap> { + /** + * Array to store heap + */ + private T[] heap; - private static class Heap> { - /** - * Array to store heap - */ - private T[] heap; - - /** - * Constructor - * - * @param heap array of unordered integers - */ - Heap(T[] heap) { - this.heap = heap; - } - - /** - * Heapifies subtree from top as root to last as last child - * - * @param rootIndex index of root - * @param lastChild index of last child - */ - private void heapSubtree(int rootIndex, int lastChild) { - int leftIndex = rootIndex * 2 + 1; - int rightIndex = rootIndex * 2 + 2; - T root = heap[rootIndex]; - if (rightIndex <= lastChild) { - // if has right and left children - T left = heap[leftIndex]; - T right = heap[rightIndex]; - if (less(left, right) && less(left, root)) { - swap(heap, leftIndex, rootIndex); - heapSubtree(leftIndex, lastChild); - } else if (less(right, root)) { - swap(heap, rightIndex, rootIndex); - heapSubtree(rightIndex, lastChild); + /** + * Constructor + * + * @param heap array of unordered integers + */ + Heap(T[] heap) { + this.heap = heap; } - } else if (leftIndex <= lastChild) { - // if no right child, but has left child - T left = heap[leftIndex]; - if (less(left, root)) { - swap(heap, leftIndex, rootIndex); - heapSubtree(leftIndex, lastChild); + + /** + * Heapifies subtree from top as root to last as last child + * + * @param rootIndex index of root + * @param lastChild index of last child + */ + private void heapSubtree(int rootIndex, int lastChild) { + int leftIndex = rootIndex * 2 + 1; + int rightIndex = rootIndex * 2 + 2; + T root = heap[rootIndex]; + if (rightIndex <= lastChild) { + // if has right and left children + T left = heap[leftIndex]; + T right = heap[rightIndex]; + if (less(left, right) && less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); + } else if (less(right, root)) { + swap(heap, rightIndex, rootIndex); + heapSubtree(rightIndex, lastChild); + } + } else if (leftIndex <= lastChild) { + // if no right child, but has left child + T left = heap[leftIndex]; + if (less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); + } + } } - } + + + /** + * Makes heap with root as root + * + * @param root index of root of heap + */ + private void makeMinHeap(int root) { + int leftIndex = root * 2 + 1; + int rightIndex = root * 2 + 2; + boolean hasLeftChild = leftIndex < heap.length; + boolean hasRightChild = rightIndex < heap.length; + if (hasRightChild) { + //if has left and right + makeMinHeap(leftIndex); + makeMinHeap(rightIndex); + heapSubtree(root, heap.length - 1); + } else if (hasLeftChild) { + heapSubtree(root, heap.length - 1); + } + } + + /** + * Gets the root of heap + * + * @return root of heap + */ + private T getRoot(int size) { + swap(heap, 0, size); + heapSubtree(0, size - 1); + // return old root + return heap[size]; + } + + } - - /** - * Makes heap with root as root - * - * @param root index of root of heap - */ - private void makeMinHeap(int root) { - int leftIndex = root * 2 + 1; - int rightIndex = root * 2 + 2; - boolean hasLeftChild = leftIndex < heap.length; - boolean hasRightChild = rightIndex < heap.length; - if (hasRightChild) { - //if has left and right - makeMinHeap(leftIndex); - makeMinHeap(rightIndex); - heapSubtree(root, heap.length - 1); - } else if (hasLeftChild) { - heapSubtree(root, heap.length - 1); - } + public > T[] sort(T[] unsorted) { + return sort(Arrays.asList(unsorted)).toArray(unsorted); } - /** - * Gets the root of heap - * - * @return root of heap - */ - private T getRoot(int size) { - swap(heap, 0, size); - heapSubtree(0, size - 1); - // return old root - return heap[size]; + private > List sort(List unsorted) { + int size = unsorted.size(); + + @SuppressWarnings("unchecked") + Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); + + // make min heap using index 0 as root. + heap.makeMinHeap(0); + List sorted = new ArrayList<>(size); + while (size > 0) { + T min = heap.getRoot(--size); + sorted.add(min); + } + + return sorted; } - - - } - - public > T[] sort(T[] unsorted) { - return sort(Arrays.asList(unsorted)).toArray(unsorted); - } - - private > List sort(List unsorted) { - int size = unsorted.size(); - - @SuppressWarnings("unchecked") - Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); - - // make min heap using index 0 as root. - heap.makeMinHeap(0); - List sorted = new ArrayList<>(size); - while (size > 0) { - T min = heap.getRoot(--size); - sorted.add(min); - } - - return sorted; - } } \ No newline at end of file diff --git a/src/main/java/com/sorts/MergeSort.java b/src/main/java/com/sorts/MergeSort.java index 3582a08b..6d6516b2 100644 --- a/src/main/java/com/sorts/MergeSort.java +++ b/src/main/java/com/sorts/MergeSort.java @@ -2,74 +2,74 @@ package src.main.java.com.sorts; public class MergeSort { - /** - * This method implements the Generic Merge Sort - * - * @param unsorted the array which should be sorted - * @param Comparable class - * @return sorted array - */ - @SuppressWarnings("unchecked") - public > T[] sort(T[] unsorted) { - T[] tmp = (T[]) new Comparable[unsorted.length]; - doSort(unsorted, tmp, 0, unsorted.length - 1); - return unsorted; - } - - /** - * @param arr The array to be sorted - * @param temp The copy of the actual array - * @param left The first index of the array - * @param right The last index of the array - * Recursively sorts the array in increasing order - **/ - private static > void doSort(T[] arr, T[] temp, int left, int right) { - if (left < right) { - int mid = left + (right - left) / 2; - doSort(arr, temp, left, mid); - doSort(arr, temp, mid + 1, right); - merge(arr, temp, left, mid, right); - } - } - - /** - * This method implements the merge step of the merge sort - * - * @param arr The array to be sorted - * @param temp The copy of the actual array - * @param left The first index of the array - * @param mid The middle index of the array - * @param right The last index of the array - * merges two parts of an array in increasing order - **/ - private static > void merge(T[] arr, T[] temp, int left, int mid, int right) { - System.arraycopy(arr, left, temp, left, right - left + 1); - - int i = left; - int j = mid + 1; - int k = left; - - while (i <= mid && j <= right) { - if (temp[i].compareTo(temp[j]) <= 0) { - arr[k] = temp[i]; - i++; - } else { - arr[k] = temp[j]; - j++; - } - k++; + /** + * This method implements the Generic Merge Sort + * + * @param unsorted the array which should be sorted + * @param Comparable class + * @return sorted array + */ + @SuppressWarnings("unchecked") + public > T[] sort(T[] unsorted) { + T[] tmp = (T[]) new Comparable[unsorted.length]; + doSort(unsorted, tmp, 0, unsorted.length - 1); + return unsorted; } - while (i <= mid) { - arr[k] = temp[i]; - i++; - k++; + /** + * @param arr The array to be sorted + * @param temp The copy of the actual array + * @param left The first index of the array + * @param right The last index of the array + * Recursively sorts the array in increasing order + **/ + private static > void doSort(T[] arr, T[] temp, int left, int right) { + if (left < right) { + int mid = left + (right - left) / 2; + doSort(arr, temp, left, mid); + doSort(arr, temp, mid + 1, right); + merge(arr, temp, left, mid, right); + } } - while (j <= right) { - arr[k] = temp[j]; - j++; - k++; + /** + * This method implements the merge step of the merge sort + * + * @param arr The array to be sorted + * @param temp The copy of the actual array + * @param left The first index of the array + * @param mid The middle index of the array + * @param right The last index of the array + * merges two parts of an array in increasing order + **/ + private static > void merge(T[] arr, T[] temp, int left, int mid, int right) { + System.arraycopy(arr, left, temp, left, right - left + 1); + + int i = left; + int j = mid + 1; + int k = left; + + while (i <= mid && j <= right) { + if (temp[i].compareTo(temp[j]) <= 0) { + arr[k] = temp[i]; + i++; + } else { + arr[k] = temp[j]; + j++; + } + k++; + } + + while (i <= mid) { + arr[k] = temp[i]; + i++; + k++; + } + + while (j <= right) { + arr[k] = temp[j]; + j++; + k++; + } } - } } diff --git a/src/main/java/com/sorts/QuickSort.java b/src/main/java/com/sorts/QuickSort.java index 31d6a0fb..e1a5f15d 100644 --- a/src/main/java/com/sorts/QuickSort.java +++ b/src/main/java/com/sorts/QuickSort.java @@ -5,61 +5,60 @@ import static src.main.java.com.sorts.SortUtils.swap; public class QuickSort { - - /** - * This method implements the Generic Quick Sort - * - * @param array The array to be sorted - * Sorts the array in increasing order - **/ - public > T[] sort(T[] array) { - doSort(array, 0, array.length - 1); - return array; - } - - - /** - * The sorting process - * - * @param left The first index of an array - * @param right The last index of an array - * @param array The array to be sorted - **/ - - private static > void doSort(T[] array, int left, int right) { - if (left < right) { - int pivot = partition(array, left, right); - doSort(array, left, pivot - 1); - doSort(array, pivot, right); + /** + * This method implements the Generic Quick Sort + * + * @param array The array to be sorted + * Sorts the array in increasing order + **/ + public > T[] sort(T[] array) { + doSort(array, 0, array.length - 1); + return array; } - } - /** - * This method finds the partition index for an array - * - * @param array The array to be sorted - * @param left The first index of an array - * @param right The last index of an array - * Finds the partition index of an array - **/ - private static > int partition(T[] array, int left, int right) { - int mid = (left + right) / 2; - T pivot = array[mid]; + /** + * The sorting process + * + * @param left The first index of an array + * @param right The last index of an array + * @param array The array to be sorted + **/ - while (left <= right) { - while (less(array[left], pivot)) { - ++left; - } - while (less(pivot, array[right])) { - --right; - } - if (left <= right) { - swap(array, left, right); - ++left; - --right; - } + private static > void doSort(T[] array, int left, int right) { + if (left < right) { + int pivot = partition(array, left, right); + doSort(array, left, pivot - 1); + doSort(array, pivot, right); + } + } + + /** + * This method finds the partition index for an array + * + * @param array The array to be sorted + * @param left The first index of an array + * @param right The last index of an array + * Finds the partition index of an array + **/ + + private static > int partition(T[] array, int left, int right) { + int mid = (left + right) / 2; + T pivot = array[mid]; + + while (left <= right) { + while (less(array[left], pivot)) { + ++left; + } + while (less(pivot, array[right])) { + --right; + } + if (left <= right) { + swap(array, left, right); + ++left; + --right; + } + } + return left; } - return left; - } } \ No newline at end of file diff --git a/src/main/java/com/sorts/SelectionSort.java b/src/main/java/com/sorts/SelectionSort.java index 1038bec3..b498aa79 100644 --- a/src/main/java/com/sorts/SelectionSort.java +++ b/src/main/java/com/sorts/SelectionSort.java @@ -5,28 +5,28 @@ import static src.main.java.com.sorts.SortUtils.swap; public class SelectionSort { - /** - * This method implements the Generic Selection Sort - * - * @param arr The array to be sorted - * Sorts the array in increasing order - **/ - public > T[] sort(T[] arr) { - int n = arr.length; - for (int i = 0; i < n - 1; i++) { - // Initial index of min - int min = i; - for (int j = i + 1; j < n; j++) { - if (less(arr[j], arr[min])) { - min = j; + /** + * This method implements the Generic Selection Sort + * + * @param arr The array to be sorted + * Sorts the array in increasing order + **/ + public > T[] sort(T[] arr) { + int n = arr.length; + for (int i = 0; i < n - 1; i++) { + // Initial index of min + int min = i; + for (int j = i + 1; j < n; j++) { + if (less(arr[j], arr[min])) { + min = j; + } + } + // Swapping if index of min is changed + if (min != i) { + swap(arr, i, min); + } } - } - // Swapping if index of min is changed - if (min != i) { - swap(arr, i, min); - } - } - return arr; - } + return arr; + } } \ No newline at end of file diff --git a/src/main/java/com/sorts/ShellSort.java b/src/main/java/com/sorts/ShellSort.java index d300cfc0..8ec8e415 100644 --- a/src/main/java/com/sorts/ShellSort.java +++ b/src/main/java/com/sorts/ShellSort.java @@ -5,28 +5,28 @@ import static src.main.java.com.sorts.SortUtils.swap; public class ShellSort { - /** - * This method implements Generic Shell Sort. - * - * @param array The array to be sorted - */ - public > T[] sort(T[] array) { - int length = array.length; - int n = 1; + /** + * This method implements Generic Shell Sort. + * + * @param array The array to be sorted + */ + public > T[] sort(T[] array) { + int length = array.length; + int n = 1; - while (n < length / 3) { - n = 3 * n + 1; - } - - while (n >= 1) { - for (int i = n; i < length; i++) { - for (int j = i; j >= n && less(array[j], array[j - n]); j -= n) { - swap(array, j, j - n); + while (n < length / 3) { + n = 3 * n + 1; } - } - n /= 3; - } - return array; - } + while (n >= 1) { + for (int i = n; i < length; i++) { + for (int j = i; j >= n && less(array[j], array[j - n]); j -= n) { + swap(array, j, j - n); + } + } + n /= 3; + } + + return array; + } } \ No newline at end of file diff --git a/src/main/java/com/sorts/SortUtils.java b/src/main/java/com/sorts/SortUtils.java index 26fc683e..bd5e5a65 100644 --- a/src/main/java/com/sorts/SortUtils.java +++ b/src/main/java/com/sorts/SortUtils.java @@ -3,43 +3,43 @@ package src.main.java.com.sorts; final class SortUtils { - /** - * Helper method for swapping places in 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 - */ - static boolean swap(T[] array, int idx, int idy) { - T swap = array[idx]; - array[idx] = array[idy]; - array[idy] = swap; - return true; - } - - - /** - * This method checks if first element is less then the other element - * - * @param v first element - * @param w second element - * @return true if the first element is less then the second element - */ - static > boolean less(T v, T w) { - return v.compareTo(w) < 0; - } - - - /** - * Swaps all position from {@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 - */ - static > void flip(T[] array, int left, int right) { - while (left <= right) { - swap(array, left++, right--); + /** + * Helper method for swapping places in 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 + */ + static boolean swap(T[] array, int idx, int idy) { + T swap = array[idx]; + array[idx] = array[idy]; + array[idy] = swap; + return true; + } + + + /** + * This method checks if first element is less then the other element + * + * @param v first element + * @param w second element + * @return true if the first element is less then the second element + */ + static > boolean less(T v, T w) { + return v.compareTo(w) < 0; + } + + + /** + * Swaps all position from {@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 + */ + static > void flip(T[] array, int left, int right) { + while (left <= right) { + swap(array, left++, right--); + } } - } } \ No newline at end of file diff --git a/src/main/java/com/sorts/StoogeSort.java b/src/main/java/com/sorts/StoogeSort.java index fe81a6df..b57d35df 100644 --- a/src/main/java/com/sorts/StoogeSort.java +++ b/src/main/java/com/sorts/StoogeSort.java @@ -5,35 +5,35 @@ import static src.main.java.com.sorts.SortUtils.less; public class StoogeSort { - /** - * This method implements recursion StoogeSort - * - * @param int[] array to store number elements - * @param f first element in the array - * @param l last element in the array - */ - public > T[] sort(T[] arr, int f, int l) { + /** + * This method implements recursion StoogeSort + * + * @param arr array to store number elements + * @param f first element in the array + * @param l last element in the array + */ + public > T[] sort(T[] arr, int f, int l) { - // Ends recursion when met - if (f >= l) - return arr; + // Ends recursion when met + if (f >= l) + return arr; - if (less(arr[l], arr[f])) { - swap(arr, f, l); - } + if (less(arr[l], arr[f])) { + swap(arr, f, l); + } - if (l - f + 1 > 2) { - int entry = (l - f + 1) / 3; + if (l - f + 1 > 2) { + int entry = (l - f + 1) / 3; - // Does a recursive sort of the first two thirds elements - sort(arr, f, l - entry); + // Does a recursive sort of the first two thirds elements + sort(arr, f, l - entry); - // Does a recursive sort of the last two thirds elements - sort(arr, f + entry, l); + // Does a recursive sort of the last two thirds elements + sort(arr, f + entry, l); - // Another recursive sort first two thirds elements to confirm - sort(arr, f, l - entry); - } - return arr; - } + // Another recursive sort first two thirds elements to confirm + sort(arr, f, l - entry); + } + return arr; + } } \ No newline at end of file diff --git a/src/main/java/com/types/Sort.java b/src/main/java/com/types/Sort.java index da89756f..e3316b4e 100644 --- a/src/main/java/com/types/Sort.java +++ b/src/main/java/com/types/Sort.java @@ -3,5 +3,5 @@ package src.main.java.com.types; @FunctionalInterface public interface Sort { - public > T[] sort(T[] array); + > T[] sort(T[] array); } diff --git a/src/test/java/com/dataStructures/BinaryTreeTest.java b/src/test/java/com/dataStructures/BinaryTreeTest.java index b269441d..383bc0aa 100644 --- a/src/test/java/com/dataStructures/BinaryTreeTest.java +++ b/src/test/java/com/dataStructures/BinaryTreeTest.java @@ -1,30 +1,29 @@ -package src.main.java.com.dataStructures; +package src.test.java.com.dataStructures; import org.junit.Test; +import src.main.java.com.dataStructures.BinaryTree; + import static org.junit.Assert.*; -/** - * - * @author RICARDO - */ public class BinaryTreeTest { - + public BinaryTreeTest() { } - + /** * Test of insert method, of class BinaryTree. */ @Test - public void testInsert_BinaryTree() { + public void testInsertBinaryTree() { System.out.println("insert"); - BinaryTree lowerdata = new BinaryTree<>("1"); - BinaryTree upperdata = new BinaryTree<>("3"); + BinaryTree lowerData = new BinaryTree<>("1"); + BinaryTree upperData = new BinaryTree<>("3"); BinaryTree instance = new BinaryTree<>("2"); - instance.insert(lowerdata); - instance.insert(upperdata); - String proof = instance.getLeft().toString()+instance.toString()+instance.getRight().toString(); - System.out.println(proof); + instance.insert(lowerData); + instance.insert(upperData); + String proof = instance.getLeft().toString() + + instance.toString() + + instance.getRight().toString(); assertEquals("123", proof); } @@ -36,10 +35,10 @@ public class BinaryTreeTest { System.out.println("search"); BinaryTree instance = new BinaryTree<>(5); for (int i = 1; i < 10; i++) { - instance.insert(new Integer(i)); + instance.insert(i); } - BinaryTree result = instance.search(new Integer(1)); - assertEquals(new Integer(1), result.getData()); + BinaryTree result = instance.search(1); + assertEquals(1, result.getData()); } /** @@ -52,9 +51,8 @@ public class BinaryTreeTest { for (int i = 1; i < 10; i++) { instance.insert(i); } - - boolean result = instance.contains(2)&&instance.contains(11); - assertEquals(false, result); - } + boolean result = instance.contains(2) && instance.contains(11); + assertFalse(result); + } } From 184f644bd7050f5ee0837b45a44ef5ef1e0eda69 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 10 May 2019 15:16:01 +0800 Subject: [PATCH 13/19] update binaryToGray --- .../java/com/conversions/BinaryToGray.java | 44 +++++++++---------- .../com/conversions/BinaryToGrayTest.java | 21 +++++---- 2 files changed, 31 insertions(+), 34 deletions(-) diff --git a/src/main/java/com/conversions/BinaryToGray.java b/src/main/java/com/conversions/BinaryToGray.java index 1482b8d6..60896e0f 100644 --- a/src/main/java/com/conversions/BinaryToGray.java +++ b/src/main/java/com/conversions/BinaryToGray.java @@ -1,28 +1,26 @@ package src.main.java.com.conversions; -public class BinaryToGray -{ - /* This method convert the binary number into gray code - @param binarycode need to convert binary number into gray code - @return graycode return as string - */ +/** + * Convert the binary number into gray code + */ +public class BinaryToGray { - public String binaryToGray(String binarycode) - { - - StringBuilder graycode = new StringBuilder(Character.toString(binarycode.charAt(0))); - - for(int i = 0; i < binarycode.length() - 1; i++) - { - - if (binarycode.charAt(i) == binarycode.charAt(i+1)) - graycode.append("0"); - else - graycode.append("1"); - - } - - return graycode.toString(); - } + /** + * convert the binary number into gray code + * + * @param binaryCode binary number + * @return grayCode return as string + */ + public String binaryToGray(String binaryCode) { + StringBuilder grayCode = new StringBuilder(Character.toString(binaryCode.charAt(0))); + + for (int i = 0; i < binaryCode.length() - 1; i++) { + if (binaryCode.charAt(i) == binaryCode.charAt(i + 1)) + grayCode.append("0"); + else + grayCode.append("1"); + } + return grayCode.toString(); + } } diff --git a/src/test/java/com/conversions/BinaryToGrayTest.java b/src/test/java/com/conversions/BinaryToGrayTest.java index c44f5470..64de8925 100644 --- a/src/test/java/com/conversions/BinaryToGrayTest.java +++ b/src/test/java/com/conversions/BinaryToGrayTest.java @@ -2,17 +2,16 @@ package src.test.java.com.conversions; import src.main.java.com.conversions.BinaryToGray; import org.junit.Test; + import static org.junit.Assert.assertEquals; -public class BinaryToGrayTest -{ - - @Test - public void testBinaryToGray() - { - BinaryToGray btog = new BinaryToGray(); - assertEquals("1101", btog.binaryToGray("1001")); - assertEquals("11010011101",btog.binaryToGray("10011101001")); - } - +public class BinaryToGrayTest { + + @Test + public void testBinaryToGray() { + BinaryToGray binaryToGray = new BinaryToGray(); + assertEquals("1101", binaryToGray.binaryToGray("1001")); + assertEquals("11010011101", binaryToGray.binaryToGray("10011101001")); + } + } From fbffeb658c131440196f5cd9b6d330fd93847b41 Mon Sep 17 00:00:00 2001 From: yanglbme Date: Fri, 10 May 2019 15:39:18 +0800 Subject: [PATCH 14/19] refactor: update FastPower --- .../com/{Others => others}/FastPower.java | 0 src/test/java/com/others/FastPowerTest.java | 9 +++++++ .../others/FastPowerTest.java___jb_tmp___} | 25 +++++++++++-------- 3 files changed, 23 insertions(+), 11 deletions(-) rename src/main/java/com/{Others => others}/FastPower.java (100%) create mode 100644 src/test/java/com/others/FastPowerTest.java rename src/{main/java/com/Others/FastPowerTest.java => test/java/com/others/FastPowerTest.java___jb_tmp___} (52%) diff --git a/src/main/java/com/Others/FastPower.java b/src/main/java/com/others/FastPower.java similarity index 100% rename from src/main/java/com/Others/FastPower.java rename to src/main/java/com/others/FastPower.java diff --git a/src/test/java/com/others/FastPowerTest.java b/src/test/java/com/others/FastPowerTest.java new file mode 100644 index 00000000..af38477f --- /dev/null +++ b/src/test/java/com/others/FastPowerTest.java @@ -0,0 +1,9 @@ +package src.test.java.com.others; + +/** + * @author bingo + * @since 2019/5/10 + */ + +public class FastPowerTest { +} diff --git a/src/main/java/com/Others/FastPowerTest.java b/src/test/java/com/others/FastPowerTest.java___jb_tmp___ similarity index 52% rename from src/main/java/com/Others/FastPowerTest.java rename to src/test/java/com/others/FastPowerTest.java___jb_tmp___ index bd61704b..4a086562 100644 --- a/src/main/java/com/Others/FastPowerTest.java +++ b/src/test/java/com/others/FastPowerTest.java___jb_tmp___ @@ -1,6 +1,7 @@ -package src.main.java.com.Others; +package src.test.java.com.others; -import org.junit.*; +import org.junit.Test; +import src.main.java.com.others.FastPower; import java.math.BigInteger; @@ -8,23 +9,25 @@ import static org.junit.Assert.*; public class FastPowerTest { - void testLong(long n, long k, long m){ - long result = FastPower.calculate(n,k,m); + @Test + void testLong(long n, long k, long m) { + long result = FastPower.calculate(n, k, m); assertEquals(result, BigInteger.valueOf(n).modPow(BigInteger.valueOf(k), BigInteger.valueOf(m)).longValue()); } - void testBigInteger(BigInteger n, BigInteger k, BigInteger m){ - BigInteger result = FastPower.calculate(n,k,m); - assertEquals(result, n.modPow(k,m)); + @Test + void testBigInteger(BigInteger n, BigInteger k, BigInteger m) { + BigInteger result = FastPower.calculate(n, k, m); + assertEquals(result, n.modPow(k, m)); } @Test public void test() { - testLong(2,2,10); - testLong(100,1000,20); - testLong(123456,123456789,234); + testLong(2, 2, 10); + testLong(100, 1000, 20); + testLong(123456, 123456789, 234); - testBigInteger(BigInteger.TEN,BigInteger.TEN, BigInteger.valueOf(4)); + testBigInteger(BigInteger.TEN, BigInteger.TEN, BigInteger.valueOf(4)); testBigInteger(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); testBigInteger(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); From 1041b02e6b81f44af8c25707edf885bced453b1c Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Fri, 10 May 2019 15:42:08 +0800 Subject: [PATCH 15/19] refactor: update FastPower --- src/main/java/com/others/FastPower.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/others/FastPower.java b/src/main/java/com/others/FastPower.java index 8cc1b8b6..ef1bd895 100644 --- a/src/main/java/com/others/FastPower.java +++ b/src/main/java/com/others/FastPower.java @@ -1,4 +1,4 @@ -package src.main.java.com.Others; +package src.main.java.com.others; import java.math.BigInteger; @@ -7,14 +7,13 @@ import java.math.BigInteger; * FastPower aims to calculate quickly in this circumstances with time complexity O(log k), * where k is the index. * - * @author DDullahan */ public class FastPower { public static BigInteger calculate(BigInteger n, BigInteger k, BigInteger mod) { BigInteger ans = BigInteger.ONE; while (!k.equals(BigInteger.ZERO)) { int odd = k.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO); - if(odd > 0){ + if (odd > 0) { ans = ans.multiply(n).mod(mod); } k = k.divide(BigInteger.valueOf(2)); From cac1b0b4c7545c6605d3c0c839003f27b34b6a2c Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Fri, 10 May 2019 15:42:55 +0800 Subject: [PATCH 16/19] Delete FastPowerTest.java___jb_tmp___ --- .../com/others/FastPowerTest.java___jb_tmp___ | 35 ------------------- 1 file changed, 35 deletions(-) delete mode 100644 src/test/java/com/others/FastPowerTest.java___jb_tmp___ diff --git a/src/test/java/com/others/FastPowerTest.java___jb_tmp___ b/src/test/java/com/others/FastPowerTest.java___jb_tmp___ deleted file mode 100644 index 4a086562..00000000 --- a/src/test/java/com/others/FastPowerTest.java___jb_tmp___ +++ /dev/null @@ -1,35 +0,0 @@ -package src.test.java.com.others; - -import org.junit.Test; -import src.main.java.com.others.FastPower; - -import java.math.BigInteger; - -import static org.junit.Assert.*; - -public class FastPowerTest { - - @Test - void testLong(long n, long k, long m) { - long result = FastPower.calculate(n, k, m); - assertEquals(result, BigInteger.valueOf(n).modPow(BigInteger.valueOf(k), BigInteger.valueOf(m)).longValue()); - } - - @Test - void testBigInteger(BigInteger n, BigInteger k, BigInteger m) { - BigInteger result = FastPower.calculate(n, k, m); - assertEquals(result, n.modPow(k, m)); - } - - @Test - public void test() { - testLong(2, 2, 10); - testLong(100, 1000, 20); - testLong(123456, 123456789, 234); - - testBigInteger(BigInteger.TEN, BigInteger.TEN, BigInteger.valueOf(4)); - testBigInteger(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); - testBigInteger(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); - - } -} \ No newline at end of file From ada660a4c313be9f4d3c2e50da4a3b2dc97f2f5f Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Fri, 10 May 2019 15:43:36 +0800 Subject: [PATCH 17/19] refactor: update FastPower --- src/test/java/com/others/FastPowerTest.java | 34 ++++++++++++++++++--- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/others/FastPowerTest.java b/src/test/java/com/others/FastPowerTest.java index af38477f..c3f504ed 100644 --- a/src/test/java/com/others/FastPowerTest.java +++ b/src/test/java/com/others/FastPowerTest.java @@ -1,9 +1,35 @@ package src.test.java.com.others; -/** - * @author bingo - * @since 2019/5/10 - */ +import org.junit.Test; +import src.main.java.com.others.FastPower; + +import java.math.BigInteger; + +import static org.junit.Assert.*; public class FastPowerTest { + + @Test + void testLong(long n, long k, long m) { + long result = FastPower.calculate(n, k, m); + assertEquals(result, BigInteger.valueOf(n).modPow(BigInteger.valueOf(k), BigInteger.valueOf(m)).longValue()); + } + + @Test + void testBigInteger(BigInteger n, BigInteger k, BigInteger m) { + BigInteger result = FastPower.calculate(n, k, m); + assertEquals(result, n.modPow(k, m)); + } + + @Test + public void test() { + testLong(2, 2, 10); + testLong(100, 1000, 20); + testLong(123456, 123456789, 234); + + testBigInteger(BigInteger.TEN, BigInteger.TEN, BigInteger.valueOf(4)); + testBigInteger(new BigInteger("123456"), new BigInteger("123456789"), new BigInteger("234")); + testBigInteger(new BigInteger("123456789101112"), new BigInteger("12345678910111213"), new BigInteger("567890")); + + } } From fa1503fa77e6904d55517dd5a869140880cb3956 Mon Sep 17 00:00:00 2001 From: Abir Bhushan Date: Fri, 10 May 2019 19:48:02 +0100 Subject: [PATCH 18/19] Apply suggestions from code review Update DepthFirstSearch.java - signature removed, and whitespaces resolved Co-Authored-By: Libin Yang --- src/main/java/com/search/DepthFirstSearch.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/search/DepthFirstSearch.java b/src/main/java/com/search/DepthFirstSearch.java index 12ce4c11..64df6bfb 100644 --- a/src/main/java/com/search/DepthFirstSearch.java +++ b/src/main/java/com/search/DepthFirstSearch.java @@ -12,7 +12,6 @@ package src.main.java.com.search; * Best-case performance O(1) * Average performance O(n) * - * @author abir (https://github.com/abircb) */ public class DepthFirstSearch { @@ -35,14 +34,12 @@ public class DepthFirstSearch { * The BinaryTree class defines the structure of a binary tree * Also contains a static nested class called TreeNode * @param - * @author abir */ class BinaryTree> { private TreeNode root; /** - * @author abir * @param

* This class defines what a node in a binary tree looks like */ @@ -87,10 +84,10 @@ class BinaryTree> { * @return the tree node corresponding to the key */ private TreeNode

find(P key) { - if(key.compareTo(this.key) == 0) return this; + if (key.compareTo(this.key) == 0) return this; else if(key.compareTo(this.key) < 0) { - if(this.left == null) return null; + if (this.left == null) return null; else return this.left.find(key); } From e5856e329fe940fb1bfff5c16d182f4ec63a77ed Mon Sep 17 00:00:00 2001 From: Libin Yang Date: Sat, 11 May 2019 09:52:38 +0800 Subject: [PATCH 19/19] Revert "Added DepthFirstSearch.java and DepthFirstTestSearch.java" --- .../java/com/search/DepthFirstSearch.java | 123 ------------------ .../java/com/search/DepthFirstSearchTest.java | 36 ----- 2 files changed, 159 deletions(-) delete mode 100644 src/main/java/com/search/DepthFirstSearch.java delete mode 100644 src/test/java/com/search/DepthFirstSearchTest.java diff --git a/src/main/java/com/search/DepthFirstSearch.java b/src/main/java/com/search/DepthFirstSearch.java deleted file mode 100644 index 64df6bfb..00000000 --- a/src/main/java/com/search/DepthFirstSearch.java +++ /dev/null @@ -1,123 +0,0 @@ -package src.main.java.com.search; - -/** - * Searching is faster in sorted structures. Binary search is O(log n). - * However, the cost of sorting is O(n · log n). - * What to do when adding or removing elements? Sort again? No. - * Create efficient data structures to maintain sorted sequences, and search in them - * Key example: binary sorted tree, allowing O(log N) insert, remove and lookup. - - In comes, depth-first search - * Worst-case performance O(n) - * Best-case performance O(1) - * Average performance O(n) - * - */ - -public class DepthFirstSearch { - - /** - * Depth-first search method - * - * @param tree- Binary tree to be searched - * @param value- Key being searched for - * @return Location of the key - */ - - public static > T find(T key, BinaryTree tree) { - return tree.get(key); - } - -} - -/** - * The BinaryTree class defines the structure of a binary tree - * Also contains a static nested class called TreeNode - * @param - */ -class BinaryTree> { - - private TreeNode root; - - /** - * @param

- * This class defines what a node in a binary tree looks like - */ - private static class TreeNode

> { - - P key, value; - TreeNode

left, right; - - private TreeNode(P key, P value) { - this.key = key; - this.value = value; - this.left = null; - this.right = null; - } - - /** - * @param node - * adds the specified node - */ - private void add(TreeNode

node) { - if (node.key.compareTo(this.key) < 0) { - if(this.left == null) { - this.left = node; - } - else { - this.left.add(node); - } - } - - else { - if(this.right == null) { - this.right = node; - } - else { - this.right.add(node); - } - } - } - - /** - * @param key - * @return the tree node corresponding to the key - */ - private TreeNode

find(P key) { - if (key.compareTo(this.key) == 0) return this; - - else if(key.compareTo(this.key) < 0) { - if (this.left == null) return null; - else return this.left.find(key); - } - - else { - if(this.right == null) return null; - else return this.right.find(key); - } - } - - } - - public BinaryTree() { - this.root = null; - } - - public void add(T key, T value) { - TreeNode node = new TreeNode(key, value); - if(this.root == null) { - this.root = node; - } - else { - this.root.add(node); - } - } - - public T get(T key) { - if(this.root == null) return null; - - TreeNode node = this.root.find(key); - if(node == null) return null; - return node.value; - } -} diff --git a/src/test/java/com/search/DepthFirstSearchTest.java b/src/test/java/com/search/DepthFirstSearchTest.java deleted file mode 100644 index 859abfb1..00000000 --- a/src/test/java/com/search/DepthFirstSearchTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package src.test.java.com.search; - -import org.junit.Assert; -import org.junit.Test; -import src.main.java.com.search.DepthFirstSearch; -import src.main.java.com.search.BinaryTree; - -public class DepthFirstSearchTest { - @Test - public void testDepthFirstSearch() { - - BinaryTree tree1 = new BinaryTree(); - tree1.add(1,1); - tree1.add(2,2); - tree1.add(3,3); - tree1.add(4,4); - Assert.assertEquals("Incorrect index", 3, DepthFirstSearch.find(3, tree1)); - Assert.assertEquals("Incorrect index", 1, DepthFirstSearch.find(1, tree1)); - Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(0, tree1)); - Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(8, tree1)); - Assert.assertEquals("Incorrect index", null, DepthFirstSearch.find(-2, tree1)); - - BinaryTree tree2 = new BinaryTree(); - tree2.add("1","A"); - tree2.add("2","B"); - tree2.add("3","C"); - tree2.add("4","D"); - - Assert.assertEquals("Incorrect index", "C", LinearSearch.findIndex(tree2,"3")); - Assert.assertEquals("Incorrect index", "B", LinearSearch.findIndex(tree2,"2")); - Assert.assertEquals("Incorrect index", null, LinearSearch.findIndex(tree2,"F")); - - BinaryTree tree3 = new BinaryTree(); - Assert.assertEquals("Incorrect index", null, LinearSearch.findIndex(tree3, "")); - } -}