From 78ec43276cf05cd8562b818f7dc7cd50175ffd2d Mon Sep 17 00:00:00 2001 From: tm4s Date: Tue, 1 Nov 2016 00:20:07 +0100 Subject: [PATCH 01/22] Fibonnaci fix --- .../pedrovgs/problem7/FibonacciNumbers.java | 32 +++++++++---------- .../problem7/FibonacciNumbersTest.java | 12 +++---- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java b/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java index bd0033f9..2404329a 100644 --- a/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java +++ b/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java @@ -41,9 +41,9 @@ public class FibonacciNumbers { * terms, the complexity order of this algorithm is O(1) because we are not using any auxiliary * data structure to solve this problem. */ - public int getRecursive(int n) { + public long getRecursive(long n) { validateInput(n); - if (n == 0 || n == 1) { + if (n == 1 || n == 2) { return 1; } else { return getRecursive(n - 1) + getRecursive(n - 2); @@ -54,16 +54,16 @@ public int getRecursive(int n) { * Iterative approach. The complexity order in this algorithm is O(N) where N is the integer used * as parameter. In space terms, the complexity order of this algorithm is again O(1). */ - public int getIterative(int n) { + public long getIterative(long n) { validateInput(n); - if (n <= 1) { + if (n <= 2) { return 1; } - int previous = 1; - int current = 1; - int element = 0; - for (int i = 2; i <= n; i++) { + long previous = 1; + long current = 1; + long element = 0; + for (long i = 3; i <= n; i++) { element = previous + current; previous = current; current = element; @@ -71,7 +71,7 @@ public int getIterative(int n) { return element; } - private static int[] elements = new int[1000]; + private static long[] elements = new long[1000]; /** * This version of the recursive algorithm is better in performance terms because we are caching @@ -85,19 +85,19 @@ public int getIterative(int n) { * the one used for the previous algorithms. In this case, we have O(N) because we are using an * additional data structure to store partial results. */ - public int getRecursiveWithCaching(int n) { + public long getRecursiveWithCaching(int n) { validateInput(n); - if (n <= 1) { + if (n <= 2) { return 1; - } else if (elements[n] != 0) { - return elements[n]; + } else if (elements[n-3] != 0) { + return elements[n-3]; } - elements[n] = getRecursiveWithCaching(n - 1) + getRecursiveWithCaching(n - 2); - return elements[n]; + elements[n-3] = getRecursiveWithCaching(n - 1) + getRecursiveWithCaching(n - 2); + return elements[n-3]; } - private void validateInput(int n) { + private void validateInput(long n) { if (n < 0) { throw new IllegalArgumentException("You can't use negative values as parameter."); } diff --git a/src/test/java/com/github/pedrovgs/problem7/FibonacciNumbersTest.java b/src/test/java/com/github/pedrovgs/problem7/FibonacciNumbersTest.java index 64facd79..7bdc2563 100644 --- a/src/test/java/com/github/pedrovgs/problem7/FibonacciNumbersTest.java +++ b/src/test/java/com/github/pedrovgs/problem7/FibonacciNumbersTest.java @@ -41,11 +41,11 @@ public void shouldNotAcceptNegativeValuesRecursive() { } @Test public void fourthNumberInFibonacciSequenceIsThreeRecursive() { - assertEquals(5, fibonacciNumbers.getRecursive(4)); + assertEquals(5, fibonacciNumbers.getRecursive(5)); } @Test public void eleventhNumberInFibonacciSequenceIsRecursive() { - assertEquals(144, fibonacciNumbers.getRecursive(11)); + assertEquals(144, fibonacciNumbers.getRecursive(12)); } @Test(expected = IllegalArgumentException.class) @@ -58,11 +58,11 @@ public void shouldNotAcceptNegativeValuesIterative() { } @Test public void fourthNumberInFibonacciSequenceIsThreeIterative() { - assertEquals(5, fibonacciNumbers.getIterative(4)); + assertEquals(5, fibonacciNumbers.getIterative(5)); } @Test public void eleventhNumberInFibonacciSequenceIsIterative() { - assertEquals(144, fibonacciNumbers.getIterative(11)); + assertEquals(144, fibonacciNumbers.getIterative(12)); } @Test(expected = IllegalArgumentException.class) @@ -71,10 +71,10 @@ public void shouldNotAcceptNegativeValuesRecursiveWithCatching() { } @Test public void fourthNumberInFibonacciSequenceIsThreeRecursiveWithCatching() { - assertEquals(5, fibonacciNumbers.getRecursiveWithCaching(4)); + assertEquals(5, fibonacciNumbers.getRecursiveWithCaching(5)); } @Test public void eleventhNumberInFibonacciSequenceIsRecursiveWithCatching() { - assertEquals(144, fibonacciNumbers.getRecursiveWithCaching(11)); + assertEquals(144, fibonacciNumbers.getRecursiveWithCaching(12)); } } From 58129e828567fac52e821ca147feeab87a95d780 Mon Sep 17 00:00:00 2001 From: tm4s Date: Tue, 1 Nov 2016 00:44:17 +0100 Subject: [PATCH 02/22] style fix --- .../com/github/pedrovgs/problem7/FibonacciNumbers.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java b/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java index 2404329a..6d19093a 100644 --- a/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java +++ b/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java @@ -90,11 +90,11 @@ public long getRecursiveWithCaching(int n) { if (n <= 2) { return 1; - } else if (elements[n-3] != 0) { - return elements[n-3]; + } else if (elements[n - 3] != 0) { + return elements[n - 3]; } - elements[n-3] = getRecursiveWithCaching(n - 1) + getRecursiveWithCaching(n - 2); - return elements[n-3]; + elements[n - 3] = getRecursiveWithCaching(n - 1) + getRecursiveWithCaching(n - 2); + return elements[n - 3]; } private void validateInput(long n) { From 1a71e9f95183a089b2b72a0cb42337681594e699 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?O=E5=9E=8B=E8=A1=80=E6=A9=99?= Date: Mon, 20 Feb 2017 06:10:01 +0800 Subject: [PATCH 03/22] bug in problem 10 (#26) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * a little mistake not a big deal * :bug: a little mistake add the number not the index add the last number in the array the test of this problem didn’t check the right answer, just unique number so it didn’t check out the problem * should support empty array test * Fix checkstyle error --- .../java/com/github/pedrovgs/problem10/RemoveDuplicates.java | 5 +++-- src/main/java/com/github/pedrovgs/problem8/SplitArray.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java b/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java index 9688feb5..e9b0ab7b 100644 --- a/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java +++ b/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java @@ -63,7 +63,7 @@ public Integer[] removeUsingSet(Integer[] numbers) { */ public Integer[] removeUsingSorting(Integer[] numbers) { validateArray(numbers); - if (numbers.length == 1) { + if (numbers.length == 1 || numbers.length == 0) { return numbers; } @@ -71,9 +71,10 @@ public Integer[] removeUsingSorting(Integer[] numbers) { List result = new LinkedList(); for (int i = 0; i < numbers.length - 1; i++) { if (!numbers[i].equals(numbers[i + 1])) { - result.add(i); + result.add(numbers[i]); } } + result.add(numbers[numbers.length - 1]); return result.toArray(new Integer[result.size()]); } diff --git a/src/main/java/com/github/pedrovgs/problem8/SplitArray.java b/src/main/java/com/github/pedrovgs/problem8/SplitArray.java index 514ec06b..7d3a7d6b 100644 --- a/src/main/java/com/github/pedrovgs/problem8/SplitArray.java +++ b/src/main/java/com/github/pedrovgs/problem8/SplitArray.java @@ -20,7 +20,7 @@ * to the left and every positive number to the right. Take into account that the order of these * elements among the same group(positive or negative) into the array doesn't care. * - * Input: [1,2,3,-1-,2,-3] Output: [-2,-1,-3,2,3,1] + * Input: [1,2,3,-1,-2,-3] Output: [-2,-1,-3,2,3,1] * * @author Pedro Vicente Gómez Sánchez. */ From 612ae63d12c4126207fcdd2366c7cee39897e23b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?O=E5=9E=8B=E8=A1=80=E6=A9=99?= Date: Tue, 21 Feb 2017 19:12:36 +0800 Subject: [PATCH 04/22] bug in problem 32 (#27) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * a little mistake not a big deal * :bug: a little mistake add the number not the index add the last number in the array the test of this problem didn’t check the right answer, just unique number so it didn’t check out the problem * should support empty array test * Fix checkstyle error * :bug: check the string's length --- src/main/java/com/github/pedrovgs/problem32/Contains.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/github/pedrovgs/problem32/Contains.java b/src/main/java/com/github/pedrovgs/problem32/Contains.java index a16efce3..09b199a4 100644 --- a/src/main/java/com/github/pedrovgs/problem32/Contains.java +++ b/src/main/java/com/github/pedrovgs/problem32/Contains.java @@ -37,7 +37,7 @@ public boolean evaluate(String w1, String w2) { for (int i = 0; i < w2.length() - 1; i++) { if (w2.charAt(i) == w1.charAt(0)) { for (int j = 0; j < w1.length(); j++) { - if (w1.charAt(j) == w2.charAt(i + j) && j == w1.length() - 1) { + if ((i + j) < w2.length() && w1.charAt(j) == w2.charAt(i + j) && j == w1.length() - 1) { contains = true; break; } From 0631dd0bdc905c69915fe33fdf2d8ff98c73ebe2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20Vicente=20G=C3=B3mez=20S=C3=A1nchez?= Date: Mon, 27 Mar 2017 14:55:24 +0200 Subject: [PATCH 05/22] Update README.md --- README.md | 140 +++++++++++++++++++++++++++--------------------------- 1 file changed, 70 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 9b650ae2..a6eee869 100644 --- a/README.md +++ b/README.md @@ -12,100 +12,100 @@ Problems ### Trees -* [Binary tree by level] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java) -* [Binary tree pre order] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem14/BinaryTreePreOrder.java) -* [Binary tree in order] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem15/BinaryTreeInOrder.java) -* [Binary tree post order] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem16/BinaryTreePostOrder.java) -* [Are binary trees equals?] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem17/BinaryTreeEquals.java) -* [Is binary search tree] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem18/IsBST.java) -* [Binary tree depth] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem19/BinaryTreeDepth.java) -* [Lowest common ancestor] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem21/LowestCommonAncestor.java) -* [Sorted array to BST] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem24/SortedArrayToBST.java) -* [AVL tree median] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem36/AvlTreeMedian.java) -* [Path calculator] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java) -* [Path to every leaf] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem38/PathToEveryLeaf.java) -* [Is tree balanced] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem65/IsTreeBalanced.java) -* [Generate list with nodes by level] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem66/TreeToListByLevel.java) +* [Binary tree by level](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java) +* [Binary tree pre order](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem14/BinaryTreePreOrder.java) +* [Binary tree in order](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem15/BinaryTreeInOrder.java) +* [Binary tree post order](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem16/BinaryTreePostOrder.java) +* [Are binary trees equals?](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem17/BinaryTreeEquals.java) +* [Is binary search tree](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem18/IsBST.java) +* [Binary tree depth](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem19/BinaryTreeDepth.java) +* [Lowest common ancestor](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem21/LowestCommonAncestor.java) +* [Sorted array to BST](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem24/SortedArrayToBST.java) +* [AVL tree median](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem36/AvlTreeMedian.java) +* [Path calculator](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java) +* [Path to every leaf](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem38/PathToEveryLeaf.java) +* [Is tree balanced](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem65/IsTreeBalanced.java) +* [Generate list with nodes by level](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem66/TreeToListByLevel.java) ### Linked List -* [Reverse linked list] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem22/ReverseLinkedList.java) -* [Remove duplicates] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem57/RemoveListDuplicatedElements.java) -* [Find kth element] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem58/FindKthElement.java) -* [Delete list node] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem59/DeleteListNode.java) -* [Partition list] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem60/PartitionList.java) -* [Sum lists] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem61/SumLists.java) -* [PalindromeList] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem62/PalindromeList.java) -* [Get element in the middle of the list] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem64/GetTheElementInTheMiddleOfTheList.java) +* [Reverse linked list](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem22/ReverseLinkedList.java) +* [Remove duplicates](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem57/RemoveListDuplicatedElements.java) +* [Find kth element](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem58/FindKthElement.java) +* [Delete list node](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem59/DeleteListNode.java) +* [Partition list](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem60/PartitionList.java) +* [Sum lists](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem61/SumLists.java) +* [PalindromeList](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem62/PalindromeList.java) +* [Get element in the middle of the list](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem64/GetTheElementInTheMiddleOfTheList.java) ### Strings -* [Int to String] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem11/IntToString.java) -* [Remove comments from file] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem23/RemoveComments.java) -* [Reverse sentence] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem27/ReverseSentence.java) -* [Contains] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem32/Contains.java) -* [Simple regular expression] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem33/SimpleRegularExpression.java) -* [Dot regular expression] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem34/DotRegularExpression.java) -* [Asterisk regular expression] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem35/AsteriskRegularExpression.java) -* [Unique chars] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem50/UniqueChars.java) -* [Reverse string] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem51/ReverseString.java) -* [Compress string] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem53/CompressString.java) -* [Is rotation using substring] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem56/IsRotationUsingIsSubstring.java) +* [Int to String](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem11/IntToString.java) +* [Remove comments from file](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem23/RemoveComments.java) +* [Reverse sentence](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem27/ReverseSentence.java) +* [Contains](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem32/Contains.java) +* [Simple regular expression](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem33/SimpleRegularExpression.java) +* [Dot regular expression](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem34/DotRegularExpression.java) +* [Asterisk regular expression](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem35/AsteriskRegularExpression.java) +* [Unique chars](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem50/UniqueChars.java) +* [Reverse string](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem51/ReverseString.java) +* [Compress string](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem53/CompressString.java) +* [Is rotation using substring](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem56/IsRotationUsingIsSubstring.java) ### Binary Numbers and bits operators -* [Is binary number even?] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem68/IsEven.java) -* [Sum binary numbers] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem3/SumBinaryNumbers.java) -* [Count the number of bits equals to 1] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java) -* [Merge binary numbers] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem67/MergeBinaryNumbers.java) -* [Count the number of different bits] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem69/BitsToTransform.java) -* [Reverse binary number order] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java) -* [Reverse binary number] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem71/ReverseBinaryNumber.java) +* [Is binary number even?](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem68/IsEven.java) +* [Sum binary numbers](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem3/SumBinaryNumbers.java) +* [Count the number of bits equals to 1](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java) +* [Merge binary numbers](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem67/MergeBinaryNumbers.java) +* [Count the number of different bits](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem69/BitsToTransform.java) +* [Reverse binary number order](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem70/ReverseOrderOfBinaryNumber.java) +* [Reverse binary number](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem71/ReverseBinaryNumber.java) ### Math Operations -* [Square root] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java) -* [Divide using subtraction] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem5/DivideUsingSubtraction.java) -* [Multiplication without multiply] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java) -* [Find sums] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem28/FindSums.java) -* [ScientificNotation] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem30/ScientificNotation.java) -* [Vector scalar product] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem2/VectorScalarProduct.java) -* [Subtract adding] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem73/SubtractAdding.java) +* [Square root](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java) +* [Divide using subtraction](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem5/DivideUsingSubtraction.java) +* [Multiplication without multiply](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem20/MultiplicationWithoutMultiply.java) +* [Find sums](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem28/FindSums.java) +* [ScientificNotation](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem30/ScientificNotation.java) +* [Vector scalar product](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem2/VectorScalarProduct.java) +* [Subtract adding](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem73/SubtractAdding.java) ### Sequences -* [Fibonacci numbers] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java) -* [Factorial] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem9/Factorial.java) +* [Fibonacci numbers](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem7/FibonacciNumbers.java) +* [Factorial](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem9/Factorial.java) ### Arrays -* [Merge sorted arrays] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem6/MergeSortedArrays.java) -* [Split array in positive and negative numbers] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem8/SplitArray.java) -* [Remove duplicated elements] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java) -* [Move zeros in array] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java) -* [Find longest consecutive sequence] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem31/FindLongestConsecutiveSequence.java) -* [Multiply array elements] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem39/MultiplyArrayElements.java) -* [Move elements to position] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem40/MoveElementsToPositions.java) -* [Replace spaces] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem52/ReplaceSpaces.java) -* [Rotate matrix] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem54/RotateMatrix.java) -* [Rewrite row and columns with zero] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem55/RewriteRowAndColumnsWithZeros.java) -* [Find the missing number] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem72/FindTheMissingNumber.java) +* [Merge sorted arrays](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem6/MergeSortedArrays.java) +* [Split array in positive and negative numbers](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem8/SplitArray.java) +* [Remove duplicated elements](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java) +* [Move zeros in array](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java) +* [Find longest consecutive sequence](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem31/FindLongestConsecutiveSequence.java) +* [Multiply array elements](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem39/MultiplyArrayElements.java) +* [Move elements to position](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem40/MoveElementsToPositions.java) +* [Replace spaces](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem52/ReplaceSpaces.java) +* [Rotate matrix](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem54/RotateMatrix.java) +* [Rewrite row and columns with zero](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem55/RewriteRowAndColumnsWithZeros.java) +* [Find the missing number](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem72/FindTheMissingNumber.java) ### Sorting Algorithms -* [Bubble Sort] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem74/BubbleSort.java) -* [Selection Sort] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem75/SelectionSort.java) -* [Insertion Sort] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem76/InsertionSort.java) -* [Merge Sort] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem79/MergeSort.java) +* [Bubble Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem74/BubbleSort.java) +* [Selection Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem75/SelectionSort.java) +* [Insertion Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem76/InsertionSort.java) +* [Merge Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem79/MergeSort.java) ### Misc -* [Anagrams] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem25/Anagrams.java) -* [Palindromes] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem26/Palindromes.java) -* [Are anagrams?] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java) -* [Constant complexity order stack] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem63/ConstantComplexityOrderStack.java) -* [Hello world without semicolon] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem77/HelloWorldWithoutSemicolon.java) -* [Autoboxing trick] (https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem78/AutoBoxingTrick.java) +* [Anagrams](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem25/Anagrams.java) +* [Palindromes](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem26/Palindromes.java) +* [Are anagrams?](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java) +* [Constant complexity order stack](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem63/ConstantComplexityOrderStack.java) +* [Hello world without semicolon](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem77/HelloWorldWithoutSemicolon.java) +* [Autoboxing trick](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem78/AutoBoxingTrick.java) Developed By ------------ From a62617e239a5241715cfa07455547035c63a97e8 Mon Sep 17 00:00:00 2001 From: Jitendra Singh Date: Mon, 1 May 2017 17:04:59 +0530 Subject: [PATCH 06/22] added quick sort (#32) * added quick sort * remove main method * extended sorting algorithm * added test case and style * indetation update * typo and override removed --- README.md | 2 + .../github/pedrovgs/problem80/QuickSort.java | 75 +++++++++++++++++++ .../pedrovgs/problem80/QuickSortTest.java | 29 +++++++ 3 files changed, 106 insertions(+) create mode 100644 src/main/java/com/github/pedrovgs/problem80/QuickSort.java create mode 100644 src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java diff --git a/README.md b/README.md index a6eee869..f6de99a1 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,8 @@ Problems * [Selection Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem75/SelectionSort.java) * [Insertion Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem76/InsertionSort.java) * [Merge Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem79/MergeSort.java) +* [Quick Sort](https://github.com/pedrovgs/Algorithms/blob/master/src/main/java/com/github/pedrovgs/problem80/QuickSort.java) + ### Misc diff --git a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java new file mode 100644 index 00000000..768c01b2 --- /dev/null +++ b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.github.pedrovgs.problem79; + +import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm; + +/** + * Given an array full of integers implement a quick sort algorithm to sort the content inside + * the array. + * + * @author jsroyal + */ + +/** + * Quick sort takes advantage for avarage case which O(nlogn); + * It starts by comparing every two and so on.Final got sort list of the algorithms described here, + * this is the first that + * scales well to very large lists, because its worst-case running time is O(n^2). It is also + * easily applied to lists, not only arrays, as it only requires sequential access, not random + * access. However, it has additional O(n) space complexity, and involves a large number of + * copies in simple implementations. + */ + +public class QuickSort extends SortingAlgorithm { + + private int[] numbers; + private int number; + + @Override public void sort(int[] numbers) { + validateInput(numbers); + + this.numbers = numbers; + number = numbers.length; + quickSort(numbers, 0, number - 1); + } + + private static int partition(int[] a, int l, int r) { + int pivot = a[r]; + while (l < r) { + while (a[l] < pivot) { //from left move + l++; + } + while (a[r] > pivot) { //from right move + r--; + } + if (l <= r) { + int temp = a[l]; + a[l] = a[r]; + a[r] = temp; + } + } + return l; //pivot index + } + + public static void quickSort(int[] a, int left, int right) { + if (left < right) { + int pi = partition(a, left, right); //pi index of pivot + quickSort(a, left, pi - 1); //sort left of pivot + quickSort(a, pi, right); //sort right of pivot + } + } +} diff --git a/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java new file mode 100644 index 00000000..1fda061f --- /dev/null +++ b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2014 Pedro Vicente Gómez Sánchez. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.github.pedrovgs.problem79; + +import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm; +import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest; + +/** + * @author jsroyal. + */ +public class QuickSortTest extends SortingAlgorithmTest { + + @Override public SortingAlgorithm getSortingAlgorithm() { + return new QuickSort(); + } +} From b7ebed2e341fec197c4b9838e66798c55fae659f Mon Sep 17 00:00:00 2001 From: pedrovgs Date: Mon, 1 May 2017 13:43:11 +0200 Subject: [PATCH 07/22] Improve problem80 code style and implementation fixing the package configuration, renaming some variables, using a different javadoc and changing some methods modifiers from public static to private --- .../github/pedrovgs/problem80/QuickSort.java | 76 +++++++++---------- .../pedrovgs/problem80/QuickSortTest.java | 3 +- 2 files changed, 40 insertions(+), 39 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java index 768c01b2..ca2899f9 100644 --- a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java +++ b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.pedrovgs.problem79; +package com.github.pedrovgs.problem80; import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm; @@ -23,53 +23,53 @@ * * @author jsroyal */ - -/** - * Quick sort takes advantage for avarage case which O(nlogn); - * It starts by comparing every two and so on.Final got sort list of the algorithms described here, - * this is the first that - * scales well to very large lists, because its worst-case running time is O(n^2). It is also - * easily applied to lists, not only arrays, as it only requires sequential access, not random - * access. However, it has additional O(n) space complexity, and involves a large number of - * copies in simple implementations. - */ - public class QuickSort extends SortingAlgorithm { - private int[] numbers; - private int number; - + /** + * Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving + * as a systematic method for placing the elements of an array in order. Developed by Tony Hoare + * in 1959 and published in 1961, it is still a commonly used algorithm for sorting. When + * implemented well, it can be about two or three times faster than its main competitors, merge + * sort and heapsort. + * + * Quicksort is a comparison sort, meaning that it can sort items of any type for which a + * "less-than" relation (formally, a total order) is defined. In efficient implementations it is + * not a stable sort, meaning that the relative order of equal sort items is not preserved. + * Quicksort can operate in-place on an array, requiring small additional amounts of memory to + * perform the sorting. + * + * Mathematical analysis of quicksort shows that, on average, the algorithm takes O(n log n) + * comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this + * behavior is rare. + */ @Override public void sort(int[] numbers) { validateInput(numbers); + quickSort(numbers, 0, numbers.length - 1); + } - this.numbers = numbers; - number = numbers.length; - quickSort(numbers, 0, number - 1); + private void quickSort(int[] numbers, int left, int right) { + if (left < right) { + int pivotIndex = partition(numbers, left, right); + quickSort(numbers, left, pivotIndex - 1); //sort left of pivot + quickSort(numbers, pivotIndex, right); //sort right of pivot + } } - private static int partition(int[] a, int l, int r) { - int pivot = a[r]; - while (l < r) { - while (a[l] < pivot) { //from left move - l++; + private int partition(int[] numbers, int left, int right) { + int pivot = numbers[right]; + while (left < right) { + while (numbers[left] < pivot) { + left++; } - while (a[r] > pivot) { //from right move - r--; + while (numbers[right] > pivot) { + right--; } - if (l <= r) { - int temp = a[l]; - a[l] = a[r]; - a[r] = temp; + if (left <= right) { + int temp = numbers[left]; + numbers[left] = numbers[right]; + numbers[right] = temp; } } - return l; //pivot index - } - - public static void quickSort(int[] a, int left, int right) { - if (left < right) { - int pi = partition(a, left, right); //pi index of pivot - quickSort(a, left, pi - 1); //sort left of pivot - quickSort(a, pi, right); //sort right of pivot - } + return left; //pivot index } } diff --git a/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java index 1fda061f..0cbb5b66 100644 --- a/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java +++ b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java @@ -13,8 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.github.pedrovgs.problem79; +package com.github.pedrovgs.problem80; +import com.github.pedrovgs.problem79.QuickSort; import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm; import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest; From 6baa2ed219e18f9763bb2f2de74c5fb800d15899 Mon Sep 17 00:00:00 2001 From: pedrovgs Date: Mon, 1 May 2017 13:44:34 +0200 Subject: [PATCH 08/22] Remove wrong import --- src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java index 0cbb5b66..510195e1 100644 --- a/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java +++ b/src/test/java/com/github/pedrovgs/problem80/QuickSortTest.java @@ -15,7 +15,6 @@ */ package com.github.pedrovgs.problem80; -import com.github.pedrovgs.problem79.QuickSort; import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm; import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest; From 8b2e3b06185e4a111ae987db7fa01901974036cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20Vicente=20G=C3=B3mez=20S=C3=A1nchez?= Date: Mon, 12 Jun 2017 19:47:20 +0200 Subject: [PATCH 09/22] Add a new case showing an error in the implementation and reimplement the algorithm (#35) --- .../pedrovgs/problem29/AreAnagrams.java | 38 +++++-------------- .../pedrovgs/problem29/AreAnagramsTest.java | 5 +++ 2 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java b/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java index 48b9195f..fe9e6223 100644 --- a/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java +++ b/src/main/java/com/github/pedrovgs/problem29/AreAnagrams.java @@ -15,6 +15,8 @@ */ package com.github.pedrovgs.problem29; +import java.util.Arrays; + /** * Given two Strings passed as parameter, can you write a method to return true if this words are * anagrams? @@ -30,13 +32,9 @@ public class AreAnagrams { /** * Iterative algorithm to solve this problem. Two words are anagrams just if contains the same - * number of letters. Using this property, we are going to calculate the number of letters per - * word and check if the sum is the same. We have used an array of int to represent the letters - * counter. The complexity order of this algorithm is O(N) where N is the number of letters in - * the largest word. In space terms, the complexity order of this algorithm is O(M), where M is - * the number of different letters in the alphabet (we assume ascii, 128 different letters), - * because we need an additional data structure to store information related to the letters - * counter. + * number of letters. Using this property, we are going to sort and compare the letters inside + * the array. The complexity order of this algorithm is O(N*Log(N)) where N is the number of + * letters in the largest word. In space terms, the complexity order of this algorithm is O(N). */ public boolean check(String a, String b) { if (a == null || b == null) { @@ -45,28 +43,12 @@ public boolean check(String a, String b) { if (a.length() != b.length()) { return false; } - int[] lettersA = getLettersAsArray(a); - int[] lettersB = getLettersAsArray(b); - - int valuesA = getSumOfArray(lettersA); - int valuesB = getSumOfArray(lettersB); - - return valuesA == valuesB; + char[] charsA = a.toCharArray(); + Arrays.sort(charsA); + char[] charsB = b.toCharArray(); + Arrays.sort(charsB); + return Arrays.equals(charsA, charsB); } - private static int getSumOfArray(int[] array) { - int count = 0; - for (int n : array) { - count += n; - } - return count; - } - private static int[] getLettersAsArray(String word) { - int[] letters = new int[128]; - for (char c : word.toCharArray()) { - letters[c] = letters[c] + 1; - } - return letters; - } } diff --git a/src/test/java/com/github/pedrovgs/problem29/AreAnagramsTest.java b/src/test/java/com/github/pedrovgs/problem29/AreAnagramsTest.java index 0a4d558c..017114c1 100644 --- a/src/test/java/com/github/pedrovgs/problem29/AreAnagramsTest.java +++ b/src/test/java/com/github/pedrovgs/problem29/AreAnagramsTest.java @@ -51,4 +51,9 @@ public class AreAnagramsTest { @Test public void shouldReturnTrueIfWordsAreAnagrams() { assertTrue(areAnagrams.check("ana", "naa")); } + + @Test + public void shouldReturnFalseEvenIfTheSumOfTheCharsIsEqual() throws Exception { + assertFalse(areAnagrams.check("abc", "efg")); + } } From 9ae21a5c070c9a97e05ef56b2d1f6d764b609f9e Mon Sep 17 00:00:00 2001 From: Bao Hexing Date: Thu, 2 Nov 2017 20:46:59 +0800 Subject: [PATCH 10/22] Two bugs fix + two typo + one test (#38) * Fix bottom increasement instead of decrement in SquareRoot * Fix typo * Fix typo * Add moveSorting test and fix swap condition in it's implementation --- .../com/github/pedrovgs/problem10/RemoveDuplicates.java | 2 +- .../com/github/pedrovgs/problem12/MoveZerosInArray.java | 2 +- .../com/github/pedrovgs/problem13/BinaryTreeByLevel.java | 2 +- .../java/com/github/pedrovgs/problem4/SquareRoot.java | 2 +- .../github/pedrovgs/problem12/MoveZerosInArrayTest.java | 8 ++++++++ 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java b/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java index e9b0ab7b..aaf1a93e 100644 --- a/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java +++ b/src/main/java/com/github/pedrovgs/problem10/RemoveDuplicates.java @@ -26,7 +26,7 @@ * Given an array full of integers, can you write a method returning other array without duplicated * elements? The elements order doesn't care. For example: * - * Input: [1,2,3,1] Output: [1,1,12] + * Input: [1,2,3,1] Output: [1,2,3] * Input: [1,1,1,1,1] Output: [1] * * @author Pedro Vicente Gómez Sánchez. diff --git a/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java b/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java index a8e942a9..ab63ed3b 100644 --- a/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java +++ b/src/main/java/com/github/pedrovgs/problem12/MoveZerosInArray.java @@ -39,7 +39,7 @@ public void moveSorting(int[] array) { while (swap) { swap = false; for (int i = 0; i < array.length - 1; i++) { - if ((array[i] < array[i + 1] && array[i + 1] > 0)) { + if (array[i] == 0 && array[i + 1] != 0) { swap(array, i, i + 1); swap = true; } diff --git a/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java b/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java index bf01de52..b0ef3792 100644 --- a/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java +++ b/src/main/java/com/github/pedrovgs/problem13/BinaryTreeByLevel.java @@ -31,7 +31,7 @@ public class BinaryTreeByLevel { /** * Add implementation based on an additional data structure, one queue which implementation is a - * LinkedList. We we are going to do is add elements of the tree to the queue and one by one + * LinkedList. What we are going to do is add elements of the tree to the queue and one by one * evaluate it adding more binary nodes to the queue if exist. The complexity order in time terms * is O(N) where N is the number of elements in the tree. The complexity order in space terms is * O(N) where N is the number of elements in the tree because we are going to store every node in diff --git a/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java b/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java index 809da1e1..aac43949 100644 --- a/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java +++ b/src/main/java/com/github/pedrovgs/problem4/SquareRoot.java @@ -61,7 +61,7 @@ public float calculateSquareRootIterative(int number) { if (result > number) { top -= 0.1f; } else { - bottom -= 0.1f; + bottom += 0.1f; } newCandidate = (top + bottom) / 2; result = newCandidate * newCandidate; diff --git a/src/test/java/com/github/pedrovgs/problem12/MoveZerosInArrayTest.java b/src/test/java/com/github/pedrovgs/problem12/MoveZerosInArrayTest.java index 2865ed0e..99f85628 100644 --- a/src/test/java/com/github/pedrovgs/problem12/MoveZerosInArrayTest.java +++ b/src/test/java/com/github/pedrovgs/problem12/MoveZerosInArrayTest.java @@ -44,6 +44,14 @@ public class MoveZerosInArrayTest { assertArrayEquals(new int[0], array); } + @Test public void shouldWorkWithPositiveNegativeZerosArraySorting() { + int[] array = {-1, 0, 2, 4, 0, -3, -5, 0, 6, -3, 0}; + + moveZeros.moveSorting(array); + + assertZerosAtRight(array); + } + @Test public void shouldOrganizeAnArrayFullOfZerosSorting() { int[] array = { 0, 0, 0, 0, 0 }; From 7729e8135393710083184ce6ab6a8a1faebd447b Mon Sep 17 00:00:00 2001 From: Lucian Nut <32246745+nlucian@users.noreply.github.com> Date: Fri, 14 Dec 2018 12:35:37 +0200 Subject: [PATCH 11/22] Bit counter will work for signed ints (#41) * Bit counter works for signed ints also * Removed unnecesarry assignment; Added toString; * Modified tests to comply with the new changes * Refactoring on spaces * tests for bits in 0 and negative numbers * Brian Kernighan bit counting algorithm --- .../github/pedrovgs/problem1/BitsCounter.java | 21 +++++++++++-- .../com/github/pedrovgs/problem2/Vector.java | 17 +++++++---- .../pedrovgs/problem1/BitsCounterTest.java | 30 +++++++++++++++++-- .../problem2/VectorScalarProductTest.java | 6 +++- 4 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java b/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java index c6e57679..93a4d084 100644 --- a/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java +++ b/src/main/java/com/github/pedrovgs/problem1/BitsCounter.java @@ -66,10 +66,27 @@ public int countBitsToOneBasedOnString(int n) { */ public int countBitsToOneBasedOnBinaryOperators(int n) { int result = 0; - while (n > 0) { + while (n != 0) { result += (n & 1) == 1 ? 1 : 0; - n = n >> 1; + n = n >>> 1; } return result; } + + /** + * Brian Kernighan's method goes through as many iterations as there are set bits. + * So if we have a 32-bit word with only the high bit set, + * then it will only go once through the loop. + * + * @param x + * @return + */ + public static int countNumberOfBitsLogN(int x) { + int result = 0; + while (x != 0) { + x &= (x - 1); + result++; + } + return result; + } } diff --git a/src/main/java/com/github/pedrovgs/problem2/Vector.java b/src/main/java/com/github/pedrovgs/problem2/Vector.java index d1f0e258..7b3e1fa1 100644 --- a/src/main/java/com/github/pedrovgs/problem2/Vector.java +++ b/src/main/java/com/github/pedrovgs/problem2/Vector.java @@ -15,6 +15,8 @@ */ package com.github.pedrovgs.problem2; +import java.util.Arrays; + /** * Class created to represent a Vector of integers. This class uses an array as main data structure * because the number of elements inside a vector can't change and we can provide constant @@ -29,12 +31,12 @@ public class Vector { private final int[] elements; - public Vector(int... elements) { - if (elements == null) { - elements = new int[0]; + public Vector(int... elements) { + if (elements == null) { + throw new IllegalArgumentException("Vector constructor should not receive null values."); + } + this.elements = elements; } - this.elements = elements; - } public int getAt(int index) { return elements[index]; @@ -43,4 +45,9 @@ public int getAt(int index) { public int size() { return elements.length; } + + @Override + public String toString() { + return Arrays.toString(elements); + } } diff --git a/src/test/java/com/github/pedrovgs/problem1/BitsCounterTest.java b/src/test/java/com/github/pedrovgs/problem1/BitsCounterTest.java index 4d93551d..7ff406d3 100644 --- a/src/test/java/com/github/pedrovgs/problem1/BitsCounterTest.java +++ b/src/test/java/com/github/pedrovgs/problem1/BitsCounterTest.java @@ -67,7 +67,33 @@ public class BitsCounterTest { assertEquals(3, bitsCounter.countBitsToOneBasedOnBinaryOperators(7)); } - @Test public void numberOfBitsIn1990IsSevenBasedOnBinaryOperator() { - assertEquals(7, bitsCounter.countBitsToOneBasedOnBinaryOperators(1990)); + /** + * A negative number is represented by calculating its complement and adding 1 to + * the result (Two's complement). + * eg. ~7 + 1 + */ + @Test + public void numberOfBitsInNegativeSevenIsThreeBasedOnBinaryOperator() { + assertEquals(30, bitsCounter.countBitsToOneBasedOnBinaryOperators(-7)); + } + + @Test + public void numberOfBitsInZero() { + assertEquals(0, bitsCounter.countBitsToOneBasedOnBinaryOperators(0)); } + + @Test + public void numberOfBitsInZeroKernighanMethod() { + assertEquals(0, bitsCounter.countNumberOfBitsLogN(0)); + } + + @Test + public void numberOfBitsInNegativeIntegerKernighanMethod() { + assertEquals(30, bitsCounter.countNumberOfBitsLogN(-7)); + } + + @Test public void numberOfBitsKernighanMethod() { + assertEquals(3, bitsCounter.countBitsToOneBasedOnBinaryOperators(7)); + } + } diff --git a/src/test/java/com/github/pedrovgs/problem2/VectorScalarProductTest.java b/src/test/java/com/github/pedrovgs/problem2/VectorScalarProductTest.java index a129bc74..8cf5e310 100644 --- a/src/test/java/com/github/pedrovgs/problem2/VectorScalarProductTest.java +++ b/src/test/java/com/github/pedrovgs/problem2/VectorScalarProductTest.java @@ -45,7 +45,11 @@ public void differentSizeVectorsShouldThrowException() { vectorScalarProduct.calculateScalarProduct(v1, null); } - @Test public void shoudlReturnZeroIfVectorsAreEmpty() { + @Test public void shouldReturnZeroIfVectorsAreEmpty() { + assertEquals(0, vectorScalarProduct.calculateScalarProduct(new Vector(), new Vector())); + } + + @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfVectorsAreNull() { assertEquals(0, vectorScalarProduct.calculateScalarProduct(new Vector(null), new Vector(null))); } From 4e2214112de23d1319ce77736547fa8900384e7c Mon Sep 17 00:00:00 2001 From: Lucas Prone <3941841+lprone@users.noreply.github.com> Date: Sun, 10 Feb 2019 17:22:59 -0300 Subject: [PATCH 12/22] Better variable definition on BinaryTreeSerialization and PathCalculator classes (#50) --- .../java/com/github/pedrovgs/problem37/PathCalculator.java | 2 +- .../github/pedrovgs/problem46/BinaryTreeSerialization.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java b/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java index 8408a60f..c53fa0bb 100644 --- a/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java +++ b/src/main/java/com/github/pedrovgs/problem37/PathCalculator.java @@ -27,7 +27,7 @@ */ public class PathCalculator { - public static final String DIR_SEPARATOR = "/"; + private static final String DIR_SEPARATOR = "/"; /** * Iterative algorithm to solve this problem. The complexity order of this algorithm is O(N+M+Ñ) diff --git a/src/main/java/com/github/pedrovgs/problem46/BinaryTreeSerialization.java b/src/main/java/com/github/pedrovgs/problem46/BinaryTreeSerialization.java index 8a0382a3..8f98a76d 100644 --- a/src/main/java/com/github/pedrovgs/problem46/BinaryTreeSerialization.java +++ b/src/main/java/com/github/pedrovgs/problem46/BinaryTreeSerialization.java @@ -25,6 +25,8 @@ */ public class BinaryTreeSerialization { + private int index; + public BinaryTreeSerialization() { index = 0; } @@ -51,8 +53,6 @@ private String serializeInner(BinaryNode root) { return stringBuilder.toString(); } - static int index = 0; - /** * Recursive algorithm based a static index to recreate the original tree properly. The * complexity order of this algorithm is O(N) where N is the number of chars in the input String. From ed6f8a49948c09a21bfeb7bc38b4f24141795e38 Mon Sep 17 00:00:00 2001 From: LHearen Date: Sun, 14 Apr 2019 18:55:14 +0800 Subject: [PATCH 13/22] fix quick sort partition for special inputs and update testcase (#52) --- .../github/pedrovgs/problem80/QuickSort.java | 18 ++++++------------ .../SortingAlgorithmTest.java | 11 +++++++++++ 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java index ca2899f9..af8d1627 100644 --- a/src/main/java/com/github/pedrovgs/problem80/QuickSort.java +++ b/src/main/java/com/github/pedrovgs/problem80/QuickSort.java @@ -57,19 +57,13 @@ private void quickSort(int[] numbers, int left, int right) { private int partition(int[] numbers, int left, int right) { int pivot = numbers[right]; - while (left < right) { - while (numbers[left] < pivot) { - left++; - } - while (numbers[right] > pivot) { - right--; - } - if (left <= right) { - int temp = numbers[left]; - numbers[left] = numbers[right]; - numbers[right] = temp; + int i = left - 1; + for (int j = left; j < right; ++j) { + if (numbers[j] <= pivot) { + swap(numbers, ++i, j); } } - return left; //pivot index + swap(numbers, ++i, right); + return i; } } diff --git a/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java b/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java index f57e22d1..59e70cbe 100644 --- a/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java +++ b/src/test/java/com/github/pedrovgs/sortingalgorithms/SortingAlgorithmTest.java @@ -79,4 +79,15 @@ public abstract class SortingAlgorithmTest { int[] expectedArray = { 1, 2, 3, 4 }; assertArrayEquals(expectedArray, input); } + + @Test(timeout = 5 * 1000) + public void shouldSortSpecialArray() { + int[] input = {12, -37, -5, 43, 62, 45, -95, -70, -55, -62, -24, -14, + -75, 43, 9, 58, -62, -22, -55}; + + sortingAlgorithm.sort(input); + + int[] expectedArray = {-95, -75, -70, -62, -62, -55, -55, -37, -24, -22, -14, -5, 9, 12, 43, 43, 45, 58, 62}; + assertArrayEquals(expectedArray, input); + } } From 9b2d15fa9ec0151383e30a0777857e5e21eb33e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20Vicente=20G=C3=B3mez=20S=C3=A1nchez?= Date: Wed, 4 Dec 2019 01:02:35 +0100 Subject: [PATCH 14/22] Update .travis.yml (#62) --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index b1048c7d..57c97914 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: java +jdk: openjdk8 install: mvn clean install From 34392b17417f48af79c61e3c6f5e050786490b9a Mon Sep 17 00:00:00 2001 From: BryanChan777 <43082778+BryanChan777@users.noreply.github.com> Date: Tue, 3 Dec 2019 16:04:02 -0800 Subject: [PATCH 15/22] Update README.md (#61) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f6de99a1..4f9443f6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ Algorithms [![Build Status](https://travis-ci.org/pedrovgs/Algorithms.svg?branch=master)](https://travis-ci.org/pedrovgs/Algorithms) ========== -This repository contains my solution for some common algorithms. I've created this repository to learn about algorithms and improve solving different common computer science problems. I'll try to add more solutions if I have time :) +This repository contains my solution for common algorithms. I've created this repository to learn about algorithms and improve solutions to common computer science problems. I'll try to add more solutions if I have time. :) -Each solved problem has a program written in Java. Every solution is tested and some problems contains more than one solution with different implementations. +Each solution has a Java program and is tested. Some problems contain mulitple solutions with different implementations. -You can check the solution executing tests inside tests directory. Some of this problems have been resolved using TDD. +You can check the solution executing tests inside tests directory. Some problems were resolved using TDD. Problems -------- From 8c92aa6bbab7548ef7c8989e2a0de2e76c552a41 Mon Sep 17 00:00:00 2001 From: contextshuffling <55522232+contextshuffling@users.noreply.github.com> Date: Mon, 17 Aug 2020 12:35:51 -0500 Subject: [PATCH 16/22] Use LinkedHashMap for deterministic iterations (#63) Great thanks @contextshuffling ! --- .../github/pedrovgs/problem45/FindNthMostRepeatedElement.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/github/pedrovgs/problem45/FindNthMostRepeatedElement.java b/src/main/java/com/github/pedrovgs/problem45/FindNthMostRepeatedElement.java index 7df18a76..73462028 100644 --- a/src/main/java/com/github/pedrovgs/problem45/FindNthMostRepeatedElement.java +++ b/src/main/java/com/github/pedrovgs/problem45/FindNthMostRepeatedElement.java @@ -15,7 +15,7 @@ */ package com.github.pedrovgs.problem45; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; /** @@ -33,7 +33,7 @@ public class FindNthMostRepeatedElement { public int find(int[] numbers, int position) { validateInput(numbers, position); Integer result = null; - Map counter = new HashMap(); + Map counter = new LinkedHashMap(); for (int i : numbers) { if (counter.get(i) == null) { counter.put(i, 1); From 6c0e3616ca17385a82a3c13526ef980a426d309a Mon Sep 17 00:00:00 2001 From: Alaz Tetik Date: Mon, 9 Nov 2020 18:33:19 +0300 Subject: [PATCH 17/22] Fix a misspelled word in readme (#65) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4f9443f6..86d8ee84 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Algorithms [![Build Status](https://travis-ci.org/pedrovgs/Algorithms.svg?branch This repository contains my solution for common algorithms. I've created this repository to learn about algorithms and improve solutions to common computer science problems. I'll try to add more solutions if I have time. :) -Each solution has a Java program and is tested. Some problems contain mulitple solutions with different implementations. +Each solution has a Java program and is tested. Some problems contain multiple solutions with different implementations. You can check the solution executing tests inside tests directory. Some problems were resolved using TDD. From 509d63fe5d98eaa2d057d2d681da109ad1fe6eb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20G=C3=B3mez?= Date: Wed, 29 Sep 2021 21:26:23 +0200 Subject: [PATCH 18/22] Create FUNDING.yml --- .github/FUNDING.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/FUNDING.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..2e48a7b5 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +GitHub: [pedrovgs] From 6b471dce28ce9625aef33f4cc3ac4c4c0b971192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20G=C3=B3mez?= Date: Wed, 29 Sep 2021 21:27:16 +0200 Subject: [PATCH 19/22] Update FUNDING.yml --- .github/FUNDING.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 2e48a7b5..fff48659 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1,3 @@ -GitHub: [pedrovgs] +# These are supported funding model platforms + +github: [pedrovgs] From 3ec71383047eb9b82589e3497831b80cf347c9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20G=C3=B3mez?= Date: Tue, 7 Jun 2022 21:10:00 +0200 Subject: [PATCH 20/22] Create gh actions workflow (#81) * Create gh actions workflow * Fix typo * Back to java 8 --- .github/workflows/check.yml | 20 ++++++++++++++++++++ .travis.yml | 6 ------ 2 files changed, 20 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/check.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 00000000..9e7c41b0 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,20 @@ +name: QA check + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 8 + uses: actions/setup-java@v3 + with: + java-version: '8' + distribution: 'temurin' + - name: Check java checkstyle + run: mvn checkstyle:checkstyle + + - name: Test + run: mvn install diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 57c97914..00000000 --- a/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: java -jdk: openjdk8 - -install: mvn clean install - -script: mvn checkstyle:checkstyle From c108e3a4b4fa2556b8c88d7ab6803084b01a4364 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20G=C3=B3mez?= Date: Tue, 7 Jun 2022 21:10:53 +0200 Subject: [PATCH 21/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 86d8ee84..603771a2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Algorithms [![Build Status](https://travis-ci.org/pedrovgs/Algorithms.svg?branch=master)](https://travis-ci.org/pedrovgs/Algorithms) +Algorithms [![QA check](https://github.com/pedrovgs/Algorithms/actions/workflows/check.yml/badge.svg)](https://github.com/pedrovgs/Algorithms/actions/workflows/check.yml) ========== This repository contains my solution for common algorithms. I've created this repository to learn about algorithms and improve solutions to common computer science problems. I'll try to add more solutions if I have time. :) From b04396ba1a8bf094494f9ba514ecbe806fdb9776 Mon Sep 17 00:00:00 2001 From: java-codehunger <119823377+java-codehunger@users.noreply.github.com> Date: Tue, 2 May 2023 05:11:01 -0500 Subject: [PATCH 22/22] Ignoring unnecessarily generated site directory (#91) Co-authored-by: other --- .github/workflows/check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 9e7c41b0..14d8c5ee 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -14,7 +14,7 @@ jobs: java-version: '8' distribution: 'temurin' - name: Check java checkstyle - run: mvn checkstyle:checkstyle + run: mvn checkstyle:check - name: Test run: mvn install