Merge pull request #122 from salehhashemi1992/ci/setup-code-style-check

Implement PSR-12 Coding Standards and Add CS Check to CI Flow
This commit is contained in:
Brandon Johnson
2023-10-05 00:47:01 -06:00
committed by GitHub
76 changed files with 922 additions and 792 deletions

View File

@ -12,23 +12,23 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Validate composer.json and composer.lock - name: Validate composer.json and composer.lock
run: composer validate run: composer validate
- name: Cache Composer packages - name: Cache Composer packages
id: composer-cache id: composer-cache
uses: actions/cache@v2 uses: actions/cache@v2
with: with:
path: vendor path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }} key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: | restore-keys: |
${{ runner.os }}-php- ${{ runner.os }}-php-
- name: Install dependencies - name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true' if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest run: composer install --prefer-dist --no-progress --no-suggest
- name: Run PHPUnit - name: Run PHPUnit
run: composer run-script test run: composer run-script test

25
.github/workflows/code-style.yml vendored Normal file
View File

@ -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 -n

3
.gitignore vendored
View File

@ -4,4 +4,7 @@
.phan .phan
composer.lock composer.lock
/.phpcs-cache
/phpcs.xml
.phpunit.result.cache .phpunit.result.cache

View File

@ -3,8 +3,8 @@
/** /**
* Encrypt given text using caesar cipher. * Encrypt given text using caesar cipher.
* *
* @param string text text to be encrypted * @param string $text text text to be encrypted
* @param int shift number of shifts to be applied * @param int $shift shift number of shifts to be applied
* @return string new encrypted text * @return string new encrypted text
*/ */
function encrypt(string $text, int $shift): string function encrypt(string $text, int $shift): string
@ -27,8 +27,8 @@ function encrypt(string $text, int $shift): string
/** /**
* Decrypt given text using caesar cipher. * Decrypt given text using caesar cipher.
* @param string text text to be decrypted * @param string $text text text to be decrypted
* @param int shift number of shifts to be applied * @param int $shift shift number of shifts to be applied
* @return string new decrypted text * @return string new decrypted text
*/ */
function decrypt(string $text, int $shift): string function decrypt(string $text, int $shift): string

View File

@ -1,32 +1,37 @@
<?php <?php
// A mono-alphabetic cipher is a simple substitution cipher
// https://www.101computing.net/mono-alphabetic-substitution-cipher/ // A mono-alphabetic cipher is a simple substitution cipher
// https://www.101computing.net/mono-alphabetic-substitution-cipher/
function monoAlphabeticCipher($key, $alphabet, $text){
function monoAlphabeticCipher($key, $alphabet, $text)
$cipherText = ''; // the cipher text (can be decrypted and encrypted) {
$cipherText = ''; // the cipher text (can be decrypted and encrypted)
if ( strlen($key) != strlen($alphabet) ) { return false; } // check if the text length matches
$text = preg_replace('/[0-9]+/', '', $text); // remove all the numbers // check if the text length matches
if (strlen($key) != strlen($alphabet)) {
for( $i = 0; $i < strlen($text); $i++ ){ return false;
$index = strripos( $alphabet, $text[$i] ); }
if( $text[$i] == " " ){ $cipherText .= " "; }
else{ $cipherText .= ( ctype_upper($text[$i]) ? strtoupper($key[$index]) : $key[$index] ); } $text = preg_replace('/[0-9]+/', '', $text); // remove all the numbers
}
return $cipherText; for ($i = 0; $i < strlen($text); $i++) {
} $index = strripos($alphabet, $text[$i]);
if ($text[$i] == " ") {
function maEncrypt($key, $alphabet, $text){ $cipherText .= " ";
} else {
return monoAlphabeticCipher($key, $alphabet, $text); $cipherText .= ( ctype_upper($text[$i]) ? strtoupper($key[$index]) : $key[$index] );
}
} }
function maDecrypt($key, $alphabet, $text){ return $cipherText;
}
return monoAlphabeticCipher($alphabet, $key, $text);
function maEncrypt($key, $alphabet, $text)
} {
return monoAlphabeticCipher($key, $alphabet, $text);
?> }
function maDecrypt($key, $alphabet, $text)
{
return monoAlphabeticCipher($alphabet, $key, $text);
}

View File

@ -3,8 +3,9 @@
/** /**
* Encode text to Morse Code. * Encode text to Morse Code.
* *
* @param string text to encode * @param string $text text to encode
* @return string encoded text * @return string encoded text
* @throws \Exception
*/ */
function encode(string $text): string function encode(string $text): string
{ {
@ -57,13 +58,14 @@ function encode(string $text): string
throw new \Exception("Invalid character: $c"); throw new \Exception("Invalid character: $c");
} }
} }
substr_replace($encodedText ,"", -1); // Removes trailing space substr_replace($encodedText, "", -1); // Removes trailing space
return $encodedText; return $encodedText;
} }
/** /**
* Decode Morse Code to text. * Decode Morse Code to text.
* @param string text to decode * @param string $text text to decode
* @throws \Exception
*/ */
function decode(string $text): string function decode(string $text): string
{ {

View File

@ -7,18 +7,16 @@
* character with the key. * character with the key.
* The key is repeated until it is the same length as the input. * The key is repeated until it is the same length as the input.
* *
* @param string $input The input string. * @param string $input_string The input string.
* @param string $key The key to use. * @param string $key The key to use.
* @return string The encrypted string. * @return string The encrypted string.
*/ */
function xorCipher(string $input_string, string $key) function xorCipher(string $input_string, string $key)
{ {
$key_len = strlen($key); $key_len = strlen($key);
$result = array(); $result = array();
for ($idx = 0; $idx < strlen($input_string); $idx++) for ($idx = 0; $idx < strlen($input_string); $idx++) {
{
array_push($result, $input_string[$idx] ^ $key[$idx % $key_len]); array_push($result, $input_string[$idx] ^ $key[$idx % $key_len]);
} }

View File

@ -11,8 +11,9 @@
* (2 + 0) base 10 * (2 + 0) base 10
* 2 base 10 * 2 base 10
* *
* @param string $binaryNumber * @param string $binaryNumber
* @return int * @return int
* @throws \Exception
*/ */
function binaryToDecimal($binaryNumber) function binaryToDecimal($binaryNumber)
{ {

View File

@ -5,8 +5,9 @@
* submitted Decimal Number to * submitted Decimal Number to
* Binary Number. * Binary Number.
* *
* @param string $decimalNumber * @param string $decimalNumber
* @return string * @return string
* @throws \Exception
*/ */
function decimalToBinary($decimalNumber) function decimalToBinary($decimalNumber)
{ {

View File

@ -10,8 +10,9 @@
* (1 * (8 ^ 1) + 0 * (8 ^ 0)) base 10 * (1 * (8 ^ 1) + 0 * (8 ^ 0)) base 10
* (8 + 0) base 10 * (8 + 0) base 10
* 9 base 10 * 9 base 10
* @param string $octalNumber * @param string $octalNumber
* @return int * @return int
* @throws \Exception
*/ */
function octalToDecimal($octalNumber) function octalToDecimal($octalNumber)
{ {
@ -34,8 +35,9 @@ function octalToDecimal($octalNumber)
* submitted Decimal Number to * submitted Decimal Number to
* Octal Number. * Octal Number.
* *
* @param string $decimalNumber * @param string $decimalNumber
* @return string * @return string
* @throws \Exception
*/ */
function decimalToOctal($decimalNumber) function decimalToOctal($decimalNumber)
{ {

View File

@ -14,25 +14,26 @@
* kn -> 1 knot which is equal to 1 nautical mile (1852 km/h) * kn -> 1 knot which is equal to 1 nautical mile (1852 km/h)
* The conversion is made using kilometers as base * The conversion is made using kilometers as base
* *
* @param float $speed * @param float $speed
* @param string $unitFrom * @param string $unitFrom
* @param string $unitTo * @param string $unitTo
* @return int * @return float
* @throws \Exception
*/ */
function convertSpeed(float $speed, string $unitFrom, string $unitTo) function convertSpeed(float $speed, string $unitFrom, string $unitTo)
{ {
$speedUnitsFrom = [ $speedUnitsFrom = [
'mph' => 1.609344, 'mph' => 1.609344,
'km/h' => 1, 'km/h' => 1,
'm/s'=> 3.6, 'm/s' => 3.6,
'ft/s'=> 1.097, 'ft/s' => 1.097,
'kn' => 1.852, 'kn' => 1.852,
]; ];
$speedUnitsTo = [ $speedUnitsTo = [
'mph' => 0.6213712, 'mph' => 0.6213712,
'km/h' => 1, 'km/h' => 1,
'm/s'=> 0.277778, 'm/s' => 0.277778,
'ft/s'=> 0.911344, 'ft/s' => 0.911344,
'kn' => 0.539957, 'kn' => 0.539957,
]; ];
$availableUnits = array_keys($speedUnitsFrom); $availableUnits = array_keys($speedUnitsFrom);

View File

@ -1,8 +1,8 @@
<?php <?php
/** /**
* Singly Linked List * Singly Linked List
*/ */
class SinglyLinkedList class SinglyLinkedList
{ {
public ?SinglyLinkedList $next = null; public ?SinglyLinkedList $next = null;
@ -16,7 +16,6 @@ class SinglyLinkedList
public function append($data): void public function append($data): void
{ {
$current = $this; $current = $this;
while ($current instanceof SinglyLinkedList && isset($current->next)) { while ($current instanceof SinglyLinkedList && isset($current->next)) {
$current = $current->next; $current = $current->next;
} }
@ -27,7 +26,6 @@ class SinglyLinkedList
public function delete($data): SinglyLinkedList public function delete($data): SinglyLinkedList
{ {
$current = $this; $current = $this;
if ($current->data == $data) { if ($current->data == $data) {
return $current->next; return $current->next;
} }
@ -35,7 +33,6 @@ class SinglyLinkedList
while ($current instanceof SinglyLinkedList && isset($current->next)) { while ($current instanceof SinglyLinkedList && isset($current->next)) {
if ($current->next->data === $data) { if ($current->next->data === $data) {
$current->next = $current->next->next; $current->next = $current->next->next;
return $this; return $this;
} }

View File

@ -1,23 +1,25 @@
<?php <?php
/** /**
* Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property. * 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). * (https://en.wikipedia.org/wiki/Breadth-first_search).
* *
* This is a non recursive implementation. * This is a non-recursive implementation.
* *
* References: * References:
* https://cp-algorithms.com/graph/breadth-first-search.html * https://cp-algorithms.com/graph/breadth-first-search.html
* *
* https://the-algorithms.com/algorithm/depth-first-search?lang=python * https://the-algorithms.com/algorithm/depth-first-search?lang=python
* *
* @author Aryansh Bhargavan https://github.com/aryanshb * @author Aryansh Bhargavan https://github.com/aryanshb
* @param array $adjList An array representing the grapth as an Adjacent List * @param array $adjList An array representing the grapth as an Adjacent List
* @param int|string $start The starting vertex * @param int|string $start The starting vertex
* @return bool if path between start and end vertex exists * @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 = []; $visited = [];
$queue = [$start]; $queue = [$start];
while (!empty($queue)) { while (!empty($queue)) {

View File

@ -1,20 +1,20 @@
<?php <?php
/** /**
* The Depth-first Search is an algorithm used for traversing or searching trees or graphs * The Depth-first Search is an algorithm used for traversing or searching trees or graphs
* (https://en.wikipedia.org/wiki/Depth-first_search). * (https://en.wikipedia.org/wiki/Depth-first_search).
* *
* This is a non recursive implementation. * This is a non-recursive implementation.
* *
* References: * References:
* https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/ * https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
* *
* https://the-algorithms.com/algorithm/depth-first-search?lang=python * https://the-algorithms.com/algorithm/depth-first-search?lang=python
* *
* @author Andre Alves https://github.com/andremralves * @author Andre Alves https://github.com/andremralves
* @param array $adjList An array representing the grapth as an Adjacent List * @param array $adjList An array representing the grapth as an Adjacent List
* @param int|string $start The starting vertex * @param int|string $start The starting vertex
* @return array The visited vertices * @return array The visited vertices
*/ */
function dfs($adjList, $start) function dfs($adjList, $start)
{ {
@ -27,8 +27,9 @@ function dfs($adjList, $start)
// Checks each adjacent vertex of $v and add to the stack if not visited // Checks each adjacent vertex of $v and add to the stack if not visited
foreach (array_reverse($adjList[$v]) as $adj) { foreach (array_reverse($adjList[$v]) as $adj) {
if (!array_key_exists($adj, $visited)) if (!array_key_exists($adj, $visited)) {
array_push($stack, $adj); array_push($stack, $adj);
}
} }
} }
return array_keys($visited); return array_keys($visited);

View File

@ -1,12 +1,14 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* Absolute max values from * Absolute max values from
* the different numbers * the different numbers
* provided * provided
* *
* @param decimal $numbers A variable sized number input * @param decimal $numbers A variable sized number input
* @return decimal $absoluteMax Absolute max value * @return decimal $absoluteMax Absolute max value
* @throws \Exception
*/ */
function absolute_max(...$numbers) function absolute_max(...$numbers)
{ {

View File

@ -1,12 +1,14 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* Absolute min values from * Absolute min values from
* the different numbers * the different numbers
* provided. * provided.
* *
* @param decimal $numbers A variable sized number input * @param decimal $numbers A variable sized number input
* @return decimal $absoluteMin Absolute min value * @return decimal $absoluteMin Absolute min value
* @throws \Exception
*/ */
function absolute_min(...$numbers) function absolute_min(...$numbers)
{ {

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This function checks if given number is Armstrong * This function checks if given number is Armstrong
* e.g. 153 * e.g. 153
@ -7,16 +8,14 @@
*/ */
function isNumberArmstrong(int $input): bool function isNumberArmstrong(int $input): bool
{ {
$arr = array_map('intval', str_split($input)); $arr = array_map('intval', str_split($input));
$sumOfCubes = 0; $sumOfCubes = 0;
foreach ($arr as $num) { foreach ($arr as $num) {
$sumOfCubes += $num * $num * $num; $sumOfCubes += $num * $num * $num;
} }
if ($sumOfCubes == $input) { if ($sumOfCubes == $input) {
return true; return true;
} } else {
else { return false;
return false; }
}
} }
?>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This function checks if given number is palindromic * This function checks if given number is palindromic
* e.g. 121 * e.g. 121
@ -7,14 +8,12 @@
*/ */
function isNumberPalindromic(int $input): bool function isNumberPalindromic(int $input): bool
{ {
$arr = array_map('intval', str_split($input)); $arr = array_map('intval', str_split($input));
$arrRev = array_reverse($arr); $arrRev = array_reverse($arr);
$inputRev = (int)implode("", $arrRev); $inputRev = (int)implode("", $arrRev);
if ($input == $inputRev) { if ($input == $inputRev) {
return true; return true;
} } else {
else { return false;
return false; }
}
} }
?>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This function check whether * This function check whether
* the provided integer is a prime * the provided integer is a prime

View File

@ -1,29 +1,35 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* and returns the factorial * and returns the factorial
* of provided positive integer * of provided positive integer
* number. * number.
* *
* @param Integer $number Integer input * @param Integer $number Integer input
* @return Integer Factorial of the input * @return Integer Factorial of the input
* @throws \Exception
*/ */
function factorial(int $number) function factorial(int $number)
{ {
static $cache = [];//internal caching memory for speed static $cache = []; //internal caching memory for speed
if ($number < 0) { if ($number < 0) {
throw new \Exception("Negative numbers are not allowed for calculating Factorial"); throw new \Exception("Negative numbers are not allowed for calculating Factorial");
} }
// Factorial of 0 is 1
if ($number === 0) { if ($number === 0) {
return 1; // Factorial of 0 is 1 return 1;
} }
if (isset($cache[$number])) { if (isset($cache[$number])) {
return $cache[$number]; return $cache[$number];
} }
$fact = ($number * factorial($number - 1)); // Recursion since x! = x * (x-1)! // Recursion since x! = x * (x-1)!
$fact = ($number * factorial($number - 1));
$cache[$number] = $fact; $cache[$number] = $fact;
return $fact; return $fact;

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This functions computes an exponent by doing repeated squares * This functions computes an exponent by doing repeated squares
* *
@ -9,16 +10,16 @@
function fastExponentiation(int $base, int $exponent) function fastExponentiation(int $base, int $exponent)
{ {
if ($exponent == 0) { if ($exponent == 0) {
return 1; return 1;
} }
if ($exponent == 1) { if ($exponent == 1) {
return $base; return $base;
} }
if ($exponent % 2 == 0) { if ($exponent % 2 == 0) {
return fastExponentiation($base*$base, $exponent/2); return fastExponentiation($base * $base, $exponent / 2);
} else { } else {
return $base * fastExponentiation($base*$base, ($exponent-1)/2); return $base * fastExponentiation($base * $base, ($exponent - 1) / 2);
} }
} }

View File

@ -3,8 +3,9 @@
/** /**
* Fibonacci recursive * Fibonacci recursive
* *
* @param int $num * @param int $num
* @return int * @return array
* @throws \Exception
*/ */
function fibonacciRecursive(int $num) function fibonacciRecursive(int $num)
{ {
@ -20,8 +21,9 @@ function fibonacciRecursive(int $num)
} }
/** /**
* @param int $num * @param int $num
* @return int * @return int
* @throws \Exception
*/ */
function recursive(int $num) function recursive(int $num)
{ {
@ -36,6 +38,9 @@ function recursive(int $num)
} }
} }
/**
* @throws \Exception
*/
function fibonacciWithBinetFormula(int $num) function fibonacciWithBinetFormula(int $num)
{ {
/* /*
@ -57,7 +62,6 @@ function fibonacciWithBinetFormula(int $num)
$seriesNumber = (pow($phi_1, $n) - pow($phi_2, $n)) / $sqrt; $seriesNumber = (pow($phi_1, $n) - pow($phi_2, $n)) / $sqrt;
array_push($fib_series, (int)$seriesNumber); array_push($fib_series, (int)$seriesNumber);
} }
} }
return $fib_series; return $fib_series;

View File

@ -10,8 +10,7 @@
*/ */
function loop($i, Generator $set) function loop($i, Generator $set)
{ {
while($i-- > 0 && $set->valid()) while ($i-- > 0 && $set->valid()) {
{
yield $set->current(); yield $set->current();
$set->next(); $set->next();
} }
@ -25,8 +24,7 @@ function fib()
yield $i = 0; yield $i = 0;
yield $j = 1; yield $j = 1;
while(true) while (true) {
{
yield $k = $i + $j; yield $k = $i + $j;
$i = $j; $i = $j;
$j = $k; $j = $k;
@ -36,7 +34,6 @@ function fib()
/* /*
* Generate 100 Fibonacci numbers * Generate 100 Fibonacci numbers
*/ */
foreach(loop(100, fib()) as $item) foreach (loop(100, fib()) as $item) {
{ print($item . ',');
print($item.','); }
}

View File

@ -1,11 +1,13 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* The mean value of * The mean value of
* numbers provided * numbers provided
* *
* @param decimal $numbers A variable sized number input * @param decimal $numbers A variable sized number input
* @return decimal $mean Mean of provided numbers * @return decimal $mean Mean of provided numbers
* @throws \Exception
*/ */
function mean(...$numbers) function mean(...$numbers)
{ {
@ -14,7 +16,6 @@ function mean(...$numbers)
} }
$total = array_sum($numbers); $total = array_sum($numbers);
$mean = $total / count($numbers);
return $total / count($numbers);
return $mean; }
}

View File

@ -1,11 +1,13 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* The median value of * The median value of
* numbers provided * numbers provided
* *
* @param decimal $numbers A variable sized number input * @param decimal $numbers A variable sized number input
* @return decimal $median Median of provided numbers * @return decimal $median Median of provided numbers
* @throws \Exception
*/ */
function median(...$numbers) function median(...$numbers)
{ {
@ -15,11 +17,10 @@ function median(...$numbers)
sort($numbers); sort($numbers);
$length = count($numbers); $length = count($numbers);
$middle = ceil($length / 2); $middle = ceil($length / 2);
if($length % 2 == 0) { if ($length % 2 == 0) {
return ($numbers[$middle] + $numbers[$middle - 1]) / 2; return ($numbers[$middle] + $numbers[$middle - 1]) / 2;
} }
return $numbers[$middle - 1]; return $numbers[$middle - 1];
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This function calculates * This function calculates
* the mode value(s) of * the mode value(s) of
@ -16,6 +17,5 @@ function mode(...$numbers)
$values = array_count_values($numbers); $values = array_count_values($numbers);
$maxCount = max($values); $maxCount = max($values);
return array_keys($values, $maxCount, true); return array_keys($values, $maxCount, true);
} }

View File

@ -1,12 +1,12 @@
<?php <?php
function isNumberNeon($input) function isNumberNeon($input)
{ {
$inputSquare = $input * $input; $inputSquare = $input * $input;
$inputArr = array_map('intval', str_split($inputSquare)); $inputArr = array_map('intval', str_split($inputSquare));
$sumOfSquareDigits =0; $sumOfSquareDigits = 0;
foreach ($inputArr as $digit) { foreach ($inputArr as $digit) {
$sumOfSquareDigits +=$digit; $sumOfSquareDigits += $digit;
} }
return $sumOfSquareDigits ==$input; return $sumOfSquareDigits == $input;
} }
?>

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* This function check whether * This function check whether
* the provided number is a * the provided number is a

View File

@ -26,9 +26,9 @@ function problem1a(): int
$numbers = range(1, $maxNumber); $numbers = range(1, $maxNumber);
return array_reduce($numbers, function($carry, $number) { return array_reduce($numbers, function ($carry, $number) {
$shouldCarry = $number % 3 == 0 || $number % 5 == 0; $shouldCarry = $number % 3 == 0 || $number % 5 == 0;
return $carry += $shouldCarry ? $number : 0; return $carry + ($shouldCarry ? $number : 0);
}); });
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/* /*
* This function solves the problem 10 of the Project Euler. * This function solves the problem 10 of the Project Euler.
* *
@ -18,14 +19,15 @@ function problem10(): int
$n = 2000000; $n = 2000000;
$isPrime = []; $isPrime = [];
for ($i = 2; $i <= $n; $i++){ for ($i = 2; $i <= $n; $i++) {
$isPrime[$i] = $i; $isPrime[$i] = $i;
} }
for ($i = 2; $i*$i <= $n; $i++){ for ($i = 2; $i * $i <= $n; $i++) {
if (isset ($isPrime[$i])){ if (isset($isPrime[$i])) {
for ( $j = $i; $i*$j <= $n; $j++) for ($j = $i; $i * $j <= $n; $j++) {
unset($isPrime[$i*$j]); unset($isPrime[$i * $j]);
}
} }
} }

View File

@ -1,6 +1,5 @@
<?php <?php
/* /*
* This function solves the problem 11 of the Project Euler. * This function solves the problem 11 of the Project Euler.
* *
@ -150,4 +149,3 @@ function problem11()
return $maxProduct; return $maxProduct;
} }

View File

@ -13,12 +13,11 @@ function problem4(): int
{ {
$largest = 0; $largest = 0;
for ($i=100; $i<1000; $i++){ for ($i = 100; $i < 1000; $i++) {
for ($j = $i; $j < 1000; $j++) {
$product = $i * $j;
for ($j=$i; $j<1000; $j++) { if (strrev((string)$product) == (string)$product && $product > $largest) {
$product = $i*$j;
if ( strrev((string)$product) == (string)$product && $product > $largest) {
$largest = $product; $largest = $product;
} }
} }

View File

@ -5,10 +5,10 @@
* *
* Problem description: * Problem description:
* The sum of the squares of the first ten natural numbers is, * 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, * 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 * Hence the difference between the sum of the squares of the
* first ten natural numbers and the square of the sum is . * first ten natural numbers and the square of the sum is .

View File

@ -59,11 +59,11 @@ function problem8(): int
$substringSize = 13; $substringSize = 13;
for ($i = 0; $i < strlen($theNumber) - $substringSize; $i++) { for ($i = 0; $i < strlen($theNumber) - $substringSize; $i++) {
$currentSubstring = substr($theNumber,$i,$substringSize); $currentSubstring = substr($theNumber, $i, $substringSize);
$currentProduct = 0; $currentProduct = 0;
for ($j = 0; $j < strlen ($currentSubstring); $j++) { for ($j = 0; $j < strlen($currentSubstring); $j++) {
$currentProduct = ($currentProduct == 0 ? (int)$currentSubstring[$j] : $currentProduct * (int)$currentSubstring[$j]); $currentProduct = ($currentProduct == 0 ? (int)$currentSubstring[$j] : $currentProduct * (int)$currentSubstring[$j]);
} }
$greatestProduct = ($greatestProduct < $currentProduct ? $currentProduct : $greatestProduct); $greatestProduct = ($greatestProduct < $currentProduct ? $currentProduct : $greatestProduct);

View File

@ -21,7 +21,7 @@
function binarySearchIterative($list, $target) function binarySearchIterative($list, $target)
{ {
$first = 0; $first = 0;
$last = count($list)-1; $last = count($list) - 1;
while ($first <= $last) { while ($first <= $last) {
@ -70,8 +70,9 @@ function binarySearchByRecursion($list, $target, $start, $end)
return $list[0] == $target ? 0 : null; return $list[0] == $target ? 0 : null;
} }
if ($start > $end) if ($start > $end) {
return null; return null;
}
$mid = ($start + $end) >> 1; $mid = ($start + $end) >> 1;
@ -80,9 +81,9 @@ function binarySearchByRecursion($list, $target, $start, $end)
if ($list[$mid] == $target) { if ($list[$mid] == $target) {
return $mid; return $mid;
} elseif ($list[$mid] > $target) { } elseif ($list[$mid] > $target) {
return binarySearchByRecursion($list, $target, $start, $mid-1); return binarySearchByRecursion($list, $target, $start, $mid - 1);
} elseif ($list[$mid] < $target) { } elseif ($list[$mid] < $target) {
return binarySearchByRecursion($list, $target, $mid+1, $end); return binarySearchByRecursion($list, $target, $mid + 1, $end);
} }
return null; return null;

View File

@ -1,60 +1,66 @@
<?php <?php
/* /*
* Exponential Search Algorithm * Exponential Search Algorithm
* *
* The algorithm consists of two stages. * The algorithm consists of two stages.
* The first stage determines a range in which the search key would reside * The first stage determines a range in which the search key would reside
**** if it were in the list. **** if it were in the list.
* In the second stage, a binary search is performed on this range. * In the second stage, a binary search is performed on this range.
*/ */
/**
* @param Array $arr /**
* @param int $value * @param Array $arr
* @param int $floor * @param int $value
* @param int $ceiling * @param int $floor
* @return int * @param int $ceiling
**/ * @return int
function binarySearch ($arr, $value, $floor, $ceiling) { **/
// Get $middle index function binarySearch($arr, $value, $floor, $ceiling)
$mid = floor(($floor + $ceiling) / 2); {
// Return position if $value is at the $mid position // Get $middle index
if ($arr[$mid] === $value) { $mid = floor(($floor + $ceiling) / 2);
return (int) $mid;
} // Return position if $value is at the $mid position
//Return -1 is range is wrong if ($arr[$mid] === $value) {
if ($floor > $ceiling) return -1; return (int) $mid;
// search the left part of the $array }
// If the $middle element is great than the $value
if ($arr[$mid] > $value) { //Return -1 is range is wrong
return binarySearch($arr, $value, $floor, $mid - 1); if ($floor > $ceiling) {
} return -1;
// search the right part of the $array }
// If the $middle element is lower than the $value
else { // search the left part of the $array
return binarySearch($arr, $value, $mid + 1, $ceiling); // If the $middle element is greater than the $value
} if ($arr[$mid] > $value) {
return binarySearch($arr, $value, $floor, $mid - 1);
} else { // search the right part of the $array If the $middle element is lower than the $value
return binarySearch($arr, $value, $mid + 1, $ceiling);
}
} }
/**
* @param Array $arr
* @param int $length
* @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;
}
// Find range for binary search /**
$i = 1; * @param Array $arr
$length = count($arr); * @param int $value
while ($i < $length && $arr[$i] <= $value) { * @return int
$i = $i * 2; */
} function exponentialSearch($arr, $value)
$floor = $i/2; {
$ceiling = min($i, $length); // If $value is the first element of the $array return this position
if ($arr[0] === $value) {
return 0;
}
// Call binary search for the range found above // Find range for binary search
return binarySearch($arr, $value, $floor, $ceiling); $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);
}

View File

@ -11,13 +11,16 @@
*/ */
function fibonacciPosition(int $n, array &$m = []) function fibonacciPosition(int $n, array &$m = [])
{ {
if(isset($m[$n])) return $m[$n]; if (isset($m[$n])) {
if($n < 2) return $n; return $m[$n];
}
if ($n < 2) {
return $n;
}
$m[$n] = fibonacciPosition($n - 1, $m) + fibonacciPosition($n - 2, $m); $m[$n] = fibonacciPosition($n - 1, $m) + fibonacciPosition($n - 2, $m);
return $m[$n]; return $m[$n];
} }
print fibonacciPosition(59); print fibonacciPosition(59);

View File

@ -1,12 +1,13 @@
<?php <?php
/** /**
* Interpolation Search******** * Interpolation Search********
* *
* *
* Description*********** * Description***********
* Searches for a key in a sorted array * Searches for a key in a sorted array
* *
* *
* How************ * How************
* Loop through the array: * Loop through the array:
* Determine the index from the low and high indices * Determine the index from the low and high indices
@ -15,36 +16,38 @@
* if the (value of index in array) is > key decrease the high index * if the (value of index in array) is > key decrease the high index
* repeat the loop * repeat the loop
*/ */
function interpolationSearch($arr, $key) { function interpolationSearch($arr, $key)
$length = count($arr) - 1; {
$low = 0; $length = count($arr) - 1;
$high = $length; $low = 0;
$position = -1; $high = $length;
//loop, between low & high $position = -1;
while ($low <= $high && $key >= $arr[$low] && $key <= $arr[$high]) { //loop, between low & high
//GET INDEX while ($low <= $high && $key >= $arr[$low] && $key <= $arr[$high]) {
$delta = ($key - $arr[$low]) / ($arr[$high] - $arr[$low]); //GET INDEX
$index = $low + floor(($high - $low) * $delta); $delta = ($key - $arr[$low]) / ($arr[$high] - $arr[$low]);
//GET VALUE OF INDEX IN ARRAY... $index = $low + floor(($high - $low) * $delta);
$indexValue = $arr[$index];
if ($indexValue === $key) { //GET VALUE OF INDEX IN ARRAY...
//index value equals key $indexValue = $arr[$index];
//FOUND TARGET
//return index value if ($indexValue === $key) {
$position = $index; //index value equals key
return (int) $position; //FOUND TARGET
//return index value
$position = $index;
return (int) $position;
} elseif ($indexValue < $key) {
//index value lower than key
//increase low index
$low = $index + 1;
} elseif ($indexValue > $key) {
//index value higher than key
//decrease high index
$high = $index - 1;
}
} }
if ($indexValue < $key) {
//index value lower than key //when key not found in array or array not sorted
//increase low index return null;
$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;
}

View File

@ -1,40 +1,39 @@
<?php <?php
/** /**
* Jump Search algorithm in PHP * Jump Search algorithm in PHP
* References: https://www.geeksforgeeks.org/jump-search/ * References: https://www.geeksforgeeks.org/jump-search/
* The list must be sorted in ascending order before performing jumpSearch * The list must be sorted in ascending order before performing jumpSearch
* *
* @param Array $list refers to a sorted list of integer * @param Array $list refers to a sorted list of integer
* @param integer $key refers to the integer target to be searched from the sorted list * @param integer $key refers to the integer target to be searched from the sorted list
* @return index of $key if found, otherwise -1 is returned * @return int index of $key if found, otherwise -1 is returned
*/ */
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*/ function jumpSearch($list, $key)
while ($list[$prev] < $key) {
{ /*number of elements in the sorted array*/
$prev++; $num = count($list);
if ($prev == min($step, $num))
return -1; /*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; return $list[$prev] === $key ? $prev : -1;
} }

View File

@ -5,10 +5,6 @@
* *
* Reference: https://www.geeksforgeeks.org/linear-search/ * 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: * Examples:
* data = 5, 7, 8, 11, 12, 15, 17, 18, 20 * data = 5, 7, 8, 11, 12, 15, 17, 18, 20
* x = 15 * x = 15
@ -17,16 +13,15 @@
* x = 1 * x = 1
* Element not found * 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 * @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) * @return integer the index where the target is found (or -1 if not found)
*/ */
function linearSearch($list, $target) function linearSearch($list, $target)
{ {
$n = sizeof($list); $n = sizeof($list);
for($i = 0; $i < $n; $i++) for ($i = 0; $i < $n; $i++) {
{ if ($list[$i] == $target) {
if($list[$i] == $target) {
return $i + 1; return $i + 1;
} }
} }

View File

@ -10,24 +10,25 @@ require_once __DIR__ . '/../Utils/ArrayHelpers.php';
* [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/lower_bound/) * [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/lower_bound/)
* *
* It is assumed that an integer array is provided * 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 array $arr of sorted integers
* @param integer whose lower bound is to be found * @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); isSortedAscendingInts($arr);
$hi = count($arr); $hi = count($arr);
$lo = 0; $lo = 0;
while($lo < $hi){ while ($lo < $hi) {
$mid = $lo + floor(($hi - $lo)/2); $mid = $lo + floor(($hi - $lo) / 2);
if($arr[$mid] < $elem){ if ($arr[$mid] < $elem) {
$lo = $mid+1; $lo = $mid + 1;
}else{ } else {
$hi = $mid; $hi = $mid;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/* Ternary search is similar to binary search /* Ternary search is similar to binary search
* It rather divides the sorted array into three parts rather than.two parts by using two middle points, $mid1 $mid2. * It rather divides the sorted array into three parts rather than.two parts by using two middle points, $mid1 $mid2.
* The value of the $key will first be compared with the two $mid points, the value will be returned if there is a match. * The value of the $key will first be compared with the two $mid points, the value will be returned if there is a match.
@ -7,77 +8,74 @@
* Otherwise, narrow the interval to the $middle part. * Otherwise, narrow the interval to the $middle part.
* Repeat the steps until the value is found or the interval is empty (value not found after checking all elements). * Repeat the steps until the value is found or the interval is empty (value not found after checking all elements).
*/ */
function ternarySearchByRecursion($arr, $key, $low, $high)
function ternarySearchByRecursion ($arr, $key, $low, $high) { {
// Return null if high is less than low (base case: key not found).
//Return -1 if high lesser than low, we can't find item in the whole array
if ($high < $low) { if ($high < $low) {
return null; return null;
} }
//get $mid1 and $mid2
$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;
}
// 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
return ternarySearchByRecursion($arr, $key, $low, $mid1 - 1);
} else if ($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);
}
}
function ternarySearchIterative ($arr, $key) { // Calculate the indices of the first and second midpoints.
$low = 0; $high = count($arr) - 1;
while ($high >= $low) {
// find the $mid1 and $mid2
$mid1 = floor($low + ($high - $low) / 3); $mid1 = floor($low + ($high - $low) / 3);
$mid2 = floor($high - ($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) { if ($arr[$mid1] === $key) {
// return index of $key if found return $mid1;
return $mid1;
}
if ($arr[$mid2] === $key) {
// return index of $key if found
return $mid2;
} }
// since the $key is not found at $mid, if ($arr[$mid2] === $key) {
// check in which region it is present return $mid2;
// and repeat the Search operation }
// in that region
if ($key < $arr[$mid1]) { // Determine which section to continue searching in.
// the $key lies in between $low and $mid1 if ($key < $arr[$mid1]) {
$high = $mid1 - 1; // Key is in the left section, between $low and $mid1.
} else if ($key > $arr[$mid2]) { return ternarySearchByRecursion($arr, $key, $low, $mid1 - 1);
// the $key lies in between $mid2 and $high } elseif ($key > $arr[$mid2]) {
$low = $mid2 + 1; // Key is in the right section, between $mid2 and $high.
} else { return ternarySearchByRecursion($arr, $key, $mid2 + 1, $high);
// the $key lies in between $mid1 and $mid2 } else {
$low = $mid1 + 1; // Key is in the middle section, between $mid1 and $mid2.
$high = $mid2 - 1; return ternarySearchByRecursion($arr, $key, $mid1 + 1, $mid2 - 1);
} }
} }
// the $key was not found
return null; 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) {
// Calculate the first and second midpoints.
$mid1 = floor($low + ($high - $low) / 3);
$mid2 = floor($high - ($high - $low) / 3);
// Check if the key is found at either midpoint.
if ($arr[$mid1] === $key) {
return $mid1;
}
if ($arr[$mid2] === $key) {
return $mid2;
}
// Determine the section to continue the search in.
if ($key < $arr[$mid1]) {
// Key is in the left section, update the high pointer.
$high = $mid1 - 1;
} elseif ($key > $arr[$mid2]) {
// Key is in the right section, update the low pointer.
$low = $mid2 + 1;
} else {
// Key is in the middle section, update both pointers.
$low = $mid1 + 1;
$high = $mid2 - 1;
}
}
// Key was not found.
return null;
} }

View File

@ -10,24 +10,25 @@ require_once __DIR__ . '/../Utils/ArrayHelpers.php';
* [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/upper_bound/) * [C++ Lower Bound](http://www.cplusplus.com/reference/algorithm/upper_bound/)
* *
* It is assumed that an integer array is provided * 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 array $arr of sorted integers
* @param integer whose upper bound is to be found * @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); isSortedAscendingInts($arr);
$hi = count($arr); $hi = count($arr);
$lo = 0; $lo = 0;
while($lo < $hi){ while ($lo < $hi) {
$mid = $lo + floor(($hi - $lo)/2); $mid = $lo + floor(($hi - $lo) / 2);
if($arr[$mid] <= $elem){ if ($arr[$mid] <= $elem) {
$lo = $mid + 1; $lo = $mid + 1;
}else{ } else {
$hi = $mid; $hi = $mid;
} }
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Sort an "Array of objects" or "Array of arrays" by keys * Sort an "Array of objects" or "Array of arrays" by keys
*/ */
@ -7,60 +8,52 @@ class ArrayKeysSort
{ {
public const ORDER_ASC = 'ASC'; public const ORDER_ASC = 'ASC';
public const ORDER_DESC = 'DESC'; public const ORDER_DESC = 'DESC';
/**
/**
* @param $collection * @param $collection
* @param array $keys * @param array $keys
* @param string $order * @param string $order
* @param bool $isCaseSensitive * @param bool $isCaseSensitive
* @return mixed * @return mixed
*/ */
public static function sort( public static function sort($collection, array $keys, string $order = self::ORDER_ASC, bool $isCaseSensitive = false)
$collection, {
array $keys,
string $order = self::ORDER_ASC,
bool $isCaseSensitive = false
) {
if (!empty($collection) && !empty($keys)) { if (!empty($collection) && !empty($keys)) {
try { try {
usort( usort($collection, function ($a, $b) use ($keys, $order, $isCaseSensitive) {
$collection,
function ($a, $b) use ($keys, $order, $isCaseSensitive) {
$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 {
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) { $pos = 0;
return 0; do {
} elseif ($order === self::ORDER_ASC) { $key = $keys[$pos];
return ($item1 < $item2) ? -1 : 1; 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 { } 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) { } catch (Exception $e) {
echo $e->getMessage(); echo $e->getMessage();
die(); die();

View File

@ -6,13 +6,14 @@
* @param array $array * @param array $array
* @return array * @return array
*/ */
function bubbleSort($array) { function bubbleSort($array)
{
$length = count($array); $length = count($array);
for ($i = $length; $i > 0; $i--) { for ($i = $length; $i > 0; $i--) {
$swapped = true; $swapped = true;
for ($j=0;$j<$i-1;$j++) { for ($j = 0; $j < $i - 1; $j++) {
if ($array[$j] > $array[$j + 1]) { if ($array[$j] > $array[$j + 1]) {
$temp = $array[$j]; $temp = $array[$j];
$array[$j] = $array[$j + 1]; $array[$j] = $array[$j + 1];
@ -21,7 +22,9 @@ function bubbleSort($array) {
} }
} }
if ($swapped) break; if ($swapped) {
break;
}
} }
return $array; return $array;

View File

@ -1,4 +1,5 @@
<?php <?php
/* /*
* Bubble Sort * Bubble Sort
* *
@ -10,25 +11,19 @@
function bubbleSort2(array $input) function bubbleSort2(array $input)
{ {
// Return nothing if input is empty // Return nothing if input is empty
if(!isset($input)) if (!isset($input)) {
{
return []; return [];
} }
do do {
{
$swapped = false; $swapped = false;
for($i = 0, $count = sizeof($input) - 1; $i < $count; $i++) for ($i = 0, $count = sizeof($input) - 1; $i < $count; $i++) {
{ if ($input[$i + 1] < $input[$i]) {
if($input[$i + 1] < $input[$i])
{
list($input[$i + 1], $input[$i]) = [$input[$i], $input[$i + 1]]; list($input[$i + 1], $input[$i]) = [$input[$i], $input[$i + 1]];
$swapped = true; $swapped = true;
} }
} }
} } while ($swapped);
while($swapped);
return $input; return $input;
} }

View File

@ -1,6 +1,5 @@
<?php <?php
/** /**
* @param $array * @param $array
* @param $min * @param $min
@ -11,20 +10,18 @@ function countSort($array, $min, $max)
{ {
$count = array(); $count = array();
for($i = $min; $i <= $max; $i++) for ($i = $min; $i <= $max; $i++) {
{
$count[$i] = 0; $count[$i] = 0;
} }
foreach($array as $number) foreach ($array as $number) {
{
$count[$number]++; $count[$number]++;
} }
$z = 0; $z = 0;
for($i = $min; $i <= $max; $i++) { for ($i = $min; $i <= $max; $i++) {
while( $count[$i]-- > 0 ) { while ($count[$i]-- > 0) {
$array[$z++] = $i; $array[$z++] = $i;
} }
} }

View File

@ -4,26 +4,25 @@
* Gnome Sort * Gnome Sort
* References: * References:
* https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/ * 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. * 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 * @param array $array refers to the array to be sorted
* @return array * @return array
*/ */
function gnomeSort($array)
function gnomeSort($array){ {
$a = 1; $a = 1;
$b = 2; $b = 2;
while($a < count($array)){ while ($a < count($array)) {
if ($array[$a - 1] <= $array[$a]) {
if ($array[$a-1] <= $array[$a]){
$a = $b; $a = $b;
$b++; $b++;
}else{ } else {
list($array[$a],$array[$a-1]) = array($array[$a-1],$array[$a]); list($array[$a],$array[$a - 1]) = array($array[$a - 1],$array[$a]);
$a--; $a--;
if($a == 0){ if ($a == 0) {
$a = $b; $a = $b;
$b++; $b++;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* HeapSort Algorithm * HeapSort Algorithm
* *
@ -12,25 +13,29 @@
*/ */
function heapSort(array $arr): array function heapSort(array $arr): array
{ {
// Get the number of elements in the array.
$n = count($arr); $n = count($arr);
// Throw an exception if the array has no elements.
if ($n <= 0) { if ($n <= 0) {
throw new \UnexpectedValueException('Input array must have at least one element.'); throw new \UnexpectedValueException('Input array must have at least one element.');
} }
// Build heap // Build a max heap from the array.
for ($i = $n / 2 - 1; $i >= 0; $i--) { for ($i = floor($n / 2) - 1; $i >= 0; $i--) {
heapify($arr, $n, $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--) { 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]]; [$arr[0], $arr[$i]] = [$arr[$i], $arr[0]];
// Heapify the reduced heap // Heapify the reduced heap.
heapify($arr, $i, 0); heapify($arr, $i, 0);
} }
// Return the sorted array.
return $arr; return $arr;
} }
@ -46,7 +51,6 @@ function heapify(array &$arr, int $n, int $i): void
$largest = $i; $largest = $i;
$left = 2 * $i + 1; $left = 2 * $i + 1;
$right = 2 * $i + 2; $right = 2 * $i + 2;
if ($left < $n && $arr[$left] > $arr[$largest]) { if ($left < $n && $arr[$left] > $arr[$largest]) {
$largest = $left; $largest = $left;
} }
@ -59,4 +63,4 @@ function heapify(array &$arr, int $n, int $i): void
[$arr[$i], $arr[$largest]] = [$arr[$largest], $arr[$i]]; [$arr[$i], $arr[$largest]] = [$arr[$largest], $arr[$i]];
heapify($arr, $n, $largest); heapify($arr, $n, $largest);
} }
} }

View File

@ -8,13 +8,11 @@
*/ */
function insertionSort(array $array) function insertionSort(array $array)
{ {
for ($i = 1; $i < count($array); $i++) for ($i = 1; $i < count($array); $i++) {
{
$currentVal = $array[$i]; $currentVal = $array[$i];
for ($j = $i - 1; $j >= 0 && $array[$j] > $currentVal; $j--) for ($j = $i - 1; $j >= 0 && $array[$j] > $currentVal; $j--) {
{ $array[$j + 1] = $array[$j];
$array[$j + 1] = $array[$j];
} }
$array[$j + 1] = $currentVal; $array[$j + 1] = $currentVal;
@ -22,5 +20,3 @@ function insertionSort(array $array)
return $array; return $array;
} }

View File

@ -9,12 +9,12 @@
function mergeSort(array $arr) function mergeSort(array $arr)
{ {
if (count($arr) <= 1) { if (count($arr) <= 1) {
return $arr; return $arr;
} }
$mid = floor( count($arr) / 2 ); $mid = floor(count($arr) / 2);
$leftArray = mergeSort( array_slice($arr, 0, $mid) ); $leftArray = mergeSort(array_slice($arr, 0, $mid));
$rightArray = mergeSort( array_slice($arr, $mid) ); $rightArray = mergeSort(array_slice($arr, $mid));
return merge($leftArray, $rightArray); return merge($leftArray, $rightArray);
} }
@ -52,6 +52,3 @@ function merge(array $leftArray, array $rightArray)
return $result; return $result;
} }

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Quick Sort * Quick Sort
* Compare number in an array to the next number and sets to new array (greater than or less than) * Compare number in an array to the next number and sets to new array (greater than or less than)
@ -9,24 +10,19 @@
function quickSort(array $input) function quickSort(array $input)
{ {
// Return nothing if input is empty // Return nothing if input is empty
if(!empty($input)) if (!empty($input)) {
{
return []; return [];
} }
$lt = []; $lt = [];
$gt = []; $gt = [];
if (sizeof($input) < 2) {
if(sizeof($input) < 2)
{
return $input; return $input;
} }
$key = key($input); $key = key($input);
$shift = array_shift($input); $shift = array_shift($input);
foreach ($input as $value) {
foreach($input as $value)
{
$value <= $shift ? $lt[] = $value : $gt[] = $value; $value <= $shift ? $lt[] = $value : $gt[] = $value;
} }

View File

@ -3,18 +3,16 @@
/** /**
* Radix Sort * Radix Sort
* *
* @param array $arr * @param $nums
* @return array * @return array
*/ */
function radixSort($nums) function radixSort($nums)
{ {
$maxDigitsCount = maxDigits($nums); $maxDigitsCount = maxDigits($nums);
for ($k=0; $k < $maxDigitsCount; $k++) for ($k = 0; $k < $maxDigitsCount; $k++) {
{ $digitBucket = array_fill(0, 10, []);
$digitBucket = array_fill(0,10,[]);
for ($i=0; $i < count($nums); $i++) for ($i = 0; $i < count($nums); $i++) {
{
$digitBucket[getDigit($nums[$i], $k)][] = $nums[$i]; $digitBucket[getDigit($nums[$i], $k)][] = $nums[$i];
} }
@ -34,7 +32,7 @@ function radixSort($nums)
* Get the digits value by it's place * Get the digits value by it's place
* *
* @param $num * @param $num
* @param $k * @param $i
* @return int * @return int
*/ */
function getDigit($num, $i) function getDigit($num, $i)
@ -45,27 +43,28 @@ function getDigit($num, $i)
/** /**
* Get the digits count * Get the digits count
* *
* @param $nums * @param $num
* @return int * @return int
*/ */
function digitsCount($num) function digitsCount($num)
{ {
if ($num == 0) return 1; if ($num == 0) {
return 1;
}
return floor(log10(abs($num))) + 1; return floor(log10(abs($num))) + 1;
} }
/** /**
* Get the max digits count * Get the max digits count
* *
* @param $nums * @param $arr
* @return int * @return int
*/ */
function maxDigits($arr) function maxDigits($arr)
{ {
$maxDigits = 0; $maxDigits = 0;
for ($i=0; $i < count($arr); $i++) for ($i = 0; $i < count($arr); $i++) {
{
$maxDigits = max($maxDigits, digitsCount($arr[$i])); $maxDigits = max($maxDigits, digitsCount($arr[$i]));
} }
@ -75,18 +74,17 @@ function maxDigits($arr)
/** /**
* Concat the array * Concat the array
* *
* @param $arr * @param array $array
* @return array * @return array
*/ */
function concat(array $array) { function concat(array $array)
$newArray=[]; {
$newArray = [];
for ($i = 0; $i < count($array); $i++) for ($i = 0; $i < count($array); $i++) {
{ for ($j = 0; $j < count($array[$i]); $j++) {
for ($j = 0; $j<count($array[$i]); $j++) $newArray[] = $array[$i][$j];
{ }
$newArray[] = $array[$i][$j];
}
} }
return $newArray; return $newArray;
} }

View File

@ -10,20 +10,16 @@ function selectionSorting(array $array)
{ {
$length = count($array); $length = count($array);
for ($i = 0; $i < $length; $i++) for ($i = 0; $i < $length; $i++) {
{
$lowest = $i; $lowest = $i;
for ($j = $i + 1; $j < $length; $j++) for ($j = $i + 1; $j < $length; $j++) {
{ if ($array[$j] < $array[$lowest]) {
if ($array[$j] < $array[$lowest])
{
$lowest = $j; $lowest = $j;
} }
} }
if ($i !==$lowest) if ($i !== $lowest) {
{
$temp = $array[$i]; $temp = $array[$i];
$array[$i] = $array[$lowest]; $array[$i] = $array[$lowest];
$array[$lowest] = $temp; $array[$lowest] = $temp;

View File

@ -10,8 +10,7 @@
*/ */
function isAnagram(string $originalString, string $testString, bool $caseInsensitive = true) function isAnagram(string $originalString, string $testString, bool $caseInsensitive = true)
{ {
if ($caseInsensitive) if ($caseInsensitive) {
{
$originalString = strtolower($originalString); // Converting string to lowercase for case-insensitive check $originalString = strtolower($originalString); // Converting string to lowercase for case-insensitive check
$testString = strtolower($testString); $testString = strtolower($testString);
} }

View File

@ -11,22 +11,18 @@ function isPalindrome(string $string, bool $caseInsensitive = true)
{ {
$string = trim($string); // Removing leading and trailing spaces $string = trim($string); // Removing leading and trailing spaces
if (empty($string)) if (empty($string)) {
{
return false; // Returning false for an Empty String return false; // Returning false for an Empty String
} }
if ($caseInsensitive) if ($caseInsensitive) {
{
$string = strtolower($string); // Converting string to lowercase for case-insensitive check $string = strtolower($string); // Converting string to lowercase for case-insensitive check
} }
$characters = str_split($string); $characters = str_split($string);
for ($i = 0; $i < count($characters); $i++) for ($i = 0; $i < count($characters); $i++) {
{ if ($characters[$i] !== $characters[count($characters) - ($i + 1)]) {
if ($characters[$i] !== $characters[count($characters) - ($i + 1)])
{
return false; return false;
} }
} }

View File

@ -5,16 +5,17 @@
* using php strrev() function * using php strrev() function
* make it simple * make it simple
* *
* @param string $string * @param string $string
* @param bool $caseInsensitive * @param bool $caseInsensitive
* @return string
* @throws \Exception
*/ */
function checkPalindromeString(string $string, bool $caseInsensitive = true): String function checkPalindromeString(string $string, bool $caseInsensitive = true): string
{ {
//removing spaces //removing spaces
$string = trim($string); $string = trim($string);
if (empty($string)) if (empty($string)) {
{
throw new \Exception('You are given empty string. Please give a non-empty string value'); throw new \Exception('You are given empty string. Please give a non-empty string value');
} }
@ -22,13 +23,11 @@ function checkPalindromeString(string $string, bool $caseInsensitive = true): St
* for case-insensitive * for case-insensitive
* lowercase string conversion * lowercase string conversion
*/ */
if ($caseInsensitive) if ($caseInsensitive) {
{
$string = strtolower($string); $string = strtolower($string);
} }
if ($string !== strrev($string)) if ($string !== strrev($string)) {
{
return $string . " - not a palindrome string." . PHP_EOL; return $string . " - not a palindrome string." . PHP_EOL;
} }

View File

@ -4,10 +4,11 @@
* Function returns the total number of consonants present in the given * Function returns the total number of consonants present in the given
* string using a linear search through the string * string using a linear search through the string
* *
* @param string $string * @param string $string
* @return int * @return int
* @throws \Exception
*/ */
function countConsonants(string $string): Int function countConsonants(string $string): int
{ {
if (empty($string)) { if (empty($string)) {
throw new \Exception('Please pass a non-empty string value'); throw new \Exception('Please pass a non-empty string value');
@ -18,11 +19,11 @@ function countConsonants(string $string): Int
$consonantCount = 0; $consonantCount = 0;
for ($i = 0; $i < strlen($string); $i++) for ($i = 0; $i < strlen($string); $i++) {
{ if (
if (!in_array($string[$i], $vowels) && !in_array($string[$i], $vowels) &&
$string[$i] >= 'a' && $string[$i] <= 'z') $string[$i] >= 'a' && $string[$i] <= 'z'
{ ) {
$consonantCount++; $consonantCount++;
} }
} }

View File

@ -1,32 +1,39 @@
<?php <?php
/** /**
* This function returns the total number of vowels present in * This function returns the total number of vowels present in
* the given string using a simple method of looping through * the given string using a simple method of looping through
* all the characters present in the string. * all the characters present in the string.
* *
* @param string $string * @param string $string
* @return int $numberOfVowels * @return int $numberOfVowels
* @throws \Exception
*/ */
function countVowelsSimple(string $string) function countVowelsSimple(string $string): int
{ {
if (empty($string)) // 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; $numberOfVowels = 0;
$vowels = ['a', 'e', 'i', 'o', 'u']; // Vowels Set $vowels = ['a', 'e', 'i', 'o', 'u']; // Set of vowels for comparison.
$string = strtolower($string); // For case-insensitive checking
$characters = str_split($string); // Splitting the string to a Character Array.
foreach ($characters as $character) // Convert the string to lowercase for case-insensitive comparison.
{ $string = strtolower($string);
if (in_array($character, $vowels))
{ // 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++; $numberOfVowels++;
} }
} }
// Return the total number of vowels found.
return $numberOfVowels; return $numberOfVowels;
} }
@ -34,15 +41,16 @@ function countVowelsSimple(string $string)
* This function returns the Total number of vowels present in the given * This function returns the Total number of vowels present in the given
* string using a regular expression. * string using a regular expression.
* *
* @param string $string * @param string $string
* @return int * @return int
* @throws \Exception
*/ */
function countVowelsRegex(string $string) function countVowelsRegex(string $string)
{ {
if (empty($string)) if (empty($string)) {
{
throw new \Exception('Please pass a non-empty string value'); 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); return preg_match_all('/[a,e,i,o,u]/', $string);

View File

@ -1,4 +1,5 @@
<?php <?php
/** /**
* Find distance (Levenshtein distance) * Find distance (Levenshtein distance)
* *
@ -13,7 +14,6 @@ function findDistance($str1, $str2)
{ {
$lenStr1 = strlen($str1); $lenStr1 = strlen($str1);
$lenStr2 = strlen($str2); $lenStr2 = strlen($str2);
if ($lenStr1 == 0) { if ($lenStr1 == 0) {
return $lenStr2; return $lenStr2;
} }
@ -40,14 +40,13 @@ function findDistance($str1, $str2)
// use formula to fill in the rest of the row // use formula to fill in the rest of the row
for ($j = 0; $j < $lenStr1; $j++) { for ($j = 0; $j < $lenStr1; $j++) {
$substitutionCost = 0; $substitutionCost = 0;
if ($str1[$j] == $str2[$i]) { if ($str1[$j] == $str2[$i]) {
$substitutionCost = $distanceVectorInit[$j]; $substitutionCost = $distanceVectorInit[$j];
} else { } else {
$substitutionCost = $distanceVectorInit[$j] + 1; $substitutionCost = $distanceVectorInit[$j] + 1;
} }
$distanceVectorFinal[$j+1] = min($distanceVectorInit[$j+1] + 1, min($distanceVectorFinal[$j] + 1, $substitutionCost)); $distanceVectorFinal[$j + 1] = min($distanceVectorInit[$j + 1] + 1, min($distanceVectorFinal[$j] + 1, $substitutionCost));
} }
$distanceVectorInit = $distanceVectorFinal; $distanceVectorInit = $distanceVectorFinal;

View File

@ -1,32 +1,41 @@
<?php <?php
/** /**
* This function returns the character which is repeated maximum number of * This function returns the character which is repeated maximum number of
* times in the given string. * times in the given string.
* *
* @param string $string * @param string $string
* @return string * @return string
* @throws \Exception
*/ */
function maxCharacter(string $string) function maxCharacter(string $string): string
{ {
// Throw an exception if the string is empty.
if (empty($string)) { if (empty($string)) {
throw new \Exception('Please pass a non-empty string value'); throw new \Exception('Please pass a non-empty string value.');
} }
$characterCountTable = []; // A variable to maintain the character counts // Initialize an associative array to hold character counts.
$string = strtolower($string); // For case-insensitive checking $characterCountTable = [];
$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) { foreach ($characters as $character) {
$currentCharacterCount = 1; // Initialize or update the count of the current character.
$currentCharacterCount = isset($characterCountTable[$character]) ? $characterCountTable[$character] + 1 : 1;
if (isset($characterCountTable[$character])) {
$currentCharacterCount = $characterCountTable[$character] + 1;
}
// Update the count in the table.
$characterCountTable[$character] = $currentCharacterCount; $characterCountTable[$character] = $currentCharacterCount;
} }
// Sort the count table in descending order.
arsort($characterCountTable); arsort($characterCountTable);
// Return the character that appears most frequently.
return array_keys($characterCountTable)[0]; return array_keys($characterCountTable)[0];
} }

View File

@ -4,7 +4,7 @@
* This function returns a given sentence with its words * This function returns a given sentence with its words
* in reverse order * in reverse order
* *
* @param string $string * @param string $text
* @return string * @return string
*/ */
function reverseWords(string $text) function reverseWords(string $text)
@ -13,8 +13,7 @@ function reverseWords(string $text)
$words = explode(' ', $text); $words = explode(' ', $text);
$reversedWords = []; $reversedWords = [];
for ($i = (count($words) - 1); $i >= 0; $i--) for ($i = (count($words) - 1); $i >= 0; $i--) {
{
$reversedWords[] = $words[$i]; $reversedWords[] = $words[$i];
} }

View File

@ -1,24 +1,25 @@
<?php <?php
/** /**
* @param an array of integers * @param array $arr array of integers
* @return is array sorted in ascending * @return void array sorted in ascending
*/ */
function isSortedAscendingInts(array $arr): void{ function isSortedAscendingInts(array $arr): void
{
$len = count($arr); $len = count($arr);
if($len == 0){ if ($len == 0) {
return; return;
} }
if(!is_int($arr[0])){ if (!is_int($arr[0])) {
throw UnexpectedValueException; throw UnexpectedValueException;
} }
for($i = 1; $i < $len; $i++){ for ($i = 1; $i < $len; $i++) {
// a sorted array is expected // a sorted array is expected
if(!is_int($arr[$i]) && $arr[$i] < $arr[$i-1]){ if (!is_int($arr[$i]) && $arr[$i] < $arr[$i - 1]) {
throw UnexpectedValueException; throw UnexpectedValueException;
} }
} }
} }

View File

@ -3,16 +3,17 @@
"description": "All Algorithms implemented in PHP", "description": "All Algorithms implemented in PHP",
"config": { "config": {
"platform": { "platform": {
"php": "7.3.0" "php": "7.4.0"
} }
}, },
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "7.3.0", "php": "7.4",
"phan/phan": "^2.7" "phan/phan": "^2.7"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^9" "phpunit/phpunit": "^9",
"squizlabs/php_codesniffer": "^3.7"
}, },
"scripts": { "scripts": {
"test": "vendor/bin/phpunit tests" "test": "vendor/bin/phpunit tests"

15
phpcs.xml.dist Normal file
View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/squizlabs/php_codesniffer/phpcs.xsd">
<arg name="extensions" value="php"/>
<rule ref="PSR12"/>
<file>.</file>
<exclude-pattern>vendor</exclude-pattern>
<rule ref="PSR1.Classes.ClassDeclaration.MissingNamespace">
<severity>0</severity>
</rule>
</ruleset>

View File

@ -1,6 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -22,7 +21,7 @@ class CiphersTest extends TestCase
$input_str = "test@string"; $input_str = "test@string";
$key = "test-key"; $key = "test-key";
$invalid_key = "wrong-key"; $invalid_key = "wrong-key";
$this->assertEquals( $input_str, xorCipher( xorCipher( $input_str , $key) , $key)); $this->assertEquals($input_str, xorCipher(xorCipher($input_str, $key), $key));
$this->assertNotEquals( $input_str, xorCipher( xorCipher( $input_str , $key) , $invalid_key)); $this->assertNotEquals($input_str, xorCipher(xorCipher($input_str, $key), $invalid_key));
} }
} }

View File

@ -1,23 +1,19 @@
<?php <?php
use PHPUnit\Framework\TestCase;
use function PHPUnit\Framework\assertEquals; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../Ciphers/MonoAlphabeticCipher.php'; require_once __DIR__ . '/../../Ciphers/MonoAlphabeticCipher.php';
class MonoAlphabeticCipherTest extends TestCase class MonoAlphabeticCipherTest extends TestCase
{ {
public function testMonoAlphabeticCipher(){ public function testMonoAlphabeticCipher()
$alphabet = "abcdefghijklmnopqrstuvwxyz"; {
$key = "yhkqgvxfoluapwmtzecjdbsnri"; $alphabet = "abcdefghijklmnopqrstuvwxyz";
$text = "I love1234 GitHub"; $key = "yhkqgvxfoluapwmtzecjdbsnri";
$encryptedText = "O ambg XojFdh"; $text = "I love1234 GitHub";
$encryptedText = "O ambg XojFdh";
assertEquals(maEncrypt($key, $alphabet, $text), $encryptedText); $this->assertEquals(maEncrypt($key, $alphabet, $text), $encryptedText);
$this->assertEquals(maDecrypt($key, $alphabet, $encryptedText), "I love GitHub");
assertEquals(maDecrypt($key, $alphabet, $encryptedText), "I love GitHub"); }
}
}
}
?>

View File

@ -1,6 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -10,6 +9,6 @@ class MorseCodeTest extends TestCase
{ {
public function testMorseCodeCipher() public function testMorseCodeCipher()
{ {
assertEquals('TEST 123', decode(encode('TEST 123'))); $this->assertEquals('TEST 123', decode(encode('TEST 123')));
} }
} }

View File

@ -1,6 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -15,8 +14,8 @@ class ConversionsTest extends TestCase
{ {
public function testBinaryToDecimal() public function testBinaryToDecimal()
{ {
assertEquals(binaryToDecimal(111), 7); $this->assertEquals(7, binaryToDecimal(111));
assertEquals(binaryToDecimal(101), 5); $this->assertEquals(5, binaryToDecimal(101));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Binary Number for Converting it to a Decimal Number.'); $this->expectExceptionMessage('Please pass a valid Binary Number for Converting it to a Decimal Number.');
binaryToDecimal("this is a string"); binaryToDecimal("this is a string");
@ -24,8 +23,8 @@ class ConversionsTest extends TestCase
public function testDecimalToBinary() public function testDecimalToBinary()
{ {
assertEquals(decimalToBinary(7), 111); $this->assertEquals(111, decimalToBinary(7));
assertEquals(decimalToBinary(5), 101); $this->assertEquals(101, decimalToBinary(5));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Binary Number.'); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Binary Number.');
decimalToBinary("this is a string"); decimalToBinary("this is a string");
@ -33,9 +32,9 @@ class ConversionsTest extends TestCase
public function testOctalToDecimal() public function testOctalToDecimal()
{ {
assertEquals(octalToDecimal(10), 8); $this->assertEquals(8, octalToDecimal(10));
assertEquals(octalToDecimal(11), 9); $this->assertEquals(9, octalToDecimal(11));
assertEquals(octalToDecimal(1115), 589); $this->assertEquals(589, octalToDecimal(1115));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Octal Number for Converting it to a Decimal Number.'); $this->expectExceptionMessage('Please pass a valid Octal Number for Converting it to a Decimal Number.');
octalToDecimal("this is a string"); octalToDecimal("this is a string");
@ -43,9 +42,9 @@ class ConversionsTest extends TestCase
public function testDecimalToOctal() public function testDecimalToOctal()
{ {
assertEquals(decimalToOctal(8), 10); $this->assertEquals(10, decimalToOctal(8));
assertEquals(decimalToOctal(9), 11); $this->assertEquals(11, decimalToOctal(9));
assertEquals(decimalToOctal(589), 1115); $this->assertEquals(1115, decimalToOctal(589));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to an Octal Number.'); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to an Octal Number.');
decimalToOctal("this is a string"); decimalToOctal("this is a string");
@ -53,9 +52,9 @@ class ConversionsTest extends TestCase
public function testDecimalToHex() public function testDecimalToHex()
{ {
assertEquals(decimalToHex(10), 'A'); $this->assertEquals('A', decimalToHex(10));
assertEquals(decimalToHex(489201875), '1D28A0D3'); $this->assertEquals('1D28A0D3', decimalToHex(489201875));
assertEquals(decimalToHex(171), 'AB'); $this->assertEquals('AB', decimalToHex(171));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Hexadecimal Number.'); $this->expectExceptionMessage('Please pass a valid Decimal Number for Converting it to a Hexadecimal Number.');
decimalToHex("this is a string"); decimalToHex("this is a string");
@ -63,9 +62,9 @@ class ConversionsTest extends TestCase
public function testHexToDecimal() public function testHexToDecimal()
{ {
assertEquals(hexToDecimal('A'), 10); $this->assertEquals(10, hexToDecimal('A'));
assertEquals(hexToDecimal('1D28A0D3'), 489201875); $this->assertEquals(489201875, hexToDecimal('1D28A0D3'));
assertEquals(hexToDecimal('AB'), 171); $this->assertEquals(171, hexToDecimal('AB'));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Please pass a valid Hexadecimal Number for Converting it to a Decimal Number.'); $this->expectExceptionMessage('Please pass a valid Hexadecimal Number for Converting it to a Decimal Number.');
hexToDecimal("this is a string"); hexToDecimal("this is a string");
@ -73,12 +72,12 @@ class ConversionsTest extends TestCase
public function testSpeedConversion() public function testSpeedConversion()
{ {
assertEquals(convertSpeed(5, 'm/s', 'mph'), 11.18); $this->assertEquals(11.18, convertSpeed(5, 'm/s', 'mph'));
assertEquals(convertSpeed(5, 'ft/s', 'km/h'), 5.49); $this->assertEquals(5.49, convertSpeed(5, 'ft/s', 'km/h'));
assertEquals(convertSpeed(3, 'km/h', 'km/h'), 3); $this->assertEquals(3, convertSpeed(3, 'km/h', 'km/h'));
assertEquals(convertSpeed(7, 'kn', 'km/h'), 12.96); $this->assertEquals(12.96, convertSpeed(7, 'kn', 'km/h'));
assertEquals(convertSpeed(12, 'mph', 'km/h'), 19.31); $this->assertEquals(19.31, convertSpeed(12, 'mph', 'km/h'));
assertEquals(convertSpeed(0.514, 'm/s', 'kn'), 1); $this->assertEquals(1, convertSpeed(0.514, 'm/s', 'kn'));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
convertSpeed('1', 'km/h', 'mph'); convertSpeed('1', 'km/h', 'mph');

View File

@ -46,4 +46,3 @@ class BreadthFirstSearchTest extends TestCase
$this->assertTrue($ans); $this->assertTrue($ans);
} }
} }

View File

@ -1,8 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertFalse;
use function PHPUnit\Framework\assertTrue;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -25,118 +22,118 @@ class MathsTest extends TestCase
{ {
public function testFactorial() public function testFactorial()
{ {
assertEquals(1, factorial(1)); $this->assertEquals(1, factorial(1));
assertEquals(120, factorial(5)); $this->assertEquals(120, factorial(5));
assertEquals(1, factorial(0)); $this->assertEquals(1, factorial(0));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
factorial(-25); factorial(-25);
} }
public function testIsNumberArmstrong() public function testIsNumberArmstrong()
{ {
assertTrue(isNumberArmstrong(153)); $this->assertTrue(isNumberArmstrong(153));
assertFalse(isNumberArmstrong(123)); $this->assertFalse(isNumberArmstrong(123));
assertTrue(isNumberArmstrong(370)); $this->assertTrue(isNumberArmstrong(370));
assertFalse(isNumberArmstrong(2468)); $this->assertFalse(isNumberArmstrong(2468));
} }
public function testIsNumberPalindromic() public function testIsNumberPalindromic()
{ {
assertTrue(isNumberPalindromic(121)); $this->assertTrue(isNumberPalindromic(121));
assertFalse(isNumberPalindromic(123)); $this->assertFalse(isNumberPalindromic(123));
assertTrue(isNumberPalindromic(123321)); $this->assertTrue(isNumberPalindromic(123321));
assertFalse(isNumberPalindromic(2468)); $this->assertFalse(isNumberPalindromic(2468));
} }
public function testIsPrime() public function testIsPrime()
{ {
assertTrue(isPrime(73)); $this->assertTrue(isPrime(73));
assertFalse(isPrime(21)); $this->assertFalse(isPrime(21));
assertFalse(isPrime(1)); $this->assertFalse(isPrime(1));
assertTrue(isPrime(997)); $this->assertTrue(isPrime(997));
} }
public function testAbsoluteMax() public function testAbsoluteMax()
{ {
assertEquals(50, absolute_max(12, 20, 35, 50, 50, 23)); $this->assertEquals(50, absolute_max(12, 20, 35, 50, 50, 23));
assertEquals(13, absolute_max(13)); $this->assertEquals(13, absolute_max(13));
assertEquals(54, absolute_max(12, 13, 54, 22)); $this->assertEquals(54, absolute_max(12, 13, 54, 22));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
absolute_max(); absolute_max();
} }
public function testAbsoluteMin() public function testAbsoluteMin()
{ {
assertEquals(12, absolute_min(12, 20, 35, 50, 50, 23)); $this->assertEquals(12, absolute_min(12, 20, 35, 50, 50, 23));
assertEquals(13, absolute_min(13)); $this->assertEquals(13, absolute_min(13));
assertEquals(12, absolute_min(12, 13, 54, 22)); $this->assertEquals(12, absolute_min(12, 13, 54, 22));
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
absolute_min(); absolute_min();
} }
public function testPerfectSquare() public function testPerfectSquare()
{ {
assertTrue(isPerfectSquare(25)); $this->assertTrue(isPerfectSquare(25));
assertFalse(isPerfectSquare(43)); $this->assertFalse(isPerfectSquare(43));
assertFalse(isPerfectSquare(2)); $this->assertFalse(isPerfectSquare(2));
assertTrue(isPerfectSquare(225)); $this->assertTrue(isPerfectSquare(225));
} }
public function testFastExponentiation() public function testFastExponentiation()
{ {
assertEquals(fastExponentiation(10, 0), 1); $this->assertEquals(1, fastExponentiation(10, 0));
assertEquals(fastExponentiation(10, 1), 10); $this->assertEquals(10, fastExponentiation(10, 1));
assertEquals(fastExponentiation(10, 2), 100); $this->assertEquals(100, fastExponentiation(10, 2));
assertEquals(fastExponentiation(10, 3), 1000); $this->assertEquals(1000, fastExponentiation(10, 3));
assertEquals(fastExponentiation(20, 5), 3200000); $this->assertEquals(3200000, fastExponentiation(20, 5));
} }
public function testFibonacciSeries() public function testFibonacciSeries()
{ {
assertEquals([0, 1, 1, 2, 3], fibonacciRecursive(5)); $this->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, 5, 8, 13, 21, 34], fibonacciRecursive(10));
assertEquals([0, 1, 1, 2, 3], fibonacciWithBinetFormula(5)); $this->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, 5, 8, 13, 21, 34], fibonacciWithBinetFormula(10));
} }
public function testNeonNumber() public function testNeonNumber()
{ {
assertTrue(isNumberNeon(1)); $this->assertTrue(isNumberNeon(1));
assertFalse(isNumberNeon(43)); $this->assertFalse(isNumberNeon(43));
assertFalse(isNumberNeon(123)); $this->assertFalse(isNumberNeon(123));
assertTrue(isNumberNeon(9)); $this->assertTrue(isNumberNeon(9));
} }
public function testFibonacciGenerator() public function testFibonacciGenerator()
{ {
assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); $this->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, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib())));
assertEquals([0, 1, 1, 2, 3], iterator_to_array(loop(5, fib()))); $this->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, 5, 8, 13, 21, 34], iterator_to_array(loop(10, fib())));
} }
public function testMean() public function testMean()
{ {
assertEquals( $this->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) mean(2, 4, 6, 8, 20, 50, 70)
); );
assertEquals( $this->assertEquals(
(-5 - 7 + 10) / 3, (-5 - 7 + 10) / 3,
mean(-5, -7, 10) mean(-5, -7, 10)
); );
assertEquals(-1, mean(-1)); $this->assertEquals(-1, mean(-1));
} }
public function testMedian() public function testMedian()
{ {
assertEquals(3, median(1, 2, 3, 4, 5)); $this->assertEquals(3, median(1, 2, 3, 4, 5));
assertEquals(4.5, median(1, 2, 3, 4, 5, 6, 7, 8)); $this->assertEquals(4.5, median(1, 2, 3, 4, 5, 6, 7, 8));
assertEquals(3, median(5, 3, 1, 2, 4)); $this->assertEquals(3, median(5, 3, 1, 2, 4));
} }
public function testMode() public function testMode()
@ -146,5 +143,4 @@ class MathsTest extends TestCase
$this->assertEquals([1, 2, 3, 4, 5], mode(1, 2, 3, 4, 5)); $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)); $this->assertEquals([2, 3, 4], mode(2, 2, 3, 3, 4, 4));
} }
} }

View File

@ -62,7 +62,7 @@ class ProjectEulerTest extends TestCase
{ {
$this->assertSame(31875000, problem9()); $this->assertSame(31875000, problem9());
} }
public function testProblem10(): void public function testProblem10(): void
{ {
$this->assertSame(142913828922, problem10()); $this->assertSame(142913828922, problem10());

View File

@ -1,8 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertFalse;
use function PHPUnit\Framework\assertTrue;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -24,16 +21,16 @@ class SearchesTest extends TestCase
$list = [0, 5, 7, 10, 15]; $list = [0, 5, 7, 10, 15];
$target = 0; $target = 0;
$result = binarySearchIterative($list, $target); $result = binarySearchIterative($list, $target);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 15; $target = 15;
$result = binarySearchIterative($list, $target); $result = binarySearchIterative($list, $target);
assertEquals(4, $result); $this->assertEquals(4, $result);
$target = 5; $target = 5;
$result = binarySearchIterative($list, $target); $result = binarySearchIterative($list, $target);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 6; $target = 6;
$result = binarySearchIterative($list, $target); $result = binarySearchIterative($list, $target);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testBinarySearchByRecursion() public function testBinarySearchByRecursion()
@ -41,16 +38,16 @@ class SearchesTest extends TestCase
$list = [0, 5, 7, 10, 15]; $list = [0, 5, 7, 10, 15];
$target = 0; $target = 0;
$result = binarySearchByRecursion($list, $target, 0, 4); $result = binarySearchByRecursion($list, $target, 0, 4);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 15; $target = 15;
$result = binarySearchByRecursion($list, $target, 0, 4); $result = binarySearchByRecursion($list, $target, 0, 4);
assertEquals(4, $result); $this->assertEquals(4, $result);
$target = 5; $target = 5;
$result = binarySearchByRecursion($list, $target, 0, 4); $result = binarySearchByRecursion($list, $target, 0, 4);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 6; $target = 6;
$result = binarySearchByRecursion($list, $target, 0, 4); $result = binarySearchByRecursion($list, $target, 0, 4);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testBinarySearchByRecursionWithEmptyList() public function testBinarySearchByRecursionWithEmptyList()
@ -58,7 +55,7 @@ class SearchesTest extends TestCase
$list = []; $list = [];
$target = 0; $target = 0;
$result = binarySearchByRecursion($list, $target, 0, 0); $result = binarySearchByRecursion($list, $target, 0, 0);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testBinarySearchByRecursionWithOneElementList() public function testBinarySearchByRecursionWithOneElementList()
@ -66,10 +63,10 @@ class SearchesTest extends TestCase
$list = [0]; $list = [0];
$target = 0; $target = 0;
$result = binarySearchByRecursion($list, $target, 0, 0); $result = binarySearchByRecursion($list, $target, 0, 0);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 1; $target = 1;
$result = binarySearchByRecursion($list, $target, 0, 0); $result = binarySearchByRecursion($list, $target, 0, 0);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testBinarySearchByRecursionWithTwoElementList() public function testBinarySearchByRecursionWithTwoElementList()
@ -77,13 +74,13 @@ class SearchesTest extends TestCase
$list = [0, 1]; $list = [0, 1];
$target = 0; $target = 0;
$result = binarySearchByRecursion($list, $target, 0, 1); $result = binarySearchByRecursion($list, $target, 0, 1);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 1; $target = 1;
$result = binarySearchByRecursion($list, $target, 0, 1); $result = binarySearchByRecursion($list, $target, 0, 1);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 2; $target = 2;
$result = binarySearchByRecursion($list, $target, 0, 1); $result = binarySearchByRecursion($list, $target, 0, 1);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testBinarySearchByRecursionWithThreeElementList() public function testBinarySearchByRecursionWithThreeElementList()
@ -91,28 +88,28 @@ class SearchesTest extends TestCase
$list = [0, 1, 2]; $list = [0, 1, 2];
$target = 0; $target = 0;
$result = binarySearchByRecursion($list, $target, 0, 2); $result = binarySearchByRecursion($list, $target, 0, 2);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 1; $target = 1;
$result = binarySearchByRecursion($list, $target, 0, 2); $result = binarySearchByRecursion($list, $target, 0, 2);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 2; $target = 2;
$result = binarySearchByRecursion($list, $target, 0, 2); $result = binarySearchByRecursion($list, $target, 0, 2);
assertEquals(2, $result); $this->assertEquals(2, $result);
$target = 3; $target = 3;
$result = binarySearchByRecursion($list, $target, 0, 2); $result = binarySearchByRecursion($list, $target, 0, 2);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testFibonacciSearch() public function testFibonacciSearch()
{ {
$test1 = fibonacciPosition(6); $test1 = fibonacciPosition(6);
assertEquals(8, $test1); $this->assertEquals(8, $test1);
$test2 = fibonacciPosition(9); $test2 = fibonacciPosition(9);
assertEquals(34, $test2); $this->assertEquals(34, $test2);
$test3 = fibonacciPosition(60); $test3 = fibonacciPosition(60);
assertEquals(1548008755920, $test3); $this->assertEquals(1548008755920, $test3);
} }
public function testLinearSearch() public function testLinearSearch()
@ -120,7 +117,7 @@ class SearchesTest extends TestCase
$list = [5, 7, 8, 11, 12, 15, 17, 18, 20]; $list = [5, 7, 8, 11, 12, 15, 17, 18, 20];
$target = 15; $target = 15;
$result = linearSearch($list, $target); $result = linearSearch($list, $target);
assertEquals(6, $result); $this->assertEquals(6, $result);
} }
public function testLowerBound() public function testLowerBound()
@ -128,7 +125,7 @@ class SearchesTest extends TestCase
$list = [1, 2, 3, 3, 3, 4, 5, 9]; $list = [1, 2, 3, 3, 3, 4, 5, 9];
$target = 3; $target = 3;
$result = lowerBound($list, $target); $result = lowerBound($list, $target);
assertEquals(2, $result); $this->assertEquals(2, $result);
} }
public function testUpperBound() public function testUpperBound()
@ -136,15 +133,15 @@ class SearchesTest extends TestCase
$list = [1, 2, 3, 3, 3, 4, 5, 9]; $list = [1, 2, 3, 3, 3, 4, 5, 9];
$target = 3; $target = 3;
$result = upperBound($list, $target); $result = upperBound($list, $target);
assertEquals(5, $result); $this->assertEquals(5, $result);
} }
public function testJumpSearch() public function testJumpSearch()
{ {
$list = array( 3,5,6,7,9,10,12,20,22,24); $list = array( 3,5,6,7,9,10,12,20,22,24);
$target = 12; $target = 12;
$result = jumpSearch($list, $target); $result = jumpSearch($list, $target);
assertEquals(6, $result); $this->assertEquals(6, $result);
} }
public function testExponentialSearch() public function testExponentialSearch()
@ -152,7 +149,7 @@ class SearchesTest extends TestCase
$list = array(2,3,4,7,28,35,63,98); $list = array(2,3,4,7,28,35,63,98);
$target = 35; $target = 35;
$result = exponentialSearch($list, $target); $result = exponentialSearch($list, $target);
assertEquals(5, $result); $this->assertEquals(5, $result);
} }
public function testTernarySearchIterative() public function testTernarySearchIterative()
@ -160,16 +157,16 @@ class SearchesTest extends TestCase
$list = [0, 5, 7, 10, 15]; $list = [0, 5, 7, 10, 15];
$target = 0; $target = 0;
$result = ternarySearchIterative($list, $target); $result = ternarySearchIterative($list, $target);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 15; $target = 15;
$result = ternarySearchIterative($list, $target); $result = ternarySearchIterative($list, $target);
assertEquals(4, $result); $this->assertEquals(4, $result);
$target = 5; $target = 5;
$result = ternarySearchIterative($list, $target); $result = ternarySearchIterative($list, $target);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 6; $target = 6;
$result = ternarySearchIterative($list, $target); $result = ternarySearchIterative($list, $target);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testTernarySearchByRecursion() public function testTernarySearchByRecursion()
@ -177,16 +174,16 @@ class SearchesTest extends TestCase
$list = [0, 5, 7, 10, 15]; $list = [0, 5, 7, 10, 15];
$target = 0; $target = 0;
$result = ternarySearchByRecursion($list, $target, 0, 4); $result = ternarySearchByRecursion($list, $target, 0, 4);
assertEquals(0, $result); $this->assertEquals(0, $result);
$target = 15; $target = 15;
$result = ternarySearchByRecursion($list, $target, 0, 4); $result = ternarySearchByRecursion($list, $target, 0, 4);
assertEquals(4, $result); $this->assertEquals(4, $result);
$target = 5; $target = 5;
$result = ternarySearchByRecursion($list, $target, 0, 4); $result = ternarySearchByRecursion($list, $target, 0, 4);
assertEquals(1, $result); $this->assertEquals(1, $result);
$target = 6; $target = 6;
$result = ternarySearchByRecursion($list, $target, 0, 4); $result = ternarySearchByRecursion($list, $target, 0, 4);
assertEquals(null, $result); $this->assertEquals(null, $result);
} }
public function testInterpolationSearch() public function testInterpolationSearch()
@ -194,15 +191,15 @@ class SearchesTest extends TestCase
$list = [2, 6, 8, 10, 12, 14, 16, 18, 20, 22, 26, 34, 39]; $list = [2, 6, 8, 10, 12, 14, 16, 18, 20, 22, 26, 34, 39];
$target = 20; $target = 20;
$result = interpolationSearch($list, $target); $result = interpolationSearch($list, $target);
assertEquals(8, $result); $this->assertEquals(8, $result);
$target = 12; $target = 12;
$result = interpolationSearch($list, $target); $result = interpolationSearch($list, $target);
assertEquals(4, $result); $this->assertEquals(4, $result);
$target = 1000; $target = 1000;
$result = interpolationSearch($list, $target); $result = interpolationSearch($list, $target);
assertEquals(null, $result); $this->assertEquals(null, $result);
$target = 39; $target = 39;
$result = interpolationSearch($list, $target); $result = interpolationSearch($list, $target);
assertEquals(12, $result); $this->assertEquals(12, $result);
} }
} }

View File

@ -7,7 +7,8 @@ use PHPUnit\Framework\TestCase;
class ArrayKeysSortTest extends TestCase class ArrayKeysSortTest extends TestCase
{ {
public function testArrayKeysSort() { public function testArrayKeysSort()
{
//test array of arrays //test array of arrays
$array1 = [ $array1 = [
['fruit' => 'banana', 'color' => 'yellow', 'cant' => 5], ['fruit' => 'banana', 'color' => 'yellow', 'cant' => 5],
@ -36,22 +37,22 @@ class ArrayKeysSortTest extends TestCase
$this->assertEquals($result2, $test2); $this->assertEquals($result2, $test2);
//test array of objects //test array of objects
$object1 = new \stdClass; $object1 = new \stdClass();
$object1->fruit = 'banana'; $object1->fruit = 'banana';
$object1->color = 'yellow'; $object1->color = 'yellow';
$object1->cant = 5; $object1->cant = 5;
$object2 = new \stdClass; $object2 = new \stdClass();
$object2->fruit = 'apple'; $object2->fruit = 'apple';
$object2->color = 'red'; $object2->color = 'red';
$object2->cant = 2; $object2->cant = 2;
$object3 = new \stdClass; $object3 = new \stdClass();
$object3->fruit = 'apple'; $object3->fruit = 'apple';
$object3->color = 'green'; $object3->color = 'green';
$object3->cant = 7; $object3->cant = 7;
$object4 = new \stdClass; $object4 = new \stdClass();
$object4->fruit = 'grapes'; $object4->fruit = 'grapes';
$object4->color = 'purple'; $object4->color = 'purple';
$object4->cant = 4; $object4->cant = 4;

View File

@ -24,9 +24,53 @@ class SortingTests extends TestCase
public function testBubbleSort2() public function testBubbleSort2()
{ {
$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 = bubbleSort2($array); $sorted = bubbleSort2($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 testCountSort() public function testCountSort()
@ -54,9 +98,53 @@ class SortingTests extends TestCase
public function testQuickSort() 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); $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() public function testQuickSortWithEmptyInput()

View File

@ -1,9 +1,5 @@
<?php <?php
use function PHPUnit\Framework\assertEquals;
use function PHPUnit\Framework\assertFalse;
use function PHPUnit\Framework\assertNotEquals;
use function PHPUnit\Framework\assertTrue;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../vendor/autoload.php';
@ -23,73 +19,74 @@ class StringsTest extends TestCase
{ {
public function testIsPalindrome() public function testIsPalindrome()
{ {
assertTrue(isPalindrome('MaDam')); // true $this->assertTrue(isPalindrome('MaDam')); // true
assertFalse(isPalindrome('ThisIsTest')); // false $this->assertFalse(isPalindrome('ThisIsTest')); // false
assertFalse(isPalindrome('')); // false $this->assertFalse(isPalindrome('')); // false
assertTrue(isPalindrome('Sator Arepo Tenet Opera Rotas')); // true $this->assertTrue(isPalindrome('Sator Arepo Tenet Opera Rotas')); // true
assertFalse(isPalindrome('Sator Arepo Tenet Opera Rotas', false)); // false since we are doing case-sensitive check $this->assertFalse(isPalindrome('Sator Arepo Tenet Opera Rotas', false)); // false since we are doing
// case-sensitive check
} }
public function testCountSentences() public function testCountSentences()
{ {
assertEquals(countSentences('Hi! Hello world.'), 2); $this->assertEquals(2, countSentences('Hi! Hello world.'));
assertEquals(countSentences('i am testing. test....'), 2); $this->assertEquals(2, countSentences('i am testing. test....'));
assertEquals(countSentences('How are you?'), 1); $this->assertEquals(1, countSentences('How are you?'));
} }
public function testReverseString() public function testReverseString()
{ {
assertEquals('txet emos si sihT', reverseString('This is some text')); $this->assertEquals('txet emos si sihT', reverseString('This is some text'));
assertEquals('mADaM', reverseString('MaDAm')); $this->assertEquals('mADaM', reverseString('MaDAm'));
assertNotEquals('MaDAm', reverseString('MaDAm')); $this->assertNotEquals('MaDAm', reverseString('MaDAm'));
} }
public function testReverseWords() public function testReverseWords()
{ {
assertEquals('Fun is Coding PHP', reverseWords('PHP Coding is Fun')); $this->assertEquals('Fun is Coding PHP', reverseWords('PHP Coding is Fun'));
assertEquals('OneWord', reverseWords('OneWord')); $this->assertEquals('OneWord', reverseWords('OneWord'));
assertEquals('Text different some is This', reverseWords('This is some different Text')); $this->assertEquals('Text different some is This', reverseWords('This is some different Text'));
} }
public function testIsAnagram() public function testIsAnagram()
{ {
assertTrue(isAnagram("php", "PHP")); // By default it's case-insensitive $this->assertTrue(isAnagram("php", "PHP")); // By default it's case-insensitive
assertFalse(isAnagram("php", "PHP", false)); // Make case-sensitive check $this->assertFalse(isAnagram("php", "PHP", false)); // Make case-sensitive check
assertTrue(isAnagram("php is fun", "pin hpf us")); $this->assertTrue(isAnagram("php is fun", "pin hpf us"));
assertFalse(isAnagram("Hello", " Hello")); //Extra space character $this->assertFalse(isAnagram("Hello", " Hello")); //Extra space character
assertTrue(isAnagram("ScRamble", "SRlmcaeb", false)); // Check with a mixture of upper and lower case $this->assertTrue(isAnagram("ScRamble", "SRlmcaeb", false)); // Check with a mixture of upper and lower case
} }
public function testMaxCharacter() public function testMaxCharacter()
{ {
assertEquals(maxCharacter("this is test for max character repetition"), 't'); $this->assertEquals('t', maxCharacter("this is test for max character repetition"));
assertEquals(maxCharacter("This is Test for max characTer repetition"), 't'); $this->assertEquals('t', maxCharacter("This is Test for max characTer repetition"));
assertEquals(maxCharacter(" "), ' '); $this->assertEquals(' ', maxCharacter(" "));
} }
public function testCountVowels() public function testCountVowels()
{ {
assertEquals(countVowelsSimple("This is a string with 7 vowels"), 7); $this->assertEquals(7, countVowelsSimple("This is a string with 7 vowels"));
assertEquals(countVowelsSimple("hello world"), 3); $this->assertEquals(3, countVowelsSimple("hello world"));
assertEquals(countVowelsRegex("Just A list of somE aaaaaaaaaa"), 16); $this->assertEquals(16, countVowelsRegex("Just A list of somE aaaaaaaaaa"));
assertEquals(countVowelsRegex("This is a string with 7 vowels"), 7); $this->assertEquals(7, countVowelsRegex("This is a string with 7 vowels"));
assertEquals(countVowelsRegex("hello world"), 3); $this->assertEquals(3, countVowelsRegex("hello world"));
assertEquals(countVowelsRegex("Just A list of somE aaaaaaaaaa"), 16); $this->assertEquals(16, countVowelsRegex("Just A list of somE aaaaaaaaaa"));
} }
public function testCountConsonants() public function testCountConsonants()
{ {
assertEquals(countConsonants("This is a string with 19 consonants"), 19); $this->assertEquals(19, countConsonants("This is a string with 19 consonants"));
assertEquals(countConsonants("hello world"), 7); $this->assertEquals(7, countConsonants("hello world"));
assertEquals(countConsonants("Just A list of somE aaaaaaaaaa"), 9); $this->assertEquals(9, countConsonants("Just A list of somE aaaaaaaaaa"));
} }
public function testFindDistance() public function testFindDistance()
{ {
assertEquals(findDistance("hello", "hallo"), 1); $this->assertEquals(1, findDistance("hello", "hallo"));
assertEquals(findDistance("hallo", "hello"), 1); $this->assertEquals(1, findDistance("hallo", "hello"));
assertEquals(findDistance("sunday", "sunday"), 0); $this->assertEquals(0, findDistance("sunday", "sunday"));
assertEquals(findDistance("saturday", "sunday"), 3); $this->assertEquals(3, findDistance("saturday", "sunday"));
} }
} }