From ca17a0db74d485c0420849d97acb21cf554bc33e Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 10:10:13 +0330 Subject: [PATCH 01/12] add cs checking to ci flow --- .github/workflows/ci.yml | 32 ++++++++++++++++---------------- .github/workflows/code-style.yml | 25 +++++++++++++++++++++++++ .gitignore | 3 +++ composer.json | 3 ++- phpcs.xml.dist | 9 +++++++++ 5 files changed, 55 insertions(+), 17 deletions(-) create mode 100644 .github/workflows/code-style.yml create mode 100644 phpcs.xml.dist diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 014f753..076bab2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,23 +12,23 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v2 - - name: Validate composer.json and composer.lock - run: composer validate + - name: Validate composer.json and composer.lock + run: composer validate - - name: Cache Composer packages - id: composer-cache - uses: actions/cache@v2 - with: - path: vendor - key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} - restore-keys: | - ${{ runner.os }}-php- + - name: Cache Composer packages + id: composer-cache + uses: actions/cache@v2 + with: + path: vendor + key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-php- - - name: Install dependencies - if: steps.composer-cache.outputs.cache-hit != 'true' - run: composer install --prefer-dist --no-progress --no-suggest + - name: Install dependencies + if: steps.composer-cache.outputs.cache-hit != 'true' + run: composer install --prefer-dist --no-progress --no-suggest - - name: Run PHPUnit - run: composer run-script test + - name: Run PHPUnit + run: composer run-script test \ No newline at end of file diff --git a/.github/workflows/code-style.yml b/.github/workflows/code-style.yml new file mode 100644 index 0000000..16ab9a5 --- /dev/null +++ b/.github/workflows/code-style.yml @@ -0,0 +1,25 @@ +name: Code style + +on: [push, pull_request] + +permissions: + contents: read + +jobs: + phpcs: + name: PHPCS + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '7.4' + + - name: Install dependencies + run: composer update --prefer-dist --no-progress --no-suggest + + - name: Run script + run: vendor/bin/phpcs \ No newline at end of file diff --git a/.gitignore b/.gitignore index 96ccab4..8e409f4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,7 @@ .phan composer.lock +/.phpcs-cache +/phpcs.xml + .phpunit.result.cache \ No newline at end of file diff --git a/composer.json b/composer.json index d164a22..e3ca6e6 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,8 @@ "phan/phan": "^2.7" }, "require-dev": { - "phpunit/phpunit": "^9" + "phpunit/phpunit": "^9", + "squizlabs/php_codesniffer": "^3.7" }, "scripts": { "test": "vendor/bin/phpunit tests" diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..1540549 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,9 @@ + + + + + + + . + From d7d34e357e36b538d0a26786f2cc38bfc52f7028 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 11:12:26 +0330 Subject: [PATCH 02/12] excluding namespace errors from cs check --- phpcs.xml.dist | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 1540549..3106956 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -6,4 +6,8 @@ . + + + 0 + From 9c2726203cad27fd7834287bb9789126d3d7cd55 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 21:36:11 +0330 Subject: [PATCH 03/12] fix cs errors to follow the psr12 standard and also some minor fixes --- Ciphers/CaesarCipher.php | 8 +- Ciphers/MonoAlphabeticCipher.php | 66 ++++++++------- Ciphers/MorseCode.php | 8 +- Ciphers/XORCipher.php | 6 +- Conversions/BinaryToDecimal.php | 3 +- Conversions/DecimalToBinary.php | 3 +- Conversions/OctalToDecimal.php | 6 +- Conversions/SpeedConversion.php | 17 ++-- DataStructures/SinglyLinkedList.php | 6 +- Graphs/BreadthFirstSearch.php | 13 +-- Graphs/DepthFirstSearch.php | 17 ++-- Maths/AbsoluteMax.php | 4 +- Maths/AbsoluteMin.php | 4 +- Maths/ArmstrongNumber.php | 23 +++-- Maths/CheckPalindrome.php | 19 ++--- Maths/CheckPrime.php | 1 + Maths/Factorial.php | 16 ++-- Maths/FastExponentiation.php | 21 ++--- Maths/Fibonacci.php | 12 ++- Maths/Fibonacci2.php | 13 ++- Maths/Mean.php | 13 +-- Maths/Median.php | 13 +-- Maths/Mode.php | 4 +- Maths/NeonNumber.php | 16 ++-- Maths/PerfectSquare.php | 1 + Maths/ProjectEuler/Problem1.php | 4 +- Maths/ProjectEuler/Problem10.php | 12 +-- Maths/ProjectEuler/Problem11.php | 2 - Maths/ProjectEuler/Problem4.php | 9 +- Maths/ProjectEuler/Problem6.php | 4 +- Maths/ProjectEuler/Problem8.php | 6 +- Searches/BinarySearch.php | 9 +- Searches/ExponentialSearch.php | 78 +++++++++-------- Searches/FibonacciSearch.php | 9 +- Searches/InterpolationSearch.php | 73 ++++++++-------- Searches/JumpSearch.php | 56 ++++++------- Searches/LinearSearch.php | 11 +-- Searches/LowerBound.php | 21 ++--- Searches/TernarySearch.php | 97 +++++++++++----------- Searches/UpperBound.php | 19 +++-- Sorting/ArrayKeysSort.php | 77 ++++++++--------- Sorting/BubbleSort.php | 9 +- Sorting/BubbleSort2.php | 17 ++-- Sorting/CountSort.php | 11 +-- Sorting/GnomeSort.php | 19 ++--- Sorting/HeapSort.php | 9 +- Sorting/InsertionSort.php | 10 +-- Sorting/MergeSort.php | 11 +-- Sorting/QuickSort.php | 12 +-- Sorting/RadixSort.php | 40 +++++---- Sorting/SelectionSort.php | 12 +-- Strings/CheckAnagram.php | 3 +- Strings/CheckPalindrome.php | 12 +-- Strings/CheckPalindrome2.php | 17 ++-- Strings/CountConsonants.php | 15 ++-- Strings/CountVowels.php | 31 +++---- Strings/Distance.php | 5 +- Strings/MaxCharacter.php | 15 ++-- Strings/ReverseWords.php | 5 +- Utils/ArrayHelpers.php | 17 ++-- composer.json | 4 +- phpcs.xml.dist | 2 + tests/Ciphers/CiphersTest.php | 5 +- tests/Ciphers/MonoAlphabeticCipherTest.php | 44 +++++----- tests/Ciphers/MorseCodeTest.php | 1 + tests/Conversions/ConversionsTest.php | 1 + tests/Graphs/BreadthFirstSearchTest.php | 1 - tests/Maths/MathsTest.php | 10 +-- tests/Maths/ProjectEulerTest.php | 2 +- tests/Searches/SearchesTest.php | 3 +- tests/Sorting/ArrayKeysSortTest.php | 11 +-- tests/Strings/StringsTest.php | 1 + 72 files changed, 577 insertions(+), 578 deletions(-) diff --git a/Ciphers/CaesarCipher.php b/Ciphers/CaesarCipher.php index 3af47ff..18182f3 100755 --- a/Ciphers/CaesarCipher.php +++ b/Ciphers/CaesarCipher.php @@ -3,8 +3,8 @@ /** * Encrypt given text using caesar cipher. * - * @param string text text to be encrypted - * @param int shift number of shifts to be applied + * @param string $text text text to be encrypted + * @param int $shift shift number of shifts to be applied * @return string new encrypted text */ function encrypt(string $text, int $shift): string @@ -27,8 +27,8 @@ function encrypt(string $text, int $shift): string /** * Decrypt given text using caesar cipher. - * @param string text text to be decrypted - * @param int shift number of shifts to be applied + * @param string $text text text to be decrypted + * @param int $shift shift number of shifts to be applied * @return string new decrypted text */ function decrypt(string $text, int $shift): string diff --git a/Ciphers/MonoAlphabeticCipher.php b/Ciphers/MonoAlphabeticCipher.php index 0810a4a..6b362db 100644 --- a/Ciphers/MonoAlphabeticCipher.php +++ b/Ciphers/MonoAlphabeticCipher.php @@ -1,32 +1,34 @@ - \ No newline at end of file + 1 knot which is equal to 1 nautical mile (1852 km/h) * The conversion is made using kilometers as base * - * @param float $speed - * @param string $unitFrom - * @param string $unitTo - * @return int + * @param float $speed + * @param string $unitFrom + * @param string $unitTo + * @return float + * @throws \Exception */ function convertSpeed(float $speed, string $unitFrom, string $unitTo) { $speedUnitsFrom = [ 'mph' => 1.609344, 'km/h' => 1, - 'm/s'=> 3.6, - 'ft/s'=> 1.097, + 'm/s' => 3.6, + 'ft/s' => 1.097, 'kn' => 1.852, ]; $speedUnitsTo = [ 'mph' => 0.6213712, 'km/h' => 1, - 'm/s'=> 0.277778, - 'ft/s'=> 0.911344, + 'm/s' => 0.277778, + 'ft/s' => 0.911344, 'kn' => 0.539957, ]; $availableUnits = array_keys($speedUnitsFrom); diff --git a/DataStructures/SinglyLinkedList.php b/DataStructures/SinglyLinkedList.php index 44621d6..7256ed7 100644 --- a/DataStructures/SinglyLinkedList.php +++ b/DataStructures/SinglyLinkedList.php @@ -1,13 +1,12 @@ data = $data; @@ -16,7 +15,6 @@ class SinglyLinkedList public function append($data): void { $current = $this; - while ($current instanceof SinglyLinkedList && isset($current->next)) { $current = $current->next; } @@ -27,7 +25,6 @@ class SinglyLinkedList public function delete($data): SinglyLinkedList { $current = $this; - if ($current->data == $data) { return $current->next; } @@ -35,7 +32,6 @@ class SinglyLinkedList while ($current instanceof SinglyLinkedList && isset($current->next)) { if ($current->next->data === $data) { $current->next = $current->next->next; - return $this; } diff --git a/Graphs/BreadthFirstSearch.php b/Graphs/BreadthFirstSearch.php index 4411011..68579e1 100644 --- a/Graphs/BreadthFirstSearch.php +++ b/Graphs/BreadthFirstSearch.php @@ -3,21 +3,22 @@ /** * Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property. * (https://en.wikipedia.org/wiki/Breadth-first_search). - * - * This is a non recursive implementation. - * + * + * This is a non-recursive implementation. + * * References: * https://cp-algorithms.com/graph/breadth-first-search.html - * + * * https://the-algorithms.com/algorithm/depth-first-search?lang=python - * + * * @author Aryansh Bhargavan https://github.com/aryanshb * @param array $adjList An array representing the grapth as an Adjacent List * @param int|string $start The starting vertex * @return bool if path between start and end vertex exists */ -function bfs($adjList, $start, $end, $yes = false){ +function bfs($adjList, $start, $end, $yes = false) +{ $visited = []; $queue = [$start]; while (!empty($queue)) { diff --git a/Graphs/DepthFirstSearch.php b/Graphs/DepthFirstSearch.php index 936484c..3a8dea5 100644 --- a/Graphs/DepthFirstSearch.php +++ b/Graphs/DepthFirstSearch.php @@ -1,20 +1,20 @@ diff --git a/Maths/CheckPalindrome.php b/Maths/CheckPalindrome.php index 574e340..d76b6da 100644 --- a/Maths/CheckPalindrome.php +++ b/Maths/CheckPalindrome.php @@ -1,4 +1,5 @@ diff --git a/Maths/CheckPrime.php b/Maths/CheckPrime.php index 6463043..f9d1452 100644 --- a/Maths/CheckPrime.php +++ b/Maths/CheckPrime.php @@ -1,4 +1,5 @@ 0 && $set->valid()) - { + while ($i-- > 0 && $set->valid()) { yield $set->current(); $set->next(); } @@ -25,8 +24,7 @@ function fib() yield $i = 0; yield $j = 1; - while(true) - { + while (true) { yield $k = $i + $j; $i = $j; $j = $k; @@ -36,7 +34,6 @@ function fib() /* * Generate 100 Fibonacci numbers */ -foreach(loop(100, fib()) as $item) -{ - print($item.','); -} \ No newline at end of file +foreach (loop(100, fib()) as $item) { + print($item . ','); +} diff --git a/Maths/Mean.php b/Maths/Mean.php index 52f0120..b24b4e0 100644 --- a/Maths/Mean.php +++ b/Maths/Mean.php @@ -1,11 +1,13 @@ diff --git a/Maths/PerfectSquare.php b/Maths/PerfectSquare.php index 7bca044..2b6fb74 100644 --- a/Maths/PerfectSquare.php +++ b/Maths/PerfectSquare.php @@ -1,4 +1,5 @@ $largest) { + if (strrev((string)$product) == (string)$product && $product > $largest) { $largest = $product; } } diff --git a/Maths/ProjectEuler/Problem6.php b/Maths/ProjectEuler/Problem6.php index 15a91ec..35fd8e5 100644 --- a/Maths/ProjectEuler/Problem6.php +++ b/Maths/ProjectEuler/Problem6.php @@ -5,10 +5,10 @@ * * Problem description: * The sum of the squares of the first ten natural numbers is, - * 1 ** 2 + 2 ** 2 + ... + 10 ** 2 = 385 + * 1 ** 2 + 2 ** 2 + ... + 10 ** 2 = 385 * * The square of the sum of the first ten natural numbers is, - * (1 + 2 + ... + 10) ** 2 = 3025 + * (1 + 2 + ... + 10) ** 2 = 3025 * * Hence the difference between the sum of the squares of the * first ten natural numbers and the square of the sum is . diff --git a/Maths/ProjectEuler/Problem8.php b/Maths/ProjectEuler/Problem8.php index 737254f..aa0a215 100644 --- a/Maths/ProjectEuler/Problem8.php +++ b/Maths/ProjectEuler/Problem8.php @@ -59,11 +59,11 @@ function problem8(): int $substringSize = 13; for ($i = 0; $i < strlen($theNumber) - $substringSize; $i++) { - $currentSubstring = substr($theNumber,$i,$substringSize); + $currentSubstring = substr($theNumber, $i, $substringSize); $currentProduct = 0; - for ($j = 0; $j < strlen ($currentSubstring); $j++) { - $currentProduct = ($currentProduct == 0 ? (int)$currentSubstring[$j] : $currentProduct * (int)$currentSubstring[$j]); + for ($j = 0; $j < strlen($currentSubstring); $j++) { + $currentProduct = ($currentProduct == 0 ? (int)$currentSubstring[$j] : $currentProduct * (int)$currentSubstring[$j]); } $greatestProduct = ($greatestProduct < $currentProduct ? $currentProduct : $greatestProduct); diff --git a/Searches/BinarySearch.php b/Searches/BinarySearch.php index e3b1e31..1078930 100644 --- a/Searches/BinarySearch.php +++ b/Searches/BinarySearch.php @@ -21,7 +21,7 @@ function binarySearchIterative($list, $target) { $first = 0; - $last = count($list)-1; + $last = count($list) - 1; while ($first <= $last) { @@ -70,8 +70,9 @@ function binarySearchByRecursion($list, $target, $start, $end) return $list[0] == $target ? 0 : null; } - if ($start > $end) + if ($start > $end) { return null; + } $mid = ($start + $end) >> 1; @@ -80,9 +81,9 @@ function binarySearchByRecursion($list, $target, $start, $end) if ($list[$mid] == $target) { return $mid; } elseif ($list[$mid] > $target) { - return binarySearchByRecursion($list, $target, $start, $mid-1); + return binarySearchByRecursion($list, $target, $start, $mid - 1); } elseif ($list[$mid] < $target) { - return binarySearchByRecursion($list, $target, $mid+1, $end); + return binarySearchByRecursion($list, $target, $mid + 1, $end); } return null; diff --git a/Searches/ExponentialSearch.php b/Searches/ExponentialSearch.php index 7073053..f034c1f 100644 --- a/Searches/ExponentialSearch.php +++ b/Searches/ExponentialSearch.php @@ -1,9 +1,10 @@ $ceiling) return -1; + if ($floor > $ceiling) { + return -1; + } // search the left part of the $array - // If the $middle element is great than the $value - if ($arr[$mid] > $value) { - return binarySearch($arr, $value, $floor, $mid - 1); - } + // If the $middle element is greater than the $value + if ($arr[$mid] > $value) { + return binarySearch($arr, $value, $floor, $mid - 1); + } // search the right part of the $array // If the $middle element is lower than the $value - else { - return binarySearch($arr, $value, $mid + 1, $ceiling); - } + else { + return binarySearch($arr, $value, $mid + 1, $ceiling); + } } - /** - * @param Array $arr - * @param int $length - * @param int $value - * @return int - **/ -function exponentialSearch ($arr, $value) { + +/** + * @param Array $arr + * @param int $value + * @return int + */ +function exponentialSearch($arr, $value) +{ + // If $value is the first element of the $array return this position - if ($arr[0] === $value) { - return 0; - } + if ($arr[0] === $value) { + return 0; + } // Find range for binary search - $i = 1; - $length = count($arr); - while ($i < $length && $arr[$i] <= $value) { - $i = $i * 2; - } - $floor = $i/2; - $ceiling = min($i, $length); - - // Call binary search for the range found above - return binarySearch($arr, $value, $floor, $ceiling); -} \ No newline at end of file + $i = 1; + $length = count($arr); + while ($i < $length && $arr[$i] <= $value) { + $i = $i * 2; + } + $floor = $i / 2; + $ceiling = min($i, $length); +// Call binary search for the range found above + return binarySearch($arr, $value, $floor, $ceiling); +} diff --git a/Searches/FibonacciSearch.php b/Searches/FibonacciSearch.php index 7e04a4b..b103785 100644 --- a/Searches/FibonacciSearch.php +++ b/Searches/FibonacciSearch.php @@ -11,13 +11,16 @@ */ function fibonacciPosition(int $n, array &$m = []) { - if(isset($m[$n])) return $m[$n]; - if($n < 2) return $n; + if (isset($m[$n])) { + return $m[$n]; + } + if ($n < 2) { + return $n; + } $m[$n] = fibonacciPosition($n - 1, $m) + fibonacciPosition($n - 2, $m); return $m[$n]; - } print fibonacciPosition(59); diff --git a/Searches/InterpolationSearch.php b/Searches/InterpolationSearch.php index 4e27c7d..bb73d92 100644 --- a/Searches/InterpolationSearch.php +++ b/Searches/InterpolationSearch.php @@ -1,12 +1,13 @@ key decrease the high index * repeat the loop */ -function interpolationSearch($arr, $key) { - $length = count($arr) - 1; - $low = 0; - $high = $length; - $position = -1; - //loop, between low & high - while ($low <= $high && $key >= $arr[$low] && $key <= $arr[$high]) { - //GET INDEX - $delta = ($key - $arr[$low]) / ($arr[$high] - $arr[$low]); - $index = $low + floor(($high - $low) * $delta); - //GET VALUE OF INDEX IN ARRAY... - $indexValue = $arr[$index]; - if ($indexValue === $key) { - //index value equals key - //FOUND TARGET - //return index value - $position = $index; - return (int) $position; +function interpolationSearch($arr, $key) +{ + + $length = count($arr) - 1; + $low = 0; + $high = $length; + $position = -1; +//loop, between low & high + while ($low <= $high && $key >= $arr[$low] && $key <= $arr[$high]) { +//GET INDEX + $delta = ($key - $arr[$low]) / ($arr[$high] - $arr[$low]); + $index = $low + floor(($high - $low) * $delta); +//GET VALUE OF INDEX IN ARRAY... + $indexValue = $arr[$index]; + if ($indexValue === $key) { + //index value equals key + //FOUND TARGET + //return index value + $position = $index; + return (int) $position; + } + if ($indexValue < $key) { + //index value lower than key + //increase low index + $low = $index + 1; + } + if ($indexValue > $key) { + //index value higher than key + //decrease high index + $high = $index - 1; + } } - if ($indexValue < $key) { - //index value lower than key - //increase low index - $low = $index + 1; - } - if ($indexValue > $key) { - //index value higher than key - //decrease high index - $high = $index - 1; - } - } //when key not found in array or array not sorted - return null; -} \ No newline at end of file + return null; +} diff --git a/Searches/JumpSearch.php b/Searches/JumpSearch.php index adda458..7be70de 100644 --- a/Searches/JumpSearch.php +++ b/Searches/JumpSearch.php @@ -1,40 +1,38 @@ = $num) - return -1; - } - /*Performing linear search for $key in block*/ - while ($list[$prev] < $key) - { - $prev++; - if ($prev == min($step, $num)) - return -1; - } - +function jumpSearch($list, $key) +{ + /*number of elements in the sorted array*/ + $num = count($list); +/*block size to be jumped*/ + $step = (int)sqrt($num); + $prev = 0; + + while ($list[min($step, $num) - 1] < $key) { + $prev = $step; + $step += (int)sqrt($num); + if ($prev >= $num) { + return -1; + } + } + + /*Performing linear search for $key in block*/ + while ($list[$prev] < $key) { + $prev++; + if ($prev == min($step, $num)) { + return -1; + } + } + return $list[$prev] === $key ? $prev : -1; } - - - diff --git a/Searches/LinearSearch.php b/Searches/LinearSearch.php index 4de38be..2d8ee41 100644 --- a/Searches/LinearSearch.php +++ b/Searches/LinearSearch.php @@ -5,10 +5,6 @@ * * Reference: https://www.geeksforgeeks.org/linear-search/ * - * @param Array $list a array of integers to search - * @param integer $target an integer number to search for in the list - * @return integer the index where the target is found (or -1 if not found) - * * Examples: * data = 5, 7, 8, 11, 12, 15, 17, 18, 20 * x = 15 @@ -17,16 +13,15 @@ * x = 1 * Element not found * - * @param Array $list a array of integers to search + * @param Array $list an array of integers to search * @param integer $target an integer number to search for in the list * @return integer the index where the target is found (or -1 if not found) */ function linearSearch($list, $target) { $n = sizeof($list); - for($i = 0; $i < $n; $i++) - { - if($list[$i] == $target) { + for ($i = 0; $i < $n; $i++) { + if ($list[$i] == $target) { return $i + 1; } } diff --git a/Searches/LowerBound.php b/Searches/LowerBound.php index cf46555..ba4ddbb 100644 --- a/Searches/LowerBound.php +++ b/Searches/LowerBound.php @@ -10,24 +10,25 @@ require_once __DIR__ . '/../Utils/ArrayHelpers.php'; * [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/lower_bound/) * * It is assumed that an integer array is provided - * and the second parameter is also a integer + * and the second parameter is also an integer * - * @param array of sorted integers - * @param integer whose lower bound is to be found + * @param array $arr of sorted integers + * @param integer $elem whose lower bound is to be found * - * @return the index of lower bound of the given element + * @return int the index of lower bound of the given element */ -function lowerBound(array $arr, int $elem){ +function lowerBound(array $arr, int $elem) +{ isSortedAscendingInts($arr); $hi = count($arr); $lo = 0; - while($lo < $hi){ - $mid = $lo + floor(($hi - $lo)/2); + while ($lo < $hi) { + $mid = $lo + floor(($hi - $lo) / 2); - if($arr[$mid] < $elem){ - $lo = $mid+1; - }else{ + if ($arr[$mid] < $elem) { + $lo = $mid + 1; + } else { $hi = $mid; } } diff --git a/Searches/TernarySearch.php b/Searches/TernarySearch.php index a0e2235..21e4aad 100644 --- a/Searches/TernarySearch.php +++ b/Searches/TernarySearch.php @@ -1,4 +1,5 @@ $arr[$mid2]) { - // the $key lies in between $mid2 and $high - return ternarySearchByRecursion($arr, $key, $mid2 + 1, $high); +// the $key lies in between $low and $mid1 + return ternarySearchByRecursion($arr, $key, $low, $mid1 - 1); + } elseif ($key > $arr[$mid2]) { + // the $key lies in between $mid2 and $high + return ternarySearchByRecursion($arr, $key, $mid2 + 1, $high); } else { - // the $key lies in between $mid1 and $mid2 - return ternarySearchByRecursion($arr, $key, $mid1 + 1, $mid2 - 1); + // the $key lies in between $mid1 and $mid2 + return ternarySearchByRecursion($arr, $key, $mid1 + 1, $mid2 - 1); } } -function ternarySearchIterative ($arr, $key) { - $low = 0; $high = count($arr) - 1; - while ($high >= $low) { +function ternarySearchIterative($arr, $key) +{ + $low = 0; + $high = count($arr) - 1; + while ($high >= $low) { // find the $mid1 and $mid2 - $mid1 = floor($low + ($high - $low) / 3); - $mid2 = floor($high - ($high - $low) / 3); - + $mid1 = floor($low + ($high - $low) / 3); + $mid2 = floor($high - ($high - $low) / 3); // check if $key is found at any $mid - if ($arr[$mid1] === $key) { - // return index of $key if found - return $mid1; - } - if ($arr[$mid2] === $key) { - // return index of $key if found - return $mid2; - } + if ($arr[$mid1] === $key) { +// return index of $key if found + return $mid1; + } + if ($arr[$mid2] === $key) { + // return index of $key if found + return $mid2; + } - // since the $key is not found at $mid, - // check in which region it is present - // and repeat the Search operation - // in that region - if ($key < $arr[$mid1]) { - // the $key lies in between $low and $mid1 - $high = $mid1 - 1; - } else if ($key > $arr[$mid2]) { - // the $key lies in between $mid2 and $high - $low = $mid2 + 1; - } else { - // the $key lies in between $mid1 and $mid2 - $low = $mid1 + 1; - $high = $mid2 - 1; + // since the $key is not found at $mid, + // check in which region it is present + // and repeat the Search operation + // in that region + if ($key < $arr[$mid1]) { + // the $key lies in between $low and $mid1 + $high = $mid1 - 1; + } elseif ($key > $arr[$mid2]) { + // the $key lies in between $mid2 and $high + $low = $mid2 + 1; + } else { + // the $key lies in between $mid1 and $mid2 + $low = $mid1 + 1; + $high = $mid2 - 1; + } } - } // the $key was not found - return null; + return null; } diff --git a/Searches/UpperBound.php b/Searches/UpperBound.php index 6cfbffe..47d6251 100644 --- a/Searches/UpperBound.php +++ b/Searches/UpperBound.php @@ -10,24 +10,25 @@ require_once __DIR__ . '/../Utils/ArrayHelpers.php'; * [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/upper_bound/) * * It is assumed that an integer array is provided - * and the second parameter is also a integer + * and the second parameter is also an integer * - * @param array of sorted integers - * @param integer whose upper bound is to be found + * @param array $arr of sorted integers + * @param integer $elem whose upper bound is to be found * - * @return the index of upper bound of the given element + * @return int the index of upper bound of the given element */ -function upperBound(array $arr, int $elem){ +function upperBound(array $arr, int $elem) +{ isSortedAscendingInts($arr); $hi = count($arr); $lo = 0; - while($lo < $hi){ - $mid = $lo + floor(($hi - $lo)/2); + while ($lo < $hi) { + $mid = $lo + floor(($hi - $lo) / 2); - if($arr[$mid] <= $elem){ + if ($arr[$mid] <= $elem) { $lo = $mid + 1; - }else{ + } else { $hi = $mid; } } diff --git a/Sorting/ArrayKeysSort.php b/Sorting/ArrayKeysSort.php index 034258e..4c97830 100644 --- a/Sorting/ArrayKeysSort.php +++ b/Sorting/ArrayKeysSort.php @@ -1,4 +1,5 @@ $key) || !isset($b->$key)) { - $errorMsg = 'The key "' . $key - . '" does not exist in the collection'; - throw new Exception($errorMsg); - } - $item1 = !$isCaseSensitive - ? strtolower($a->$key) : $a->$key; - $item2 = !$isCaseSensitive - ? strtolower($b->$key) : $b->$key; - } - } while ($item1 === $item2 && !empty($keys[++$pos])); + usort($collection, function ($a, $b) use ($keys, $order, $isCaseSensitive) { - if ($item1 === $item2) { - return 0; - } elseif ($order === self::ORDER_ASC) { - return ($item1 < $item2) ? -1 : 1; + $pos = 0; + do { + $key = $keys[$pos]; + if (is_array($a)) { + if (!isset($a[$key]) || !isset($b[$key])) { + $errorMsg = 'The key "' . $key + . '" does not exist in the collection'; + throw new Exception($errorMsg); + } + $item1 = !$isCaseSensitive + ? strtolower($a[$key]) : $a[$key]; + $item2 = !$isCaseSensitive + ? strtolower($b[$key]) : $b[$key]; } else { - return ($item1 > $item2) ? -1 : 1; + if (!isset($a->$key) || !isset($b->$key)) { + $errorMsg = 'The key "' . $key + . '" does not exist in the collection'; + throw new Exception($errorMsg); + } + $item1 = !$isCaseSensitive + ? strtolower($a->$key) : $a->$key; + $item2 = !$isCaseSensitive + ? strtolower($b->$key) : $b->$key; } + } while ($item1 === $item2 && !empty($keys[++$pos])); + if ($item1 === $item2) { + return 0; + } elseif ($order === self::ORDER_ASC) { + return ($item1 < $item2) ? -1 : 1; + } else { + return ($item1 > $item2) ? -1 : 1; } - ); + }); } catch (Exception $e) { echo $e->getMessage(); die(); diff --git a/Sorting/BubbleSort.php b/Sorting/BubbleSort.php index b46e7a0..9bc6679 100644 --- a/Sorting/BubbleSort.php +++ b/Sorting/BubbleSort.php @@ -6,13 +6,14 @@ * @param array $array * @return array */ -function bubbleSort($array) { +function bubbleSort($array) +{ $length = count($array); for ($i = $length; $i > 0; $i--) { $swapped = true; - for ($j=0;$j<$i-1;$j++) { + for ($j = 0; $j < $i - 1; $j++) { if ($array[$j] > $array[$j + 1]) { $temp = $array[$j]; $array[$j] = $array[$j + 1]; @@ -21,7 +22,9 @@ function bubbleSort($array) { } } - if ($swapped) break; + if ($swapped) { + break; + } } return $array; diff --git a/Sorting/BubbleSort2.php b/Sorting/BubbleSort2.php index f29b339..97d0757 100644 --- a/Sorting/BubbleSort2.php +++ b/Sorting/BubbleSort2.php @@ -1,4 +1,5 @@ 0 ) { + for ($i = $min; $i <= $max; $i++) { + while ($count[$i]-- > 0) { $array[$z++] = $i; } } diff --git a/Sorting/GnomeSort.php b/Sorting/GnomeSort.php index 003e097..a9a88ce 100644 --- a/Sorting/GnomeSort.php +++ b/Sorting/GnomeSort.php @@ -4,26 +4,25 @@ * Gnome Sort * References: * https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/ - * + * * The Gnome algorithm works by locating the first instance in which two adjoining elements are arranged incorrectly and swaps with each other. - * + * * @param array $array refers to the array to be sorted * @return array */ - -function gnomeSort($array){ +function gnomeSort($array) +{ $a = 1; $b = 2; - while($a < count($array)){ - - if ($array[$a-1] <= $array[$a]){ + while ($a < count($array)) { + if ($array[$a - 1] <= $array[$a]) { $a = $b; $b++; - }else{ - list($array[$a],$array[$a-1]) = array($array[$a-1],$array[$a]); + } else { + list($array[$a],$array[$a - 1]) = array($array[$a - 1],$array[$a]); $a--; - if($a == 0){ + if ($a == 0) { $a = $b; $b++; } diff --git a/Sorting/HeapSort.php b/Sorting/HeapSort.php index 308b220..d999967 100644 --- a/Sorting/HeapSort.php +++ b/Sorting/HeapSort.php @@ -1,4 +1,5 @@ = 0; $i--) { - // Swap +// Swap [$arr[0], $arr[$i]] = [$arr[$i], $arr[0]]; - - // Heapify the reduced heap +// Heapify the reduced heap heapify($arr, $i, 0); } @@ -46,7 +46,6 @@ function heapify(array &$arr, int $n, int $i): void $largest = $i; $left = 2 * $i + 1; $right = 2 * $i + 2; - if ($left < $n && $arr[$left] > $arr[$largest]) { $largest = $left; } @@ -59,4 +58,4 @@ function heapify(array &$arr, int $n, int $i): void [$arr[$i], $arr[$largest]] = [$arr[$largest], $arr[$i]]; heapify($arr, $n, $largest); } -} \ No newline at end of file +} diff --git a/Sorting/InsertionSort.php b/Sorting/InsertionSort.php index b184e54..fcffaa0 100644 --- a/Sorting/InsertionSort.php +++ b/Sorting/InsertionSort.php @@ -8,13 +8,11 @@ */ function insertionSort(array $array) { - for ($i = 1; $i < count($array); $i++) - { + for ($i = 1; $i < count($array); $i++) { $currentVal = $array[$i]; - for ($j = $i - 1; $j >= 0 && $array[$j] > $currentVal; $j--) - { - $array[$j + 1] = $array[$j]; + for ($j = $i - 1; $j >= 0 && $array[$j] > $currentVal; $j--) { + $array[$j + 1] = $array[$j]; } $array[$j + 1] = $currentVal; @@ -22,5 +20,3 @@ function insertionSort(array $array) return $array; } - - diff --git a/Sorting/MergeSort.php b/Sorting/MergeSort.php index 7923917..23c6417 100644 --- a/Sorting/MergeSort.php +++ b/Sorting/MergeSort.php @@ -9,12 +9,12 @@ function mergeSort(array $arr) { if (count($arr) <= 1) { - return $arr; + return $arr; } - $mid = floor( count($arr) / 2 ); - $leftArray = mergeSort( array_slice($arr, 0, $mid) ); - $rightArray = mergeSort( array_slice($arr, $mid) ); + $mid = floor(count($arr) / 2); + $leftArray = mergeSort(array_slice($arr, 0, $mid)); + $rightArray = mergeSort(array_slice($arr, $mid)); return merge($leftArray, $rightArray); } @@ -52,6 +52,3 @@ function merge(array $leftArray, array $rightArray) return $result; } - - - diff --git a/Sorting/QuickSort.php b/Sorting/QuickSort.php index da35617..0950eff 100644 --- a/Sorting/QuickSort.php +++ b/Sorting/QuickSort.php @@ -1,4 +1,5 @@ = 'a' && $string[$i] <= 'z') - { + for ($i = 0; $i < strlen($string); $i++) { + if ( + !in_array($string[$i], $vowels) && + $string[$i] >= 'a' && $string[$i] <= 'z' + ) { $consonantCount++; } } diff --git a/Strings/CountVowels.php b/Strings/CountVowels.php index e3eef0a..34a78c0 100644 --- a/Strings/CountVowels.php +++ b/Strings/CountVowels.php @@ -1,28 +1,30 @@ = 0; $i--) - { + for ($i = (count($words) - 1); $i >= 0; $i--) { $reversedWords[] = $words[$i]; } diff --git a/Utils/ArrayHelpers.php b/Utils/ArrayHelpers.php index 9666aa6..37602e9 100644 --- a/Utils/ArrayHelpers.php +++ b/Utils/ArrayHelpers.php @@ -1,24 +1,25 @@ . + vendor + 0 diff --git a/tests/Ciphers/CiphersTest.php b/tests/Ciphers/CiphersTest.php index d620481..241e729 100755 --- a/tests/Ciphers/CiphersTest.php +++ b/tests/Ciphers/CiphersTest.php @@ -1,6 +1,7 @@ assertEquals( $input_str, xorCipher( xorCipher( $input_str , $key) , $key)); - $this->assertNotEquals( $input_str, xorCipher( xorCipher( $input_str , $key) , $invalid_key)); + $this->assertEquals($input_str, xorCipher(xorCipher($input_str, $key), $key)); + $this->assertNotEquals($input_str, xorCipher(xorCipher($input_str, $key), $invalid_key)); } } diff --git a/tests/Ciphers/MonoAlphabeticCipherTest.php b/tests/Ciphers/MonoAlphabeticCipherTest.php index 4509ab4..de90096 100644 --- a/tests/Ciphers/MonoAlphabeticCipherTest.php +++ b/tests/Ciphers/MonoAlphabeticCipherTest.php @@ -1,23 +1,21 @@ - +assertTrue($ans); } } - diff --git a/tests/Maths/MathsTest.php b/tests/Maths/MathsTest.php index 8684a73..d3bc9b4 100644 --- a/tests/Maths/MathsTest.php +++ b/tests/Maths/MathsTest.php @@ -3,6 +3,7 @@ use function PHPUnit\Framework\assertEquals; use function PHPUnit\Framework\assertFalse; use function PHPUnit\Framework\assertTrue; + use PHPUnit\Framework\TestCase; require_once __DIR__ . '/../../vendor/autoload.php'; @@ -107,7 +108,7 @@ class MathsTest extends TestCase assertFalse(isNumberNeon(123)); assertTrue(isNumberNeon(9)); } - + public function testFibonacciGenerator() { assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); @@ -120,15 +121,15 @@ class MathsTest extends TestCase public function testMean() { assertEquals( - (2 + 4 + 6 + 8 + 20 + 50 + 70) / 7, + (2 + 4 + 6 + 8 + 20 + 50 + 70) / 7, mean(2, 4, 6, 8, 20, 50, 70) ); assertEquals( - (-5 - 7 + 10) / 3, + (-5 - 7 + 10) / 3, mean(-5, -7, 10) ); - + assertEquals(-1, mean(-1)); } @@ -146,5 +147,4 @@ class MathsTest extends TestCase $this->assertEquals([1, 2, 3, 4, 5], mode(1, 2, 3, 4, 5)); $this->assertEquals([2, 3, 4], mode(2, 2, 3, 3, 4, 4)); } - } diff --git a/tests/Maths/ProjectEulerTest.php b/tests/Maths/ProjectEulerTest.php index 3b74f3e..43b1da4 100644 --- a/tests/Maths/ProjectEulerTest.php +++ b/tests/Maths/ProjectEulerTest.php @@ -62,7 +62,7 @@ class ProjectEulerTest extends TestCase { $this->assertSame(31875000, problem9()); } - + public function testProblem10(): void { $this->assertSame(142913828922, problem10()); diff --git a/tests/Searches/SearchesTest.php b/tests/Searches/SearchesTest.php index 08d2f71..3de89db 100644 --- a/tests/Searches/SearchesTest.php +++ b/tests/Searches/SearchesTest.php @@ -3,6 +3,7 @@ use function PHPUnit\Framework\assertEquals; use function PHPUnit\Framework\assertFalse; use function PHPUnit\Framework\assertTrue; + use PHPUnit\Framework\TestCase; require_once __DIR__ . '/../../vendor/autoload.php'; @@ -138,7 +139,7 @@ class SearchesTest extends TestCase $result = upperBound($list, $target); assertEquals(5, $result); } - + public function testJumpSearch() { $list = array( 3,5,6,7,9,10,12,20,22,24); diff --git a/tests/Sorting/ArrayKeysSortTest.php b/tests/Sorting/ArrayKeysSortTest.php index 2b05498..31c322d 100644 --- a/tests/Sorting/ArrayKeysSortTest.php +++ b/tests/Sorting/ArrayKeysSortTest.php @@ -7,7 +7,8 @@ use PHPUnit\Framework\TestCase; class ArrayKeysSortTest extends TestCase { - public function testArrayKeysSort() { + public function testArrayKeysSort() + { //test array of arrays $array1 = [ ['fruit' => 'banana', 'color' => 'yellow', 'cant' => 5], @@ -36,22 +37,22 @@ class ArrayKeysSortTest extends TestCase $this->assertEquals($result2, $test2); //test array of objects - $object1 = new \stdClass; + $object1 = new \stdClass(); $object1->fruit = 'banana'; $object1->color = 'yellow'; $object1->cant = 5; - $object2 = new \stdClass; + $object2 = new \stdClass(); $object2->fruit = 'apple'; $object2->color = 'red'; $object2->cant = 2; - $object3 = new \stdClass; + $object3 = new \stdClass(); $object3->fruit = 'apple'; $object3->color = 'green'; $object3->cant = 7; - $object4 = new \stdClass; + $object4 = new \stdClass(); $object4->fruit = 'grapes'; $object4->color = 'purple'; $object4->cant = 4; diff --git a/tests/Strings/StringsTest.php b/tests/Strings/StringsTest.php index 3b17907..41cd170 100644 --- a/tests/Strings/StringsTest.php +++ b/tests/Strings/StringsTest.php @@ -4,6 +4,7 @@ use function PHPUnit\Framework\assertEquals; use function PHPUnit\Framework\assertFalse; use function PHPUnit\Framework\assertNotEquals; use function PHPUnit\Framework\assertTrue; + use PHPUnit\Framework\TestCase; require_once __DIR__ . '/../../vendor/autoload.php'; From 39ab69ecea305299975d7f793bf0b8cbbe7bf668 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 22:56:49 +0330 Subject: [PATCH 04/12] fix string test structure --- tests/Strings/StringsTest.php | 76 +++++++++++++++++------------------ 1 file changed, 36 insertions(+), 40 deletions(-) diff --git a/tests/Strings/StringsTest.php b/tests/Strings/StringsTest.php index 41cd170..99a176b 100644 --- a/tests/Strings/StringsTest.php +++ b/tests/Strings/StringsTest.php @@ -1,10 +1,5 @@ assertTrue(isPalindrome('MaDam')); // true + $this->assertFalse(isPalindrome('ThisIsTest')); // false + $this->assertFalse(isPalindrome('')); // false + $this->assertTrue(isPalindrome('Sator Arepo Tenet Opera Rotas')); // true + $this->assertFalse(isPalindrome('Sator Arepo Tenet Opera Rotas', false)); // false since we are doing + // case-sensitive check } public function testCountSentences() { - assertEquals(countSentences('Hi! Hello world.'), 2); - assertEquals(countSentences('i am testing. test....'), 2); - assertEquals(countSentences('How are you?'), 1); + $this->assertEquals(2, countSentences('Hi! Hello world.')); + $this->assertEquals(2, countSentences('i am testing. test....')); + $this->assertEquals(1, countSentences('How are you?')); } public function testReverseString() { - assertEquals('txet emos si sihT', reverseString('This is some text')); - assertEquals('mADaM', reverseString('MaDAm')); - assertNotEquals('MaDAm', reverseString('MaDAm')); + $this->assertEquals('txet emos si sihT', reverseString('This is some text')); + $this->assertEquals('mADaM', reverseString('MaDAm')); + $this->assertNotEquals('MaDAm', reverseString('MaDAm')); } public function testReverseWords() { - assertEquals('Fun is Coding PHP', reverseWords('PHP Coding is Fun')); - assertEquals('OneWord', reverseWords('OneWord')); - assertEquals('Text different some is This', reverseWords('This is some different Text')); + $this->assertEquals('Fun is Coding PHP', reverseWords('PHP Coding is Fun')); + $this->assertEquals('OneWord', reverseWords('OneWord')); + $this->assertEquals('Text different some is This', reverseWords('This is some different Text')); } public function testIsAnagram() { - assertTrue(isAnagram("php", "PHP")); // By default it's case-insensitive - assertFalse(isAnagram("php", "PHP", false)); // Make case-sensitive check - assertTrue(isAnagram("php is fun", "pin hpf us")); - assertFalse(isAnagram("Hello", " Hello")); //Extra space character - assertTrue(isAnagram("ScRamble", "SRlmcaeb", false)); // Check with a mixture of upper and lower case + $this->assertTrue(isAnagram("php", "PHP")); // By default it's case-insensitive + $this->assertFalse(isAnagram("php", "PHP", false)); // Make case-sensitive check + $this->assertTrue(isAnagram("php is fun", "pin hpf us")); + $this->assertFalse(isAnagram("Hello", " Hello")); //Extra space character + $this->assertTrue(isAnagram("ScRamble", "SRlmcaeb", false)); // Check with a mixture of upper and lower case } public function testMaxCharacter() { - assertEquals(maxCharacter("this is test for max character repetition"), 't'); - assertEquals(maxCharacter("This is Test for max characTer repetition"), 't'); - assertEquals(maxCharacter(" "), ' '); + $this->assertEquals('t', maxCharacter("this is test for max character repetition")); + $this->assertEquals('t', maxCharacter("This is Test for max characTer repetition")); + $this->assertEquals(' ', maxCharacter(" ")); } public function testCountVowels() { - assertEquals(countVowelsSimple("This is a string with 7 vowels"), 7); - assertEquals(countVowelsSimple("hello world"), 3); - assertEquals(countVowelsRegex("Just A list of somE aaaaaaaaaa"), 16); + $this->assertEquals(7, countVowelsSimple("This is a string with 7 vowels")); + $this->assertEquals(3, countVowelsSimple("hello world")); + $this->assertEquals(16, countVowelsRegex("Just A list of somE aaaaaaaaaa")); - assertEquals(countVowelsRegex("This is a string with 7 vowels"), 7); - assertEquals(countVowelsRegex("hello world"), 3); - assertEquals(countVowelsRegex("Just A list of somE aaaaaaaaaa"), 16); + $this->assertEquals(7, countVowelsRegex("This is a string with 7 vowels")); + $this->assertEquals(3, countVowelsRegex("hello world")); + $this->assertEquals(16, countVowelsRegex("Just A list of somE aaaaaaaaaa")); } public function testCountConsonants() { - assertEquals(countConsonants("This is a string with 19 consonants"), 19); - assertEquals(countConsonants("hello world"), 7); - assertEquals(countConsonants("Just A list of somE aaaaaaaaaa"), 9); + $this->assertEquals(19, countConsonants("This is a string with 19 consonants")); + $this->assertEquals(7, countConsonants("hello world")); + $this->assertEquals(9, countConsonants("Just A list of somE aaaaaaaaaa")); } public function testFindDistance() { - assertEquals(findDistance("hello", "hallo"), 1); - assertEquals(findDistance("hallo", "hello"), 1); - assertEquals(findDistance("sunday", "sunday"), 0); - assertEquals(findDistance("saturday", "sunday"), 3); + $this->assertEquals(1, findDistance("hello", "hallo")); + $this->assertEquals(1, findDistance("hallo", "hello")); + $this->assertEquals(0, findDistance("sunday", "sunday")); + $this->assertEquals(3, findDistance("saturday", "sunday")); } } From 963bafca7178808a78b1a527044a7d677b5d51bc Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:03:29 +0330 Subject: [PATCH 05/12] fix searches test structure --- tests/Searches/SearchesTest.php | 80 ++++++++++++++++----------------- 1 file changed, 38 insertions(+), 42 deletions(-) diff --git a/tests/Searches/SearchesTest.php b/tests/Searches/SearchesTest.php index 3de89db..edf1618 100644 --- a/tests/Searches/SearchesTest.php +++ b/tests/Searches/SearchesTest.php @@ -1,9 +1,5 @@ assertEquals(0, $result); $target = 15; $result = binarySearchIterative($list, $target); - assertEquals(4, $result); + $this->assertEquals(4, $result); $target = 5; $result = binarySearchIterative($list, $target); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 6; $result = binarySearchIterative($list, $target); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testBinarySearchByRecursion() @@ -42,16 +38,16 @@ class SearchesTest extends TestCase $list = [0, 5, 7, 10, 15]; $target = 0; $result = binarySearchByRecursion($list, $target, 0, 4); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 15; $result = binarySearchByRecursion($list, $target, 0, 4); - assertEquals(4, $result); + $this->assertEquals(4, $result); $target = 5; $result = binarySearchByRecursion($list, $target, 0, 4); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 6; $result = binarySearchByRecursion($list, $target, 0, 4); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testBinarySearchByRecursionWithEmptyList() @@ -59,7 +55,7 @@ class SearchesTest extends TestCase $list = []; $target = 0; $result = binarySearchByRecursion($list, $target, 0, 0); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testBinarySearchByRecursionWithOneElementList() @@ -67,10 +63,10 @@ class SearchesTest extends TestCase $list = [0]; $target = 0; $result = binarySearchByRecursion($list, $target, 0, 0); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 1; $result = binarySearchByRecursion($list, $target, 0, 0); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testBinarySearchByRecursionWithTwoElementList() @@ -78,13 +74,13 @@ class SearchesTest extends TestCase $list = [0, 1]; $target = 0; $result = binarySearchByRecursion($list, $target, 0, 1); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 1; $result = binarySearchByRecursion($list, $target, 0, 1); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 2; $result = binarySearchByRecursion($list, $target, 0, 1); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testBinarySearchByRecursionWithThreeElementList() @@ -92,28 +88,28 @@ class SearchesTest extends TestCase $list = [0, 1, 2]; $target = 0; $result = binarySearchByRecursion($list, $target, 0, 2); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 1; $result = binarySearchByRecursion($list, $target, 0, 2); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 2; $result = binarySearchByRecursion($list, $target, 0, 2); - assertEquals(2, $result); + $this->assertEquals(2, $result); $target = 3; $result = binarySearchByRecursion($list, $target, 0, 2); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testFibonacciSearch() { $test1 = fibonacciPosition(6); - assertEquals(8, $test1); + $this->assertEquals(8, $test1); $test2 = fibonacciPosition(9); - assertEquals(34, $test2); + $this->assertEquals(34, $test2); $test3 = fibonacciPosition(60); - assertEquals(1548008755920, $test3); + $this->assertEquals(1548008755920, $test3); } public function testLinearSearch() @@ -121,7 +117,7 @@ class SearchesTest extends TestCase $list = [5, 7, 8, 11, 12, 15, 17, 18, 20]; $target = 15; $result = linearSearch($list, $target); - assertEquals(6, $result); + $this->assertEquals(6, $result); } public function testLowerBound() @@ -129,7 +125,7 @@ class SearchesTest extends TestCase $list = [1, 2, 3, 3, 3, 4, 5, 9]; $target = 3; $result = lowerBound($list, $target); - assertEquals(2, $result); + $this->assertEquals(2, $result); } public function testUpperBound() @@ -137,7 +133,7 @@ class SearchesTest extends TestCase $list = [1, 2, 3, 3, 3, 4, 5, 9]; $target = 3; $result = upperBound($list, $target); - assertEquals(5, $result); + $this->assertEquals(5, $result); } public function testJumpSearch() @@ -145,7 +141,7 @@ class SearchesTest extends TestCase $list = array( 3,5,6,7,9,10,12,20,22,24); $target = 12; $result = jumpSearch($list, $target); - assertEquals(6, $result); + $this->assertEquals(6, $result); } public function testExponentialSearch() @@ -153,7 +149,7 @@ class SearchesTest extends TestCase $list = array(2,3,4,7,28,35,63,98); $target = 35; $result = exponentialSearch($list, $target); - assertEquals(5, $result); + $this->assertEquals(5, $result); } public function testTernarySearchIterative() @@ -161,16 +157,16 @@ class SearchesTest extends TestCase $list = [0, 5, 7, 10, 15]; $target = 0; $result = ternarySearchIterative($list, $target); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 15; $result = ternarySearchIterative($list, $target); - assertEquals(4, $result); + $this->assertEquals(4, $result); $target = 5; $result = ternarySearchIterative($list, $target); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 6; $result = ternarySearchIterative($list, $target); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testTernarySearchByRecursion() @@ -178,16 +174,16 @@ class SearchesTest extends TestCase $list = [0, 5, 7, 10, 15]; $target = 0; $result = ternarySearchByRecursion($list, $target, 0, 4); - assertEquals(0, $result); + $this->assertEquals(0, $result); $target = 15; $result = ternarySearchByRecursion($list, $target, 0, 4); - assertEquals(4, $result); + $this->assertEquals(4, $result); $target = 5; $result = ternarySearchByRecursion($list, $target, 0, 4); - assertEquals(1, $result); + $this->assertEquals(1, $result); $target = 6; $result = ternarySearchByRecursion($list, $target, 0, 4); - assertEquals(null, $result); + $this->assertEquals(null, $result); } public function testInterpolationSearch() @@ -195,15 +191,15 @@ class SearchesTest extends TestCase $list = [2, 6, 8, 10, 12, 14, 16, 18, 20, 22, 26, 34, 39]; $target = 20; $result = interpolationSearch($list, $target); - assertEquals(8, $result); + $this->assertEquals(8, $result); $target = 12; $result = interpolationSearch($list, $target); - assertEquals(4, $result); + $this->assertEquals(4, $result); $target = 1000; $result = interpolationSearch($list, $target); - assertEquals(null, $result); + $this->assertEquals(null, $result); $target = 39; $result = interpolationSearch($list, $target); - assertEquals(12, $result); + $this->assertEquals(12, $result); } } From a305f06efe1206e87e80fcb32e6533a59dc215e8 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:09:58 +0330 Subject: [PATCH 06/12] fix maths test structure --- tests/Maths/MathsTest.php | 100 ++++++++++++++++++-------------------- 1 file changed, 48 insertions(+), 52 deletions(-) diff --git a/tests/Maths/MathsTest.php b/tests/Maths/MathsTest.php index d3bc9b4..3d6f300 100644 --- a/tests/Maths/MathsTest.php +++ b/tests/Maths/MathsTest.php @@ -1,9 +1,5 @@ assertEquals(1, factorial(1)); + $this->assertEquals(120, factorial(5)); + $this->assertEquals(1, factorial(0)); $this->expectException(\Exception::class); factorial(-25); } public function testIsNumberArmstrong() { - assertTrue(isNumberArmstrong(153)); - assertFalse(isNumberArmstrong(123)); - assertTrue(isNumberArmstrong(370)); - assertFalse(isNumberArmstrong(2468)); + $this->assertTrue(isNumberArmstrong(153)); + $this->assertFalse(isNumberArmstrong(123)); + $this->assertTrue(isNumberArmstrong(370)); + $this->assertFalse(isNumberArmstrong(2468)); } public function testIsNumberPalindromic() { - assertTrue(isNumberPalindromic(121)); - assertFalse(isNumberPalindromic(123)); - assertTrue(isNumberPalindromic(123321)); - assertFalse(isNumberPalindromic(2468)); + $this->assertTrue(isNumberPalindromic(121)); + $this->assertFalse(isNumberPalindromic(123)); + $this->assertTrue(isNumberPalindromic(123321)); + $this->assertFalse(isNumberPalindromic(2468)); } public function testIsPrime() { - assertTrue(isPrime(73)); - assertFalse(isPrime(21)); - assertFalse(isPrime(1)); - assertTrue(isPrime(997)); + $this->assertTrue(isPrime(73)); + $this->assertFalse(isPrime(21)); + $this->assertFalse(isPrime(1)); + $this->assertTrue(isPrime(997)); } public function testAbsoluteMax() { - assertEquals(50, absolute_max(12, 20, 35, 50, 50, 23)); - assertEquals(13, absolute_max(13)); - assertEquals(54, absolute_max(12, 13, 54, 22)); + $this->assertEquals(50, absolute_max(12, 20, 35, 50, 50, 23)); + $this->assertEquals(13, absolute_max(13)); + $this->assertEquals(54, absolute_max(12, 13, 54, 22)); $this->expectException(\Exception::class); absolute_max(); } public function testAbsoluteMin() { - assertEquals(12, absolute_min(12, 20, 35, 50, 50, 23)); - assertEquals(13, absolute_min(13)); - assertEquals(12, absolute_min(12, 13, 54, 22)); + $this->assertEquals(12, absolute_min(12, 20, 35, 50, 50, 23)); + $this->assertEquals(13, absolute_min(13)); + $this->assertEquals(12, absolute_min(12, 13, 54, 22)); $this->expectException(\Exception::class); absolute_min(); } public function testPerfectSquare() { - assertTrue(isPerfectSquare(25)); - assertFalse(isPerfectSquare(43)); - assertFalse(isPerfectSquare(2)); - assertTrue(isPerfectSquare(225)); + $this->assertTrue(isPerfectSquare(25)); + $this->assertFalse(isPerfectSquare(43)); + $this->assertFalse(isPerfectSquare(2)); + $this->assertTrue(isPerfectSquare(225)); } public function testFastExponentiation() { - assertEquals(fastExponentiation(10, 0), 1); - assertEquals(fastExponentiation(10, 1), 10); - assertEquals(fastExponentiation(10, 2), 100); - assertEquals(fastExponentiation(10, 3), 1000); - assertEquals(fastExponentiation(20, 5), 3200000); + $this->assertEquals(1, fastExponentiation(10, 0)); + $this->assertEquals(10, fastExponentiation(10, 1)); + $this->assertEquals(100, fastExponentiation(10, 2)); + $this->assertEquals(1000, fastExponentiation(10, 3)); + $this->assertEquals(3200000, fastExponentiation(20, 5)); } public function testFibonacciSeries() { - assertEquals([0, 1, 1, 2, 3], fibonacciRecursive(5)); - assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], fibonacciRecursive(10)); + $this->assertEquals([0, 1, 1, 2, 3], fibonacciRecursive(5)); + $this->assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], fibonacciRecursive(10)); - assertEquals([0, 1, 1, 2, 3], fibonacciWithBinetFormula(5)); - assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], fibonacciWithBinetFormula(10)); + $this->assertEquals([0, 1, 1, 2, 3], fibonacciWithBinetFormula(5)); + $this->assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], fibonacciWithBinetFormula(10)); } public function testNeonNumber() { - assertTrue(isNumberNeon(1)); - assertFalse(isNumberNeon(43)); - assertFalse(isNumberNeon(123)); - assertTrue(isNumberNeon(9)); + $this->assertTrue(isNumberNeon(1)); + $this->assertFalse(isNumberNeon(43)); + $this->assertFalse(isNumberNeon(123)); + $this->assertTrue(isNumberNeon(9)); } public function testFibonacciGenerator() { - assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); - assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib()))); + $this->assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); + $this->assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib()))); - assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); - assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib()))); + $this->assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); + $this->assertEquals([0, 1, 1, 2, 3, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib()))); } public function testMean() { - assertEquals( + $this->assertEquals( (2 + 4 + 6 + 8 + 20 + 50 + 70) / 7, mean(2, 4, 6, 8, 20, 50, 70) ); - assertEquals( + $this->assertEquals( (-5 - 7 + 10) / 3, mean(-5, -7, 10) ); - assertEquals(-1, mean(-1)); + $this->assertEquals(-1, mean(-1)); } public function testMedian() { - assertEquals(3, median(1, 2, 3, 4, 5)); - assertEquals(4.5, median(1, 2, 3, 4, 5, 6, 7, 8)); - assertEquals(3, median(5, 3, 1, 2, 4)); + $this->assertEquals(3, median(1, 2, 3, 4, 5)); + $this->assertEquals(4.5, median(1, 2, 3, 4, 5, 6, 7, 8)); + $this->assertEquals(3, median(5, 3, 1, 2, 4)); } public function testMode() From e5523e0c4c5116f342d6a576e36db93c0064634a Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:40:29 +0330 Subject: [PATCH 07/12] fix conversions test structure --- tests/Conversions/ConversionsTest.php | 46 +++++++++++++-------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/tests/Conversions/ConversionsTest.php b/tests/Conversions/ConversionsTest.php index cb8fb51..8280a2f 100644 --- a/tests/Conversions/ConversionsTest.php +++ b/tests/Conversions/ConversionsTest.php @@ -1,7 +1,5 @@ assertEquals(7, binaryToDecimal(111)); + $this->assertEquals(5, binaryToDecimal(101)); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Binary Number for Converting it to a Decimal Number.'); binaryToDecimal("this is a string"); @@ -25,8 +23,8 @@ class ConversionsTest extends TestCase public function testDecimalToBinary() { - assertEquals(decimalToBinary(7), 111); - assertEquals(decimalToBinary(5), 101); + $this->assertEquals(111, decimalToBinary(7)); + $this->assertEquals(101, decimalToBinary(5)); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Binary Number.'); decimalToBinary("this is a string"); @@ -34,9 +32,9 @@ class ConversionsTest extends TestCase public function testOctalToDecimal() { - assertEquals(octalToDecimal(10), 8); - assertEquals(octalToDecimal(11), 9); - assertEquals(octalToDecimal(1115), 589); + $this->assertEquals(8, octalToDecimal(10)); + $this->assertEquals(9, octalToDecimal(11)); + $this->assertEquals(589, octalToDecimal(1115)); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Octal Number for Converting it to a Decimal Number.'); octalToDecimal("this is a string"); @@ -44,9 +42,9 @@ class ConversionsTest extends TestCase public function testDecimalToOctal() { - assertEquals(decimalToOctal(8), 10); - assertEquals(decimalToOctal(9), 11); - assertEquals(decimalToOctal(589), 1115); + $this->assertEquals(10, decimalToOctal(8)); + $this->assertEquals(11, decimalToOctal(9)); + $this->assertEquals(1115, decimalToOctal(589)); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to an Octal Number.'); decimalToOctal("this is a string"); @@ -54,9 +52,9 @@ class ConversionsTest extends TestCase public function testDecimalToHex() { - assertEquals(decimalToHex(10), 'A'); - assertEquals(decimalToHex(489201875), '1D28A0D3'); - assertEquals(decimalToHex(171), 'AB'); + $this->assertEquals('A', decimalToHex(10)); + $this->assertEquals('1D28A0D3', decimalToHex(489201875)); + $this->assertEquals('AB', decimalToHex(171)); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Hexadecimal Number.'); decimalToHex("this is a string"); @@ -64,9 +62,9 @@ class ConversionsTest extends TestCase public function testHexToDecimal() { - assertEquals(hexToDecimal('A'), 10); - assertEquals(hexToDecimal('1D28A0D3'), 489201875); - assertEquals(hexToDecimal('AB'), 171); + $this->assertEquals(10, hexToDecimal('A')); + $this->assertEquals(489201875, hexToDecimal('1D28A0D3')); + $this->assertEquals(171, hexToDecimal('AB')); $this->expectException(\Exception::class); $this->expectExceptionMessage('Please pass a valid Hexadecimal Number for Converting it to a Decimal Number.'); hexToDecimal("this is a string"); @@ -74,12 +72,12 @@ class ConversionsTest extends TestCase public function testSpeedConversion() { - assertEquals(convertSpeed(5, 'm/s', 'mph'), 11.18); - assertEquals(convertSpeed(5, 'ft/s', 'km/h'), 5.49); - assertEquals(convertSpeed(3, 'km/h', 'km/h'), 3); - assertEquals(convertSpeed(7, 'kn', 'km/h'), 12.96); - assertEquals(convertSpeed(12, 'mph', 'km/h'), 19.31); - assertEquals(convertSpeed(0.514, 'm/s', 'kn'), 1); + $this->assertEquals(11.18, convertSpeed(5, 'm/s', 'mph')); + $this->assertEquals(5.49, convertSpeed(5, 'ft/s', 'km/h')); + $this->assertEquals(3, convertSpeed(3, 'km/h', 'km/h')); + $this->assertEquals(12.96, convertSpeed(7, 'kn', 'km/h')); + $this->assertEquals(19.31, convertSpeed(12, 'mph', 'km/h')); + $this->assertEquals(1, convertSpeed(0.514, 'm/s', 'kn')); $this->expectException(\Exception::class); convertSpeed('1', 'km/h', 'mph'); From 1a04f5ea8f89ab273b442236b473b19d2d335197 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:44:04 +0330 Subject: [PATCH 08/12] fix morse test structure --- tests/Ciphers/MorseCodeTest.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/Ciphers/MorseCodeTest.php b/tests/Ciphers/MorseCodeTest.php index 10bce3b..bdb2b03 100644 --- a/tests/Ciphers/MorseCodeTest.php +++ b/tests/Ciphers/MorseCodeTest.php @@ -1,7 +1,5 @@ assertEquals('TEST 123', decode(encode('TEST 123'))); } } From 5817388856c96ac56eabee5b94eb888c3ee14516 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:45:09 +0330 Subject: [PATCH 09/12] fix mono alphabetic cipher test structure --- tests/Ciphers/MonoAlphabeticCipherTest.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/Ciphers/MonoAlphabeticCipherTest.php b/tests/Ciphers/MonoAlphabeticCipherTest.php index de90096..b8f9978 100644 --- a/tests/Ciphers/MonoAlphabeticCipherTest.php +++ b/tests/Ciphers/MonoAlphabeticCipherTest.php @@ -2,8 +2,6 @@ use PHPUnit\Framework\TestCase; -use function PHPUnit\Framework\assertEquals; - require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../Ciphers/MonoAlphabeticCipher.php'; @@ -15,7 +13,7 @@ class MonoAlphabeticCipherTest extends TestCase $key = "yhkqgvxfoluapwmtzecjdbsnri"; $text = "I love1234 GitHub"; $encryptedText = "O ambg XojFdh"; - assertEquals(maEncrypt($key, $alphabet, $text), $encryptedText); - assertEquals(maDecrypt($key, $alphabet, $encryptedText), "I love GitHub"); + $this->assertEquals(maEncrypt($key, $alphabet, $text), $encryptedText); + $this->assertEquals(maDecrypt($key, $alphabet, $encryptedText), "I love GitHub"); } } From b814cf266929b3f1f618c41e428b6a06a0de6242 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Wed, 4 Oct 2023 23:48:42 +0330 Subject: [PATCH 10/12] fix some ci warnings --- Graphs/BreadthFirstSearch.php | 3 +- Searches/ExponentialSearch.php | 35 ++++++------- tests/Ciphers/CiphersTest.php | 2 - tests/Sorting/SortingTests.php | 96 ++++++++++++++++++++++++++++++++-- 4 files changed, 110 insertions(+), 26 deletions(-) diff --git a/Graphs/BreadthFirstSearch.php b/Graphs/BreadthFirstSearch.php index 68579e1..205e7f1 100644 --- a/Graphs/BreadthFirstSearch.php +++ b/Graphs/BreadthFirstSearch.php @@ -1,7 +1,8 @@ $ceiling) { return -1; } - // search the left part of the $array - // If the $middle element is greater than the $value + + // search the left part of the $array + // If the $middle element is greater than the $value if ($arr[$mid] > $value) { return binarySearch($arr, $value, $floor, $mid - 1); - } - // search the right part of the $array - // If the $middle element is lower than the $value - else { + } else { // search the right part of the $array If the $middle element is lower than the $value return binarySearch($arr, $value, $mid + 1, $ceiling); } } @@ -47,13 +45,12 @@ function binarySearch($arr, $value, $floor, $ceiling) */ function exponentialSearch($arr, $value) { - - // If $value is the first element of the $array return this position + // If $value is the first element of the $array return this position if ($arr[0] === $value) { return 0; } - // Find range for binary search + // Find range for binary search $i = 1; $length = count($arr); while ($i < $length && $arr[$i] <= $value) { diff --git a/tests/Ciphers/CiphersTest.php b/tests/Ciphers/CiphersTest.php index 241e729..83e5254 100755 --- a/tests/Ciphers/CiphersTest.php +++ b/tests/Ciphers/CiphersTest.php @@ -1,7 +1,5 @@ assertEquals([272, 1392, 1689, 1807, 1856, 2246, 2811, 2847, 3720, 3938, 4204, 4337, 4605, 4696, 4813, 5239, 5257, 5520, 5523, 5676, 6466, 6506, 7018, 7515, 7762, 7853, 7873, 8181, 8350, 8459, 8935, 9358, 9508, 9592, 10786, 10867, 11122, 11754, 12029, 12440, 12973, 13720, 13732, 14098, 14123, 14202, 15003, 15352, 16122, 16387, 16544, 16677, 16868, 17860, 18158, 18362, 18456, 18492, 18708, 19074, 19713, 19756, 20620, 21165, 21746, 22192, 22296, 22479, 22874, 23232, 23606, 23954, 24105, 24689, 24714, 24932, 25236, 25385, 25774, 26277, 26281, 26993, 27230, 27760, 27892, 28229, 28302, 28309, 28493, 28651, 29373, 29411, 29724, 30110, 30258, 30298, 30819, 30948, 31159, 31263, 31577, 31805, 31919, 32074, 32158, 32178, 32392, 33446, 33679, 33963, 33982, 34201, 34649, 34671, 34925, 35245, 35374, 36141, 36625, 36828, 36852, 37348, 38265, 38386, 39583, 39621, 40171, 40206, 40372, 40459, 40565, 40742, 40789, 40858, 42310, 42348, 42422, 42685, 43340, 43688, 43780, 43836, 44044, 44518, 44628, 44637, 44654, 45344, 45519, 45755, 45799, 45894, 46184, 46186, 46528, 46574, 46704, 47432, 47489, 47596, 47615, 47662, 47910, 48208, 48964, 49048, 49052, 49168, 49709, 49809, 49935, 50209, 50596, 50800, 51158, 51433, 51830, 51886, 52068, 52328, 52905, 52928, 53635, 54211, 54616, 54955, 55295, 55416, 55515, 55549, 55908, 56063, 56301, 56494, 56841, 56963, 56992, 57402, 57954, 57981, 58213, 58223, 58336, 59748, 59973, 59992, 61349, 61591, 61968, 62310, 63015, 63178, 63245, 63395, 63771, 63968, 64204, 64208, 65764, 66174, 66178, 66206, 66570, 67025, 67338, 67452, 67957, 68125, 68514, 68756, 68831, 68975, 69091, 69858, 70466, 70474, 71526, 71774, 72472, 72686, 72849, 73437, 73907, 74474, 74813, 74872, 75043, 75045, 75190, 75197, 75786, 76201, 76277, 76474, 76818, 77026, 77849, 77977, 78095, 78105, 78533, 78629, 78828, 79028, 79488, 79935, 80188, 81097, 81960, 82300, 82656, 82785, 83246, 83638, 84076, 84402, 85799, 86070, 86198, 86309, 86358, 86805, 86814, 86897, 86968, 87450, 88246, 90235, 90728, 90876, 91503, 92106, 92215, 92559, 92837, 93070, 93144, 93729, 94083, 94257, 94706, 94807, 96145, 96407, 96782, 97156, 97222, 97577, 97799, 98758, 98845, 99156, 99211, 99272, 99519, 99711], $sorted); + $this->assertEquals([ + 272, 1392, 1689, 1807, 1856, 2246, 2811, 2847, 3720, 3938, 4204, 4337, 4605, 4696, 4813, 5239, 5257, 5520, + 5523, 5676, 6466, 6506, 7018, 7515, 7762, 7853, 7873, 8181, 8350, 8459, 8935, 9358, 9508, 9592, 10786, + 10867, 11122, 11754, 12029, 12440, 12973, 13720, 13732, 14098, 14123, 14202, 15003, 15352, 16122, 16387, + 16544, 16677, 16868, 17860, 18158, 18362, 18456, 18492, 18708, 19074, 19713, 19756, 20620, 21165, 21746, + 22192, 22296, 22479, 22874, 23232, 23606, 23954, 24105, 24689, 24714, 24932, 25236, 25385, 25774, 26277, + 26281, 26993, 27230, 27760, 27892, 28229, 28302, 28309, 28493, 28651, 29373, 29411, 29724, 30110, 30258, + 30298, 30819, 30948, 31159, 31263, 31577, 31805, 31919, 32074, 32158, 32178, 32392, 33446, 33679, 33963, + 33982, 34201, 34649, 34671, 34925, 35245, 35374, 36141, 36625, 36828, 36852, 37348, 38265, 38386, 39583, + 39621, 40171, 40206, 40372, 40459, 40565, 40742, 40789, 40858, 42310, 42348, 42422, 42685, 43340, 43688, + 43780, 43836, 44044, 44518, 44628, 44637, 44654, 45344, 45519, 45755, 45799, 45894, 46184, 46186, 46528, + 46574, 46704, 47432, 47489, 47596, 47615, 47662, 47910, 48208, 48964, 49048, 49052, 49168, 49709, 49809, + 49935, 50209, 50596, 50800, 51158, 51433, 51830, 51886, 52068, 52328, 52905, 52928, 53635, 54211, 54616, + 54955, 55295, 55416, 55515, 55549, 55908, 56063, 56301, 56494, 56841, 56963, 56992, 57402, 57954, 57981, + 58213, 58223, 58336, 59748, 59973, 59992, 61349, 61591, 61968, 62310, 63015, 63178, 63245, 63395, 63771, + 63968, 64204, 64208, 65764, 66174, 66178, 66206, 66570, 67025, 67338, 67452, 67957, 68125, 68514, 68756, + 68831, 68975, 69091, 69858, 70466, 70474, 71526, 71774, 72472, 72686, 72849, 73437, 73907, 74474, 74813, + 74872, 75043, 75045, 75190, 75197, 75786, 76201, 76277, 76474, 76818, 77026, 77849, 77977, 78095, 78105, + 78533, 78629, 78828, 79028, 79488, 79935, 80188, 81097, 81960, 82300, 82656, 82785, 83246, 83638, 84076, + 84402, 85799, 86070, 86198, 86309, 86358, 86805, 86814, 86897, 86968, 87450, 88246, 90235, 90728, 90876, + 91503, 92106, 92215, 92559, 92837, 93070, 93144, 93729, 94083, 94257, 94706, 94807, 96145, 96407, 96782, + 97156, 97222, 97577, 97799, 98758, 98845, 99156, 99211, 99272, 99519, 99711 + ], $sorted); } public function testCountSort() @@ -54,9 +98,53 @@ class SortingTests extends TestCase public function testQuickSort() { - $array = [51158,1856,8459,67957,59748,58213,90876,39621,66570,64204,79935,27892,47615,94706,34201,74474,63968,4337,43688,42685,31577,5239,25385,56301,94083,23232,67025,44044,74813,34671,90235,65764,49709,12440,21165,20620,38265,12973,25236,93144,13720,4204,77026,42348,19756,97222,78828,73437,48208,69858,19713,29411,49809,66174,5257,43340,40565,9592,52328,16677,38386,55416,99519,13732,84076,52905,47662,31805,46184,2811,35374,50800,53635,51886,49052,75197,3720,75045,28309,63771,71526,16122,36625,44654,86814,98845,44637,54955,24714,81960,78095,49048,99711,272,45755,31919,8181,1392,15352,82656,27760,18362,43780,50209,51433,2847,62310,87450,22874,40789,56841,52928,5523,76474,8935,63245,16387,21746,47596,84402,49168,58223,26993,55908,92837,64208,86309,30819,83638,9508,44628,10786,68125,14123,70474,50596,44518,74872,61968,36828,17860,4605,68756,86070,52068,51830,56992,45799,42422,68514,92559,40206,31263,71774,14202,94807,25774,15003,54211,18708,32074,43836,48964,40742,26281,67338,75786,34925,34649,45519,72472,80188,40858,83246,92215,66178,67452,86198,82300,45894,97156,73907,31159,7018,55549,35245,68975,88246,14098,59973,7762,40459,86358,63178,47489,55515,79488,46528,99272,10867,75190,56963,5520,56494,42310,40171,78105,29724,30110,28493,36141,22479,85799,70466,92106,16868,57402,4813,47432,24689,78533,97577,32178,30258,82785,56063,76277,96407,77849,1807,45344,30298,18158,49935,90728,22192,36852,33982,66206,30948,40372,33446,99156,28651,61591,79028,1689,94257,32158,11122,81097,57981,26277,7515,7873,8350,28229,24105,76818,86897,18456,29373,7853,24932,93070,4696,63015,9358,28302,3938,11754,33679,18492,91503,63395,12029,23954,27230,58336,16544,23606,61349,37348,78629,96145,57954,32392,76201,54616,59992,5676,97799,47910,98758,75043,72849,6466,68831,2246,69091,22296,6506,93729,86968,39583,46186,96782,19074,46574,46704,99211,55295,33963,77977,86805,72686]; + $array = [ + 51158, 1856, 8459, 67957, 59748, 58213, 90876, 39621, 66570, 64204, 79935, 27892, 47615, 94706, 34201, + 74474, 63968, 4337, 43688, 42685, 31577, 5239, 25385, 56301, 94083, 23232, 67025, 44044, 74813, 34671, + 90235, 65764, 49709, 12440, 21165, 20620, 38265, 12973, 25236, 93144, 13720, 4204, 77026, 42348, 19756, + 97222, 78828, 73437, 48208, 69858, 19713, 29411, 49809, 66174, 5257, 43340, 40565, 9592, 52328, 16677, + 38386, 55416, 99519, 13732, 84076, 52905, 47662, 31805, 46184, 2811, 35374, 50800, 53635, 51886, 49052, + 75197, 3720, 75045, 28309, 63771, 71526, 16122, 36625, 44654, 86814, 98845, 44637, 54955, 24714, 81960, + 78095, 49048, 99711, 272, 45755, 31919, 8181, 1392, 15352, 82656, 27760, 18362, 43780, 50209, 51433, 2847, + 62310, 87450, 22874, 40789, 56841, 52928, 5523, 76474, 8935, 63245, 16387, 21746, 47596, 84402, 49168, + 58223, 26993, 55908, 92837, 64208, 86309, 30819, 83638, 9508, 44628, 10786, 68125, 14123, 70474, 50596, + 44518, 74872, 61968, 36828, 17860, 4605, 68756, 86070, 52068, 51830, 56992, 45799, 42422, 68514, 92559, + 40206, 31263, 71774, 14202, 94807, 25774, 15003, 54211, 18708, 32074, 43836, 48964, 40742, 26281, 67338, + 75786, 34925, 34649, 45519, 72472, 80188, 40858, 83246, 92215, 66178, 67452, 86198, 82300, 45894, 97156, + 73907, 31159, 7018, 55549, 35245, 68975, 88246, 14098, 59973, 7762, 40459, 86358, 63178, 47489, 55515, + 79488, 46528, 99272, 10867, 75190, 56963, 5520, 56494, 42310, 40171, 78105, 29724, 30110, 28493, 36141, + 22479, 85799, 70466, 92106, 16868, 57402, 4813, 47432, 24689, 78533, 97577, 32178, 30258, 82785, 56063, + 76277, 96407, 77849, 1807, 45344, 30298, 18158, 49935, 90728, 22192, 36852, 33982, 66206, 30948, 40372, + 33446, 99156, 28651, 61591, 79028, 1689, 94257, 32158, 11122, 81097, 57981, 26277, 7515, 7873, 8350, 28229, + 24105, 76818, 86897, 18456, 29373, 7853, 24932, 93070, 4696, 63015, 9358, 28302, 3938, 11754, 33679, 18492, + 91503, 63395, 12029, 23954, 27230, 58336, 16544, 23606, 61349, 37348, 78629, 96145, 57954, 32392, 76201, + 54616, 59992, 5676, 97799, 47910, 98758, 75043, 72849, 6466, 68831, 2246, 69091, 22296, 6506, 93729, 86968, + 39583, 46186, 96782, 19074, 46574, 46704, 99211, 55295, 33963, 77977, 86805, 72686 + ]; $sorted = quickSort($array); - $this->assertEquals([272, 1392, 1689, 1807, 1856, 2246, 2811, 2847, 3720, 3938, 4204, 4337, 4605, 4696, 4813, 5239, 5257, 5520, 5523, 5676, 6466, 6506, 7018, 7515, 7762, 7853, 7873, 8181, 8350, 8459, 8935, 9358, 9508, 9592, 10786, 10867, 11122, 11754, 12029, 12440, 12973, 13720, 13732, 14098, 14123, 14202, 15003, 15352, 16122, 16387, 16544, 16677, 16868, 17860, 18158, 18362, 18456, 18492, 18708, 19074, 19713, 19756, 20620, 21165, 21746, 22192, 22296, 22479, 22874, 23232, 23606, 23954, 24105, 24689, 24714, 24932, 25236, 25385, 25774, 26277, 26281, 26993, 27230, 27760, 27892, 28229, 28302, 28309, 28493, 28651, 29373, 29411, 29724, 30110, 30258, 30298, 30819, 30948, 31159, 31263, 31577, 31805, 31919, 32074, 32158, 32178, 32392, 33446, 33679, 33963, 33982, 34201, 34649, 34671, 34925, 35245, 35374, 36141, 36625, 36828, 36852, 37348, 38265, 38386, 39583, 39621, 40171, 40206, 40372, 40459, 40565, 40742, 40789, 40858, 42310, 42348, 42422, 42685, 43340, 43688, 43780, 43836, 44044, 44518, 44628, 44637, 44654, 45344, 45519, 45755, 45799, 45894, 46184, 46186, 46528, 46574, 46704, 47432, 47489, 47596, 47615, 47662, 47910, 48208, 48964, 49048, 49052, 49168, 49709, 49809, 49935, 50209, 50596, 50800, 51158, 51433, 51830, 51886, 52068, 52328, 52905, 52928, 53635, 54211, 54616, 54955, 55295, 55416, 55515, 55549, 55908, 56063, 56301, 56494, 56841, 56963, 56992, 57402, 57954, 57981, 58213, 58223, 58336, 59748, 59973, 59992, 61349, 61591, 61968, 62310, 63015, 63178, 63245, 63395, 63771, 63968, 64204, 64208, 65764, 66174, 66178, 66206, 66570, 67025, 67338, 67452, 67957, 68125, 68514, 68756, 68831, 68975, 69091, 69858, 70466, 70474, 71526, 71774, 72472, 72686, 72849, 73437, 73907, 74474, 74813, 74872, 75043, 75045, 75190, 75197, 75786, 76201, 76277, 76474, 76818, 77026, 77849, 77977, 78095, 78105, 78533, 78629, 78828, 79028, 79488, 79935, 80188, 81097, 81960, 82300, 82656, 82785, 83246, 83638, 84076, 84402, 85799, 86070, 86198, 86309, 86358, 86805, 86814, 86897, 86968, 87450, 88246, 90235, 90728, 90876, 91503, 92106, 92215, 92559, 92837, 93070, 93144, 93729, 94083, 94257, 94706, 94807, 96145, 96407, 96782, 97156, 97222, 97577, 97799, 98758, 98845, 99156, 99211, 99272, 99519, 99711], $sorted); + $this->assertEquals([ + 272, 1392, 1689, 1807, 1856, 2246, 2811, 2847, 3720, 3938, 4204, 4337, 4605, 4696, 4813, 5239, 5257, 5520, + 5523, 5676, 6466, 6506, 7018, 7515, 7762, 7853, 7873, 8181, 8350, 8459, 8935, 9358, 9508, 9592, 10786, + 10867, 11122, 11754, 12029, 12440, 12973, 13720, 13732, 14098, 14123, 14202, 15003, 15352, 16122, 16387, + 16544, 16677, 16868, 17860, 18158, 18362, 18456, 18492, 18708, 19074, 19713, 19756, 20620, 21165, 21746, + 22192, 22296, 22479, 22874, 23232, 23606, 23954, 24105, 24689, 24714, 24932, 25236, 25385, 25774, 26277, + 26281, 26993, 27230, 27760, 27892, 28229, 28302, 28309, 28493, 28651, 29373, 29411, 29724, 30110, 30258, + 30298, 30819, 30948, 31159, 31263, 31577, 31805, 31919, 32074, 32158, 32178, 32392, 33446, 33679, 33963, + 33982, 34201, 34649, 34671, 34925, 35245, 35374, 36141, 36625, 36828, 36852, 37348, 38265, 38386, 39583, + 39621, 40171, 40206, 40372, 40459, 40565, 40742, 40789, 40858, 42310, 42348, 42422, 42685, 43340, 43688, + 43780, 43836, 44044, 44518, 44628, 44637, 44654, 45344, 45519, 45755, 45799, 45894, 46184, 46186, 46528, + 46574, 46704, 47432, 47489, 47596, 47615, 47662, 47910, 48208, 48964, 49048, 49052, 49168, 49709, 49809, + 49935, 50209, 50596, 50800, 51158, 51433, 51830, 51886, 52068, 52328, 52905, 52928, 53635, 54211, 54616, + 54955, 55295, 55416, 55515, 55549, 55908, 56063, 56301, 56494, 56841, 56963, 56992, 57402, 57954, 57981, + 58213, 58223, 58336, 59748, 59973, 59992, 61349, 61591, 61968, 62310, 63015, 63178, 63245, 63395, 63771, + 63968, 64204, 64208, 65764, 66174, 66178, 66206, 66570, 67025, 67338, 67452, 67957, 68125, 68514, 68756, + 68831, 68975, 69091, 69858, 70466, 70474, 71526, 71774, 72472, 72686, 72849, 73437, 73907, 74474, 74813, + 74872, 75043, 75045, 75190, 75197, 75786, 76201, 76277, 76474, 76818, 77026, 77849, 77977, 78095, 78105, + 78533, 78629, 78828, 79028, 79488, 79935, 80188, 81097, 81960, 82300, 82656, 82785, 83246, 83638, 84076, + 84402, 85799, 86070, 86198, 86309, 86358, 86805, 86814, 86897, 86968, 87450, 88246, 90235, 90728, 90876, + 91503, 92106, 92215, 92559, 92837, 93070, 93144, 93729, 94083, 94257, 94706, 94807, 96145, 96407, 96782, + 97156, 97222, 97577, 97799, 98758, 98845, 99156, 99211, 99272, 99519, 99711 + ], $sorted); } public function testQuickSortWithEmptyInput() From 29db48075ef56e551cd28ca943e229beb86a1502 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Thu, 5 Oct 2023 00:10:11 +0330 Subject: [PATCH 11/12] ignoring warnings in cs checker --- .github/workflows/code-style.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/code-style.yml b/.github/workflows/code-style.yml index 16ab9a5..71333e1 100644 --- a/.github/workflows/code-style.yml +++ b/.github/workflows/code-style.yml @@ -22,4 +22,4 @@ jobs: run: composer update --prefer-dist --no-progress --no-suggest - name: Run script - run: vendor/bin/phpcs \ No newline at end of file + run: vendor/bin/phpcs -n \ No newline at end of file From 658618ae9510e50f39d021460482280bec14bf32 Mon Sep 17 00:00:00 2001 From: salehhashemi1992 <81674631+salehhashemi1992@users.noreply.github.com> Date: Thu, 5 Oct 2023 09:59:11 +0330 Subject: [PATCH 12/12] fix comment indents and docs --- Ciphers/MonoAlphabeticCipher.php | 5 ++- DataStructures/SinglyLinkedList.php | 1 + Maths/Factorial.php | 10 +++--- Searches/ExponentialSearch.php | 7 +++-- Searches/InterpolationSearch.php | 34 ++++++++++----------- Searches/JumpSearch.php | 3 +- Searches/TernarySearch.php | 47 ++++++++++++++--------------- Sorting/HeapSort.php | 15 ++++++--- Strings/CountVowels.php | 25 +++++++++------ Strings/MaxCharacter.php | 28 ++++++++++------- 10 files changed, 99 insertions(+), 76 deletions(-) diff --git a/Ciphers/MonoAlphabeticCipher.php b/Ciphers/MonoAlphabeticCipher.php index 6b362db..dd8be15 100644 --- a/Ciphers/MonoAlphabeticCipher.php +++ b/Ciphers/MonoAlphabeticCipher.php @@ -7,9 +7,11 @@ function monoAlphabeticCipher($key, $alphabet, $text) { $cipherText = ''; // the cipher text (can be decrypted and encrypted) + // check if the text length matches if (strlen($key) != strlen($alphabet)) { return false; - } // check if the text length matches + } + $text = preg_replace('/[0-9]+/', '', $text); // remove all the numbers for ($i = 0; $i < strlen($text); $i++) { @@ -20,6 +22,7 @@ function monoAlphabeticCipher($key, $alphabet, $text) $cipherText .= ( ctype_upper($text[$i]) ? strtoupper($key[$index]) : $key[$index] ); } } + return $cipherText; } diff --git a/DataStructures/SinglyLinkedList.php b/DataStructures/SinglyLinkedList.php index 7256ed7..b7a97bc 100644 --- a/DataStructures/SinglyLinkedList.php +++ b/DataStructures/SinglyLinkedList.php @@ -7,6 +7,7 @@ class SinglyLinkedList { public ?SinglyLinkedList $next = null; public $data; + public function __construct($data) { $this->data = $data; diff --git a/Maths/Factorial.php b/Maths/Factorial.php index cce08d6..e004100 100644 --- a/Maths/Factorial.php +++ b/Maths/Factorial.php @@ -12,23 +12,25 @@ */ function factorial(int $number) { - static $cache = []; -//internal caching memory for speed + static $cache = []; //internal caching memory for speed if ($number < 0) { throw new \Exception("Negative numbers are not allowed for calculating Factorial"); } + + // Factorial of 0 is 1 if ($number === 0) { return 1; -// Factorial of 0 is 1 } if (isset($cache[$number])) { return $cache[$number]; } + // Recursion since x! = x * (x-1)! $fact = ($number * factorial($number - 1)); -// Recursion since x! = x * (x-1)! + $cache[$number] = $fact; + return $fact; } diff --git a/Searches/ExponentialSearch.php b/Searches/ExponentialSearch.php index 9c5c2a6..1ea8a1c 100644 --- a/Searches/ExponentialSearch.php +++ b/Searches/ExponentialSearch.php @@ -20,10 +20,12 @@ function binarySearch($arr, $value, $floor, $ceiling) { // Get $middle index $mid = floor(($floor + $ceiling) / 2); -// Return position if $value is at the $mid position + + // Return position if $value is at the $mid position if ($arr[$mid] === $value) { return (int) $mid; } + //Return -1 is range is wrong if ($floor > $ceiling) { return -1; @@ -58,6 +60,7 @@ function exponentialSearch($arr, $value) } $floor = $i / 2; $ceiling = min($i, $length); -// Call binary search for the range found above + + // Call binary search for the range found above return binarySearch($arr, $value, $floor, $ceiling); } diff --git a/Searches/InterpolationSearch.php b/Searches/InterpolationSearch.php index bb73d92..fcd3dee 100644 --- a/Searches/InterpolationSearch.php +++ b/Searches/InterpolationSearch.php @@ -18,36 +18,36 @@ */ function interpolationSearch($arr, $key) { - $length = count($arr) - 1; $low = 0; $high = $length; $position = -1; -//loop, between low & high + //loop, between low & high while ($low <= $high && $key >= $arr[$low] && $key <= $arr[$high]) { -//GET INDEX + //GET INDEX $delta = ($key - $arr[$low]) / ($arr[$high] - $arr[$low]); $index = $low + floor(($high - $low) * $delta); -//GET VALUE OF INDEX IN ARRAY... + + //GET VALUE OF INDEX IN ARRAY... $indexValue = $arr[$index]; + if ($indexValue === $key) { - //index value equals key - //FOUND TARGET - //return index value - $position = $index; + //index value equals key + //FOUND TARGET + //return index value + $position = $index; return (int) $position; - } - if ($indexValue < $key) { - //index value lower than key - //increase low index + } elseif ($indexValue < $key) { + //index value lower than key + //increase low index $low = $index + 1; - } - if ($indexValue > $key) { - //index value higher than key - //decrease high index + } elseif ($indexValue > $key) { + //index value higher than key + //decrease high index $high = $index - 1; } } - //when key not found in array or array not sorted + + //when key not found in array or array not sorted return null; } diff --git a/Searches/JumpSearch.php b/Searches/JumpSearch.php index 7be70de..a84daa7 100644 --- a/Searches/JumpSearch.php +++ b/Searches/JumpSearch.php @@ -14,7 +14,8 @@ function jumpSearch($list, $key) { /*number of elements in the sorted array*/ $num = count($list); -/*block size to be jumped*/ + + /*block size to be jumped*/ $step = (int)sqrt($num); $prev = 0; diff --git a/Searches/TernarySearch.php b/Searches/TernarySearch.php index 21e4aad..61dbee1 100644 --- a/Searches/TernarySearch.php +++ b/Searches/TernarySearch.php @@ -10,75 +10,72 @@ */ function ternarySearchByRecursion($arr, $key, $low, $high) { - - //Return -1 if high lesser than low, we can't find item in the whole array + // Return null if high is less than low (base case: key not found). if ($high < $low) { return null; } - //get $mid1 and $mid2 + // Calculate the indices of the first and second midpoints. $mid1 = floor($low + ($high - $low) / 3); $mid2 = floor($high - ($high - $low) / 3); -// check if $key is found at any $mid + + // Check if key is located at either midpoint. if ($arr[$mid1] === $key) { -// return index of $key if found return $mid1; } + if ($arr[$mid2] === $key) { -// return index of $key if found return $mid2; } - // since the $key is not found at $mid, - // check in which region it is present - // and repeat the Search operation - // in that region + // Determine which section to continue searching in. if ($key < $arr[$mid1]) { -// the $key lies in between $low and $mid1 + // Key is in the left section, between $low and $mid1. return ternarySearchByRecursion($arr, $key, $low, $mid1 - 1); } elseif ($key > $arr[$mid2]) { - // the $key lies in between $mid2 and $high + // Key is in the right section, between $mid2 and $high. return ternarySearchByRecursion($arr, $key, $mid2 + 1, $high); } else { - // the $key lies in between $mid1 and $mid2 + // Key is in the middle section, between $mid1 and $mid2. return ternarySearchByRecursion($arr, $key, $mid1 + 1, $mid2 - 1); } } function ternarySearchIterative($arr, $key) { + // Initialize low and high pointers. $low = 0; $high = count($arr) - 1; + + // Continue searching while the high pointer is greater than or equal to the low pointer. while ($high >= $low) { - // find the $mid1 and $mid2 + // Calculate the first and second midpoints. $mid1 = floor($low + ($high - $low) / 3); $mid2 = floor($high - ($high - $low) / 3); - // check if $key is found at any $mid + + // Check if the key is found at either midpoint. if ($arr[$mid1] === $key) { -// return index of $key if found return $mid1; } + if ($arr[$mid2] === $key) { - // return index of $key if found return $mid2; } - // since the $key is not found at $mid, - // check in which region it is present - // and repeat the Search operation - // in that region + // Determine the section to continue the search in. if ($key < $arr[$mid1]) { - // the $key lies in between $low and $mid1 + // Key is in the left section, update the high pointer. $high = $mid1 - 1; } elseif ($key > $arr[$mid2]) { - // the $key lies in between $mid2 and $high + // Key is in the right section, update the low pointer. $low = $mid2 + 1; } else { - // the $key lies in between $mid1 and $mid2 + // Key is in the middle section, update both pointers. $low = $mid1 + 1; $high = $mid2 - 1; } } - // the $key was not found + + // Key was not found. return null; } diff --git a/Sorting/HeapSort.php b/Sorting/HeapSort.php index d999967..8cd0c52 100644 --- a/Sorting/HeapSort.php +++ b/Sorting/HeapSort.php @@ -13,24 +13,29 @@ */ function heapSort(array $arr): array { + // Get the number of elements in the array. $n = count($arr); + + // Throw an exception if the array has no elements. if ($n <= 0) { throw new \UnexpectedValueException('Input array must have at least one element.'); } - // Build heap - for ($i = $n / 2 - 1; $i >= 0; $i--) { + // Build a max heap from the array. + for ($i = floor($n / 2) - 1; $i >= 0; $i--) { heapify($arr, $n, $i); } - // Extract elements from heap one by one + // Extract elements from the max heap and build the sorted array. for ($i = $n - 1; $i >= 0; $i--) { -// Swap + // Swap the root(maximum value) of the heap with the last element of the heap. [$arr[0], $arr[$i]] = [$arr[$i], $arr[0]]; -// Heapify the reduced heap + + // Heapify the reduced heap. heapify($arr, $i, 0); } + // Return the sorted array. return $arr; } diff --git a/Strings/CountVowels.php b/Strings/CountVowels.php index 34a78c0..8351378 100644 --- a/Strings/CountVowels.php +++ b/Strings/CountVowels.php @@ -9,26 +9,31 @@ * @return int $numberOfVowels * @throws \Exception */ -function countVowelsSimple(string $string) +function countVowelsSimple(string $string): int { + // Check for an empty string and throw an exception if so. if (empty($string)) { - throw new \Exception('Please pass a non-empty string value'); + throw new \Exception('Please pass a non-empty string value.'); } + // Initialize variables. $numberOfVowels = 0; - $vowels = ['a', 'e', 'i', 'o', 'u']; -// Vowels Set - $string = strtolower($string); -// For case-insensitive checking - $characters = str_split($string); -// Splitting the string to a Character Array. + $vowels = ['a', 'e', 'i', 'o', 'u']; // Set of vowels for comparison. + // Convert the string to lowercase for case-insensitive comparison. + $string = strtolower($string); + + // Split the string into an array of characters. + $characters = str_split($string); + + // Loop through each character to count the vowels. foreach ($characters as $character) { if (in_array($character, $vowels)) { $numberOfVowels++; } } + // Return the total number of vowels found. return $numberOfVowels; } @@ -45,8 +50,8 @@ function countVowelsRegex(string $string) if (empty($string)) { throw new \Exception('Please pass a non-empty string value'); } - $string = strtolower($string); -// For case-insensitive checking + + $string = strtolower($string); // For case-insensitive checking return preg_match_all('/[a,e,i,o,u]/', $string); } diff --git a/Strings/MaxCharacter.php b/Strings/MaxCharacter.php index 7c74ed8..d64c2e0 100644 --- a/Strings/MaxCharacter.php +++ b/Strings/MaxCharacter.php @@ -8,28 +8,34 @@ * @return string * @throws \Exception */ -function maxCharacter(string $string) +function maxCharacter(string $string): string { + // Throw an exception if the string is empty. if (empty($string)) { - throw new \Exception('Please pass a non-empty string value'); + throw new \Exception('Please pass a non-empty string value.'); } + // Initialize an associative array to hold character counts. $characterCountTable = []; -// A variable to maintain the character counts - $string = strtolower($string); -// For case-insensitive checking - $characters = str_split($string); -// Splitting the string to a Character Array. + // Convert the string to lowercase for case-insensitive analysis. + $string = strtolower($string); + + // Convert the string into an array of characters. + $characters = str_split($string); + + // Loop through the characters to populate the count table. foreach ($characters as $character) { - $currentCharacterCount = 1; - if (isset($characterCountTable[$character])) { - $currentCharacterCount = $characterCountTable[$character] + 1; - } + // Initialize or update the count of the current character. + $currentCharacterCount = isset($characterCountTable[$character]) ? $characterCountTable[$character] + 1 : 1; + // Update the count in the table. $characterCountTable[$character] = $currentCharacterCount; } + // Sort the count table in descending order. arsort($characterCountTable); + + // Return the character that appears most frequently. return array_keys($characterCountTable)[0]; }