├── .editorconfig ├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── LICENSE ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── composer.json ├── composer.lock ├── phpstan.neon ├── phpunit.xml ├── src ├── Algorithm │ ├── Search │ │ ├── BidirectionalSearch.php │ │ ├── BreadthFirstSearch.php │ │ ├── DepthFirstSearch.php │ │ ├── LinkedListSearch.php │ │ └── RecursiveSearch.php │ ├── Sorting │ │ ├── BubbleSort.php │ │ ├── BucketSort.php │ │ ├── InsertionSort.php │ │ ├── MergeSort.php │ │ ├── QuickSort.php │ │ ├── RadixSort.php │ │ ├── SelectionSort.php │ │ ├── TimSort.php │ │ └── TopologicalSort.php │ ├── Traversal │ │ ├── InOrder.php │ │ ├── LevelOrder.php │ │ ├── PostOrder.php │ │ └── PreOrder.php │ └── Various │ │ ├── Converter.php │ │ ├── Misc.php │ │ └── Permutation.php ├── Common │ ├── Abstracts │ │ ├── AbstractBinaryNode.php │ │ ├── AbstractGraph.php │ │ ├── AbstractGraphSearch.php │ │ ├── AbstractLinkedList.php │ │ ├── AbstractNode.php │ │ ├── AbstractSet.php │ │ ├── AbstractTable.php │ │ ├── AbstractTraverse.php │ │ └── AbstractTree.php │ ├── Exception │ │ ├── IndexOutOfBoundsException.php │ │ ├── InvalidBitLengthException.php │ │ ├── InvalidGraphTypeException.php │ │ ├── InvalidKeyTypeException.php │ │ ├── InvalidSearchComparisionException.php │ │ ├── NoNodeFoundException.php │ │ ├── NodeNotFoundException.php │ │ ├── NullNotAllowedException.php │ │ ├── PHPAlgorithmsException.php │ │ ├── UnsupportedKeyTypeException.php │ │ └── ValueNotAllowedException.php │ ├── Interfaces │ │ ├── IBinaryNode.php │ │ ├── ICache.php │ │ ├── IComparable.php │ │ ├── IGraphSortable.php │ │ ├── IHashable.php │ │ ├── IHeap.php │ │ ├── INode.php │ │ ├── ISet.php │ │ ├── ISortable.php │ │ ├── IUnaryNode.php │ │ └── IVector.php │ ├── Iterator │ │ └── LinkedListIterator.php │ └── Util │ │ ├── Comparator.php │ │ └── MapUtil.php └── Datastructure │ ├── Cache │ ├── LRUCache.php │ └── Node.php │ ├── Graph │ ├── Graph │ │ ├── DirectedGraph.php │ │ ├── Node.php │ │ └── UndirectedGraph.php │ └── Tree │ │ ├── AVLTree.php │ │ ├── AVLTree │ │ └── Node.php │ │ ├── BinarySearchTree.php │ │ ├── BinaryTree.php │ │ ├── BinaryTree │ │ ├── BinaryNode.php │ │ └── BinarySearchNode.php │ │ ├── Heap │ │ ├── MaxHeap.php │ │ └── MinHeap.php │ │ ├── RedBlackTree.php │ │ ├── RedBlackTree │ │ └── Node.php │ │ ├── Tree │ │ └── Node.php │ │ └── Trie │ │ ├── EndOfWordNode.php │ │ ├── Node.php │ │ ├── RootNode.php │ │ └── Trie.php │ ├── Lists │ ├── ArrayList │ │ ├── ArrayList.php │ │ └── StringBuilder.php │ ├── LinkedList │ │ ├── DoublyLinkedList.php │ │ └── SinglyLinkedList.php │ └── Node.php │ ├── Map │ └── Map.php │ ├── Set │ └── HashSet.php │ ├── Stackqueue │ ├── CircularBuffer.php │ ├── FixedQueue.php │ ├── FixedStack.php │ ├── PriorityQueue.php │ ├── Queue.php │ ├── Stack.php │ └── StackSet.php │ ├── Table │ ├── ConsistentHashTable.php │ ├── HashTable.php │ └── SimpleTable.php │ ├── Various │ └── Enum.php │ └── Vector │ ├── BitVector │ └── IntegerVector.php │ └── IntegerVector.php ├── tests ├── Cache │ └── LRUCacheTest.php ├── Comparator │ └── ComparatorTest.php ├── Graph │ ├── graph │ │ └── DirectedGraphTest.php │ └── trees │ │ ├── AVLTree.php │ │ ├── BinarySearchTreeTest.php │ │ ├── BinaryTreeTest.php │ │ └── trie │ │ └── TrieTest.php ├── Lists │ ├── ArrayList │ │ ├── ArrayListTest.php │ │ └── StringBuilderTest.php │ └── LinkedList │ │ ├── DoublyLinkedListTest.php │ │ └── SinglyLinkedListTest.php ├── Map │ └── NodeTest.php ├── Set │ └── HashSetTest.php ├── Sorting │ └── SortTest.php ├── StackQueue │ ├── CircularBufferTest.php │ ├── FixedStackTest.php │ ├── StackSetTest.php │ └── StackTest.php ├── Table │ ├── Entity │ │ └── HashableObject.php │ └── HashTableTest.php ├── Util │ ├── HashTableUtil.php │ ├── LinkedListUtil.php │ └── TreeUtil.php └── Various │ ├── EnumTest.php │ └── PermutationTest.php └── travis.yml /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | ij_php_special_else_if_treatment = false 5 | ij_any_special_else_if_treatment = false 6 | ij_php_block_brace_style = end_of_line 7 | ij_php_class_brace_style = end_of_line 8 | ij_php_for_brace_force = always 9 | ij_php_if_brace_force = never 10 | ij_php_method_brace_style = end_of_line 11 | ij_php_space_after_type_cast = true 12 | ij_php_space_after_colon_in_return_type = true 13 | ij_php_blank_lines_after_imports = 1 14 | ij_php_blank_lines_before_imports = 1 15 | ij_php_align_class_constants = true 16 | ij_php_align_assignments = true 17 | ij_php_align_inline_comments = true 18 | ij_php_align_key_value_pairs = true 19 | ij_php_align_group_field_declarations = true 20 | ij_php_align_multiline_array_initializer_expression = true 21 | ij_php_align_multiline_for = true 22 | ij_php_align_phpdoc_comments = true 23 | ij_php_align_phpdoc_param_names = true 24 | ij_php_import_sorting = alphabetic 25 | ij_php_blank_lines_after_class_header = 1 26 | ij_php_blank_lines_before_class_end = 1 27 | ij_php_else_if_style = separate 28 | ij_any_else_on_new_line = false 29 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://www.paypal.me/doganoo 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/custom.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Custom issue template 3 | about: Describe this issue template's purpose here. 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | 3 | /vendor/ 4 | /aufgaben/ 5 | 6 | main.php 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at dogan@dogan-ucar.de. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Please add your name and email address to each files header you change, example: 15 | 16 | ```` 17 | @author Copyright (c) year, Firstname Lastname 18 | ```` 19 | 20 | 4. Unit tests are required! Please add or extend unit tests. Untested code and/or skips are not allowed! -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Issue tracker is **ONLY** used for reporting bugs. NO NEW FEATURE ACCEPTED! 2 | 3 | 4 | 5 | ## Expected Behavior 6 | 7 | 8 | ## Current Behavior 9 | 10 | 11 | ## Possible Solution 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 17 | 1. 18 | 2. 19 | 3. 20 | 4. 21 | 22 | ## Context (Environment) 23 | 24 | 25 | 26 | 27 | 28 | ## Detailed Description 29 | 30 | 31 | ## Possible Implementation 32 | 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Dogan Ucar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Description 4 | 5 | 6 | ## Related Issue 7 | 8 | 9 | 10 | 11 | 12 | ## Motivation and Context 13 | 14 | 15 | 16 | ## How Has This Been Tested? 17 | 18 | 19 | 20 | 21 | ## Screenshots (if appropriate): 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PHPAlgorithms 2 | 3 | 4 | A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell 5 | 6 | You can find the package on Packagist: https://packagist.org/packages/doganoo/php-algorithms 7 | 8 | ## Why Using PHPAlgorithms? 9 | 10 | "Algorithms + Data Structures = Programs" 11 | 12 | Algorithms are a part of the basic toolkit for solving problems. Data Structures organize data in an efficient way. The combination of both allow the creation of smart and efficient software. 13 | 14 | ## Installation 15 | 16 | You can install the package via composer: 17 | 18 | ```bash 19 | composer require doganoo/php-algorithms 20 | ``` 21 | 22 | ## Usage 23 | 24 | Here's an Binary Tree example: 25 | 26 | ```php 27 | use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree; 28 | 29 | $binaryTree = new BinaryTree(); 30 | $binaryTree->insertValue(50); 31 | $binaryTree->insertValue(25); 32 | $binaryTree->insertValue(75); 33 | $binaryTree->insertValue(10); 34 | $binaryTree->insertValue(100); 35 | 36 | echo json_encode($binaryTree); 37 | ``` 38 | 39 | produces 40 | ```php 41 | {"nodes":{"value":50,"left":{"value":25,"left":{"value":10,"left":null,"right":null},"right":null},"right":{"value":75,"left":null,"right":{"value":100,"left":null,"right":null}}}} 42 | ``` 43 | 44 | ## Contributions 45 | 46 | Feel free to send a pull request to add more algorithms and data structures. Please make sure that you read https://github.com/doganoo/PHPAlgorithms/wiki/Best-Practices before opening a PR. 47 | Please also consider https://github.com/doganoo/PHPAlgorithms/blob/master/CONTRIBUTING.md. 48 | 49 | ## Maintainer/Creator 50 | 51 | Doğan Uçar ([@doganoo](https://www.dogan-ucar.de)) 52 | 53 | ## License 54 | 55 | MIT 56 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "doganoo/php-algorithms", 3 | "description": "A collection of common algorithms implemented in PHP. The collection is based on \"Cracking the Coding Interview\" by Gayle Laakmann McDowell", 4 | "license": "MIT", 5 | "type": "library", 6 | "keywords": [ 7 | "algorithms", 8 | "data structures" 9 | ], 10 | "authors": [ 11 | { 12 | "name": "Dogan Ucar", 13 | "email": "dogan@dogan-ucar.de", 14 | "homepage": "https://www.dogan-ucar.de" 15 | } 16 | ], 17 | "homepage": "https://www.dogan-ucar.de/phpalgorithms-2/", 18 | "require": { 19 | "php": ">=8.0", 20 | "ext-json": "*", 21 | "doganoo/php-util": "0.5.*" 22 | }, 23 | "conflict": { 24 | "stevebauman/unfinalize": "*" 25 | }, 26 | "require-dev": { 27 | "ergebnis/composer-normalize": "^2.9", 28 | "phpcompatibility/php-compatibility": "^9.3", 29 | "phpstan/phpstan": "^0.12.54", 30 | "phpunit/phpunit": "^8.0", 31 | "roave/security-advisories": "dev-latest", 32 | "squizlabs/php_codesniffer": "^3.5" 33 | }, 34 | "autoload": { 35 | "psr-4": { 36 | "doganoo\\PHPAlgorithms\\": "src/", 37 | "doganoo\\PHPAlgorithmsTest\\": "tests/" 38 | } 39 | }, 40 | "config": { 41 | "allow-plugins": { 42 | "ergebnis/composer-normalize": true 43 | } 44 | }, 45 | "scripts": { 46 | "post-install-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility", 47 | "post-update-cmd": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility", 48 | "add-php-compatibility": "\"vendor/bin/phpcs\" --config-set installed_paths vendor/phpcompatibility/php-compatibility", 49 | "php-compatibility": "./vendor/bin/phpcs -p . --standard=PHPCompatibility --runtime-set testVersion 7.4-8.1 --extensions=php --ignore=vendor/", 50 | "phpstan": "vendor/bin/phpstan analyse --level=8 --memory-limit=2G src tests", 51 | "test": "vendor/bin/phpunit tests" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | checkMissingIterableValueType: false -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | ./tests/ 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Algorithm/Search/BidirectionalSearch.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Algorithm\Search; 30 | 31 | use doganoo\PHPAlgorithms\Datastructure\Graph\Graph\Node; 32 | use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\ArrayList; 33 | 34 | /** 35 | * TODO implement AbstractGraphSearch 36 | * 37 | * Class BidirectionalSearch 38 | * 39 | * @package doganoo\PHPAlgorithms\Algorithm\Search 40 | */ 41 | class BidirectionalSearch { 42 | 43 | /** 44 | * @param Node $start 45 | * @param Node $end 46 | * @return bool 47 | */ 48 | public function hasPath(Node $start, Node $end): bool { 49 | $startList = $this->performSearch($start); 50 | $endList = $this->performSearch($end); 51 | 52 | if (null === $startList 53 | || $startList->length() === 0 54 | || null === $endList 55 | || $endList->length() === 0) { 56 | $startList->retainAll($endList); 57 | return $startList->length() > 0; 58 | } 59 | return false; 60 | } 61 | 62 | /** 63 | * @param Node $node 64 | * @return ArrayList|null 65 | */ 66 | private function performSearch(Node $node): ?ArrayList { 67 | $bfs = new BreadthFirstSearch(); 68 | $bfs->setCallable( 69 | function () { 70 | } 71 | ); 72 | $bfs->searchByNode($node); 73 | return $bfs->getVisitedNodes(); 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /src/Algorithm/Search/BreadthFirstSearch.php: -------------------------------------------------------------------------------- 1 | searchByNode($graph->getRoot()); 49 | } 50 | 51 | /** 52 | * @param Node|null $node 53 | * @return void 54 | */ 55 | public function searchByNode(?Node $node): void { 56 | if (null === $node) return; 57 | $queue = new Queue(); 58 | $this->visited->add($node); 59 | $queue->enqueue($node); 60 | 61 | while (!$queue->isEmpty()) { 62 | /** @var Node $n */ 63 | $n = $queue->dequeue(); 64 | $this->visit($n); 65 | /** @var Node $adjacent */ 66 | foreach ($n->getAdjacents() as $adjacent) { 67 | if (!$this->visited->containsValue($adjacent)) { 68 | $this->visited->add($adjacent); 69 | $queue->enqueue($adjacent); 70 | } 71 | } 72 | } 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/Algorithm/Search/DepthFirstSearch.php: -------------------------------------------------------------------------------- 1 | searchByNode($graph->getRoot()); 48 | } 49 | 50 | /** 51 | * @param Node|null $node 52 | * @return void 53 | */ 54 | public function searchByNode(?Node $node): void { 55 | if (null === $node) { 56 | return; 57 | } 58 | $this->visit($node); 59 | $this->visited->add($node); 60 | /** 61 | * @var Node $adjacent 62 | */ 63 | foreach ($node->getAdjacents() as $adjacent) { 64 | if (!$this->visited->containsValue($adjacent)) { 65 | $this->searchByNode($adjacent); 66 | } 67 | } 68 | } 69 | 70 | } -------------------------------------------------------------------------------- /src/Algorithm/Search/LinkedListSearch.php: -------------------------------------------------------------------------------- 1 | getHead(); 49 | $hare = $linkedList->getHead(); 50 | 51 | while ($tortoise !== null && $hare->getNext() !== null && 52 | $hare->getNext()->getNext() !== null) { 53 | $hare = $hare->getNext()->getNext(); 54 | 55 | if (Comparator::equals($tortoise->getValue(), $hare->getValue())) { 56 | return true; 57 | } 58 | 59 | $tortoise = $tortoise->getNext(); 60 | } 61 | return false; 62 | } 63 | 64 | /** 65 | * @param AbstractLinkedList $linkedList 66 | * @param int $k 67 | * @return Node|null 68 | */ 69 | public function findKthElementFromEnd(AbstractLinkedList $linkedList, int $k): ?Node { 70 | $listSize = 0; 71 | $temp = $linkedList->getHead(); 72 | while ($temp !== null) { 73 | $temp = $temp->getNext(); 74 | $listSize++; 75 | } 76 | if ($k > $listSize) { 77 | return null; 78 | } 79 | $resultNode = $linkedList->getHead(); 80 | for ($i = 1; $i < $listSize - $k + 1; $i++) { 81 | $resultNode = $resultNode->getNext(); 82 | } 83 | return $resultNode; 84 | 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /src/Algorithm/Search/RecursiveSearch.php: -------------------------------------------------------------------------------- 1 | getValue(), $needle)) { 50 | return true; 51 | } else if (Comparator::lessThan($needle, $node->getValue())) { 52 | return $this->search($node->getLeft(), $needle); 53 | } else if (Comparator::greaterThan($needle, $node->getValue())) { 54 | return $this->search($node->getRight(), $needle); 55 | } 56 | return false; 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /src/Algorithm/Sorting/BubbleSort.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Algorithm\Sorting; 30 | 31 | use doganoo\PHPAlgorithms\Common\Interfaces\ISortable; 32 | use function array_fill; 33 | use function count; 34 | use function max; 35 | 36 | /** 37 | * Class BucketSort 38 | * 39 | * @package doganoo\PHPAlgorithms\Algorithm\Sorting 40 | */ 41 | class BucketSort implements ISortable { 42 | 43 | /** 44 | * @param array $array 45 | * @return array 46 | */ 47 | public function sort(array $array): array { 48 | if (empty($array)) { 49 | return []; 50 | } 51 | 52 | $size = count($array); 53 | $max = max($array); 54 | $buckets = array_fill(0, $size + 1, []); 55 | 56 | foreach ($array as $v) { 57 | $bucket = (int) ($size * $v / $max); 58 | $buckets[$bucket][] = $v; 59 | } 60 | 61 | $insertionSort = new InsertionSort(); 62 | for ($i = 0; $i < $size; ++$i) { 63 | $buckets[$i] = $insertionSort->sort($buckets[$i]); 64 | } 65 | 66 | $sorted = []; 67 | foreach ($buckets as $bucket) { 68 | foreach ($bucket as $v) { 69 | $sorted[] = $v; 70 | } 71 | } 72 | 73 | return $sorted; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Algorithm/Sorting/InsertionSort.php: -------------------------------------------------------------------------------- 1 | 0) && (Comparator::lessThan($array[$j], $array[$j - 1]))) { 54 | $tmp = $array[$j - 1]; 55 | $array[$j - 1] = $array[$j]; 56 | $array[$j] = $tmp; 57 | $j--; 58 | } 59 | } 60 | return $array; 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /src/Algorithm/Sorting/MergeSort.php: -------------------------------------------------------------------------------- 1 | sort($left); 57 | $right = $this->sort($right); 58 | return $this->merge($left, $right); 59 | } 60 | 61 | /** 62 | * @param array $left 63 | * @param array $right 64 | * @return array 65 | */ 66 | private function merge(array $left, array $right): array { 67 | 68 | $result = []; 69 | $left = array_values($left); 70 | $right = array_values($right); 71 | 72 | while (count($left) !== 0 && count($right) !== 0) { 73 | if (Comparator::greaterThan($left[0], $right[0])) { 74 | $result[] = array_shift($right); 75 | } else { 76 | $result[] = array_shift($left); 77 | } 78 | } 79 | 80 | while (count($left) !== 0) { 81 | $result[] = $left[0]; 82 | $left = array_slice($left, 1); 83 | } 84 | 85 | while (count($right) !== 0) { 86 | $result[] = $right[0]; 87 | $right = array_slice($right, 1); 88 | } 89 | return $result; 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /src/Algorithm/Sorting/QuickSort.php: -------------------------------------------------------------------------------- 1 | 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Algorithm\Sorting; 30 | 31 | use doganoo\PHPAlgorithms\Common\Interfaces\ISortable; 32 | use doganoo\PHPAlgorithms\Common\Util\Comparator; 33 | use function count; 34 | 35 | /** 36 | * Class QuickSort 37 | * 38 | * @package doganoo\PHPAlgorithms\Sorting 39 | */ 40 | class QuickSort implements ISortable { 41 | 42 | /** 43 | * @param array $array 44 | * @return array 45 | */ 46 | public function sort(array $array): array { 47 | $this->quickSort($array, 0, count($array) - 1); 48 | return $array; 49 | } 50 | 51 | private function quickSort(array &$array, int $left, int $right): void { 52 | if ($left >= $right) { 53 | return; 54 | } 55 | $pivotIndex = $this->partition($array, $left, $right); 56 | $this->quicksort($array, $left, $pivotIndex - 1); 57 | $this->quicksort($array, $pivotIndex, $right); 58 | } 59 | 60 | private function partition(array &$array, int $left, int $right): int { 61 | $pivotIndex = floor(($right + $left) / 2); 62 | $pivot = $array[$pivotIndex]; 63 | while ($left <= $right) { 64 | while (Comparator::lessThan($array[$left], $pivot)) { 65 | $left++; 66 | } 67 | while (Comparator::greaterThan($array[$right], $pivot)) { 68 | $right--; 69 | } 70 | if ($left <= $right) { 71 | $temp = $array[$left]; 72 | $array[$left] = $array[$right]; 73 | $array[$right] = $temp; 74 | $left++; 75 | $right--; 76 | } 77 | } 78 | return $left; 79 | } 80 | 81 | } -------------------------------------------------------------------------------- /src/Algorithm/Sorting/RadixSort.php: -------------------------------------------------------------------------------- 1 | getMax($array); 47 | $exponent = 1; 48 | 49 | while (Comparator::greaterThan($max / $exponent, 0)) { 50 | $this->countSort($array, $exponent); 51 | $exponent = $exponent * 10; 52 | $exponent = (int) $exponent; 53 | } 54 | 55 | return $array; 56 | } 57 | 58 | /** 59 | * @param array $array 60 | * @param int $exponent 61 | */ 62 | private function countSort(array &$array, int $exponent): void { 63 | $n = count($array); 64 | $output = []; 65 | $count = array_fill(0, 10, 0); 66 | 67 | for ($i = 0; $i < $n; $i++) { 68 | $count[(int) ($array[$i] / $exponent) % 10]++; 69 | } 70 | 71 | for ($i = 1; $i < 10; $i++) { 72 | $count[$i] += $count[$i - 1]; 73 | } 74 | 75 | for ($i = $n - 1; $i >= 0; $i--) { 76 | $output[$count[(int) ($array[(int) $i] / $exponent) % 10] - 1] = $array[$i]; 77 | $count[(int) ($array[(int) $i] / $exponent) % 10]--; 78 | } 79 | 80 | for ($i = 0; $i < $n; $i++) { 81 | $array[$i] = $output[$i]; 82 | } 83 | } 84 | 85 | /** 86 | * @param array $array 87 | * @return int 88 | */ 89 | private function getMax(array $array): int { 90 | $n = count($array); 91 | 92 | $max = $array[0]; 93 | for ($i = 1; $i < $n; $i++) { 94 | if (Comparator::greaterThan($array[$i], $max)) { 95 | $max = $array[$i]; 96 | } 97 | } 98 | return $max; 99 | } 100 | 101 | } -------------------------------------------------------------------------------- /src/Algorithm/Sorting/SelectionSort.php: -------------------------------------------------------------------------------- 1 | sort(array_slice($array, $i, min(($i + self::RUN), ($size)))); 60 | $arr = $mergeSort->sort($arr); 61 | $result = array_merge($result, $arr); 62 | } 63 | return $result; 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /src/Algorithm/Traversal/InOrder.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Algorithm\Traversal; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractTraverse; 30 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractTree; 31 | use doganoo\PHPAlgorithms\Common\Interfaces\IBinaryNode; 32 | 33 | /** 34 | * Class InOrder 35 | * 36 | * @package doganoo\PHPAlgorithms\Algorithm\Traversal 37 | */ 38 | class InOrder extends AbstractTraverse { 39 | 40 | private AbstractTree $binarySearchTree; 41 | 42 | /** 43 | * InOrder constructor. 44 | * 45 | * @param AbstractTree $tree 46 | */ 47 | public function __construct(AbstractTree $tree) { 48 | $this->binarySearchTree = $tree; 49 | } 50 | 51 | /** 52 | * traverses the tree in in order 53 | */ 54 | public function traverse(): void { 55 | $this->_traverse($this->binarySearchTree->getRoot()); 56 | } 57 | 58 | /** 59 | * helper method for traversing 60 | * 61 | * @param IBinaryNode|null $node 62 | */ 63 | public function _traverse(?IBinaryNode $node): void { 64 | if (null !== $node) { 65 | if (null !== $node->getLeft()) { 66 | $this->_traverse($node->getLeft()); 67 | } 68 | parent::visit($node->getValue()); 69 | if (null !== $node->getRight()) { 70 | $this->_traverse($node->getRight()); 71 | } 72 | } 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/Algorithm/Traversal/LevelOrder.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Algorithm\Traversal; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractTraverse; 30 | use doganoo\PHPAlgorithms\Common\Interfaces\IBinaryNode; 31 | use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinarySearchTree; 32 | 33 | /** 34 | * Class LevelOrder 35 | * @package doganoo\PHPAlgorithms\Algorithm\Traversal 36 | * @author Dogan Ucar 37 | */ 38 | class LevelOrder extends AbstractTraverse { 39 | 40 | private BinarySearchTree $binarySearchTree; 41 | private array $levels = []; 42 | 43 | /** 44 | * LevelOrder constructor. 45 | * @param BinarySearchTree $binarySearchTree 46 | */ 47 | public function __construct(BinarySearchTree $binarySearchTree) { 48 | $this->binarySearchTree = $binarySearchTree; 49 | 50 | $this->setCallable( 51 | function (array $values) { 52 | var_dump(json_encode($values)); 53 | }); 54 | } 55 | 56 | /** 57 | *Traverses the Binary Search Tree in Level Order 58 | */ 59 | public function traverse(): void { 60 | $level = 0; 61 | $result = []; 62 | $this->helper( 63 | $this->binarySearchTree->getRoot() 64 | , $result 65 | , $level 66 | ); 67 | 68 | /** 69 | * @var int $level 70 | * @var IBinaryNode[] $values 71 | */ 72 | foreach ($result as $level => $values) { 73 | $this->visit($values); 74 | } 75 | 76 | } 77 | 78 | /** 79 | * Helper function to traverse the BST 80 | * 81 | * @param IBinaryNode|null $node 82 | * @param array $result 83 | * @param int $level 84 | */ 85 | private function helper(?IBinaryNode $node, array &$result, int $level): void { 86 | if (null === $node) return; 87 | 88 | $levelArray = $result[$level] ?? []; 89 | $levelArray[] = $node; 90 | $result[$level] = $levelArray; 91 | 92 | if (null !== $node->getLeft()) { 93 | $this->helper($node->getLeft(), $result, $level + 1); 94 | } 95 | 96 | if (null !== $node->getRight()) { 97 | $this->helper($node->getRight(), $result, $level + 1); 98 | } 99 | } 100 | 101 | } -------------------------------------------------------------------------------- /src/Algorithm/Traversal/PostOrder.php: -------------------------------------------------------------------------------- 1 | tree = $tree; 49 | } 50 | 51 | /** 52 | * traverses the tree in post order 53 | */ 54 | public function traverse(): void { 55 | $this->_traverse($this->tree->getRoot()); 56 | } 57 | 58 | /** 59 | * helper method 60 | * 61 | * @param IBinaryNode|null $node 62 | */ 63 | public function _traverse(?IBinaryNode $node): void { 64 | if (null !== $node) { 65 | if (null !== $node->getLeft()) { 66 | $this->_traverse($node->getLeft()); 67 | } 68 | if (null !== $node->getRight()) { 69 | $this->_traverse($node->getRight()); 70 | } 71 | parent::visit($node->getValue()); 72 | } 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/Algorithm/Traversal/PreOrder.php: -------------------------------------------------------------------------------- 1 | tree = $tree; 49 | } 50 | 51 | /** 52 | * traverses a tre in preorder 53 | */ 54 | public function traverse(): void { 55 | $this->_traverse($this->tree->getRoot()); 56 | } 57 | 58 | /** 59 | * helper method 60 | * 61 | * @param IBinaryNode|null $node 62 | */ 63 | public function _traverse(?IBinaryNode $node): void { 64 | if (null !== $node) { 65 | parent::visit($node->getValue()); 66 | if (null !== $node->getLeft()) { 67 | $this->_traverse($node->getLeft()); 68 | } 69 | if (null !== $node->getRight()) { 70 | $this->_traverse($node->getRight()); 71 | } 72 | } 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/Algorithm/Various/Converter.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Algorithm\Various; 30 | 31 | use doganoo\PHPAlgorithms\common\Exception\InvalidKeyTypeException; 32 | use doganoo\PHPAlgorithms\common\Exception\UnsupportedKeyTypeException; 33 | use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\ArrayList; 34 | use doganoo\PHPAlgorithms\Datastructure\Table\HashTable; 35 | 36 | /** 37 | * Class Converter 38 | * @package doganoo\PHPAlgorithms\Algorithm\Various 39 | */ 40 | class Converter { 41 | 42 | /** 43 | * @param HashTable|null $table 44 | * @return ArrayList|null 45 | * @throws InvalidKeyTypeException 46 | * @throws UnsupportedKeyTypeException 47 | */ 48 | public function hashTableToArrayList(?HashTable $table): ?ArrayList { 49 | if (null === $table) return null; 50 | 51 | $keySet = $table->keySet(); 52 | $list = new ArrayList(); 53 | foreach ($keySet as $key) { 54 | $value = $table->get($key); 55 | $list->add($value); 56 | } 57 | 58 | return $list; 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractBinaryNode.php: -------------------------------------------------------------------------------- 1 | left; 45 | } 46 | 47 | /** 48 | * @param IBinaryNode|null $node 49 | */ 50 | public function setLeft(?IBinaryNode $node): void { 51 | $this->left = $node; 52 | } 53 | 54 | /** 55 | * @return IBinaryNode|null 56 | */ 57 | public function getRight(): ?IBinaryNode { 58 | return $this->right; 59 | } 60 | 61 | /** 62 | * @param IBinaryNode|null $node 63 | */ 64 | public function setRight(?IBinaryNode $node): void { 65 | $this->right = $node; 66 | } 67 | 68 | /** 69 | * @return array 70 | */ 71 | public function jsonSerialize(): array { 72 | return parent::jsonSerialize() + 73 | [ 74 | "left" => $this->getLeft() 75 | , "right" => $this->getRight() 76 | ]; 77 | } 78 | 79 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractGraphSearch.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Common\Abstracts; 30 | 31 | use doganoo\PHPAlgorithms\Datastructure\Graph\Graph\Node; 32 | use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\ArrayList; 33 | use function is_callable; 34 | 35 | /** 36 | * Class AbstractTraverse 37 | * 38 | * @package doganoo\PHPAlgorithms\common\Abstracts 39 | */ 40 | abstract class AbstractGraphSearch { 41 | 42 | /** @var $callable callable|null */ 43 | protected $callable = null; 44 | protected ArrayList $visited; 45 | 46 | public function __construct() { 47 | $this->visited = new ArrayList(); 48 | $this->callable = function (Node $value) { 49 | echo $value->getValue(); 50 | echo "\n"; 51 | }; 52 | } 53 | 54 | /** 55 | * @param AbstractGraph $graph 56 | * @return mixed 57 | */ 58 | public abstract function search(AbstractGraph $graph); 59 | 60 | /** 61 | * @param Node $value 62 | */ 63 | public function visit(Node $value): void { 64 | $callable = $this->callable; 65 | if (null === $this->callable 66 | && !is_callable($this->callable)) { 67 | $callable = function (Node $otherValue) { 68 | echo $otherValue->getValue(); 69 | echo "\n"; 70 | }; 71 | } 72 | $callable($value); 73 | } 74 | 75 | public function getVisitedNodes(): ?ArrayList { 76 | return $this->visited; 77 | } 78 | 79 | /** 80 | * @param callable $callable 81 | */ 82 | public function setCallable(callable $callable): void { 83 | $this->callable = $callable; 84 | } 85 | 86 | /** 87 | * @param Node|null $node 88 | * @return mixed 89 | */ 90 | public abstract function searchByNode(?Node $node); 91 | 92 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractNode.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Abstracts; 28 | 29 | use doganoo\PHPAlgorithms\Common\Interfaces\IComparable; 30 | use doganoo\PHPAlgorithms\Common\Interfaces\INode; 31 | use doganoo\PHPAlgorithms\Common\Util\Comparator; 32 | 33 | /** 34 | * Class AbstractNode 35 | * @package doganoo\PHPAlgorithms\Common\Abstracts 36 | */ 37 | abstract class AbstractNode implements INode { 38 | 39 | /** @var null|mixed $value */ 40 | private $value = null; 41 | 42 | /** 43 | * AbstractNode constructor. 44 | * @param null $value 45 | */ 46 | public function __construct($value = null) { 47 | $this->setValue($value); 48 | } 49 | 50 | /** 51 | * @param $value 52 | */ 53 | public function setValue($value): void { 54 | $this->value = $value; 55 | } 56 | 57 | /** 58 | * @return mixed 59 | */ 60 | public function getValue() { 61 | return $this->value; 62 | } 63 | 64 | /** 65 | * returns the height 66 | * 67 | * @return int 68 | */ 69 | public function getHeight(): int { 70 | return $this->height($this); 71 | } 72 | 73 | /** 74 | * helper method 75 | * 76 | * @param ?AbstractNode $node 77 | * @return int 78 | */ 79 | private function height(?AbstractNode $node): int { 80 | if (null === $node) { 81 | return 0; 82 | } 83 | 84 | return 1 + max($this->height($node->getLeft()), $this->height($node->getRight())); 85 | } 86 | 87 | /** 88 | * @param $object 89 | * @return int 90 | */ 91 | public function compareTo($object): int { 92 | if ($object instanceof AbstractNode) { 93 | if (Comparator::equals($this->getValue(), $object->getValue())) return IComparable::EQUAL; 94 | if (Comparator::lessThan($this->getValue(), $object->getValue())) return IComparable::IS_LESS; 95 | if (Comparator::greaterThan($this->getValue(), $object->getValue())) return IComparable::IS_GREATER; 96 | } 97 | return IComparable::IS_LESS; 98 | } 99 | 100 | /** 101 | * Specify data which should be serialized to JSON 102 | * @link https://php.net/manual/en/jsonserializable.jsonserialize.php 103 | * @return array data which can be serialized by json_encode, 104 | * which is a value of any type other than a resource. 105 | * @since 5.4.0 106 | */ 107 | public function jsonSerialize(): array { 108 | return [ 109 | "value" => $this->getValue() 110 | , "height" => $this->getHeight() 111 | ]; 112 | } 113 | 114 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractSet.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Abstracts; 28 | 29 | use doganoo\PHPAlgorithms\Common\Interfaces\ISet; 30 | use function crc32; 31 | use function spl_object_hash; 32 | 33 | /** 34 | * Class AbstractSet 35 | * 36 | * @package doganoo\PHPAlgorithms\Common\Abstracts 37 | */ 38 | abstract class AbstractSet implements ISet { 39 | 40 | /** 41 | * Compares the specified object with this set for equality. 42 | * 43 | * @param $object 44 | * @return bool 45 | */ 46 | public function equals($object): bool { 47 | return $this->compareTo($object) === 0; 48 | } 49 | 50 | /** 51 | * Returns the hash code value for this set. 52 | * 53 | * @return int 54 | */ 55 | public function hashCode(): int { 56 | return crc32(spl_object_hash($this)); 57 | } 58 | 59 | /** 60 | * Removes from this set all of its elements that are contained in the specified collection (optional operation). 61 | * 62 | * @param $elements 63 | * @return bool 64 | */ 65 | public function removeAll($elements): bool { 66 | $removed = false; 67 | foreach ($elements as $element) { 68 | $removed |= $this->remove($element); 69 | } 70 | return $removed; 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractTable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Abstracts; 28 | 29 | /** 30 | * Class AbstractTable 31 | * @package doganoo\PHPAlgorithms\Common\Abstracts 32 | * 33 | * THIS CLASS SERVES AS A BASE CLASS FOR ALL TABLE CLASSES. 34 | * CURRENTLY, THERE IS JUST A HASHTABLE CLASS WHICH DOES NOT 35 | * REQUIRE A BASE CLASS IMPLEMENTATION YET. 36 | * 37 | * THIS CLASS IS GOING TO BE IMPLEMENTED WHEN NEW TABLE CLASSES 38 | * ARE ADDED TO PHPALGORITHMS AND WE CAN DIFFER BETWEEN BASE CLASS 39 | * AND EXTENDER CLASS METHODS. 40 | * 41 | * TODO implement 42 | */ 43 | abstract class AbstractTable { 44 | 45 | } -------------------------------------------------------------------------------- /src/Common/Abstracts/AbstractTraverse.php: -------------------------------------------------------------------------------- 1 | callable; 51 | if (null === $this->callable 52 | && !is_callable($this->callable)) { 53 | $callable = function ($otherValue) { 54 | echo $otherValue; 55 | }; 56 | } 57 | $callable($value); 58 | } 59 | 60 | /** 61 | * @param callable $callable 62 | */ 63 | public function setCallable(callable $callable): void { 64 | $this->callable = $callable; 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /src/Common/Exception/IndexOutOfBoundsException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Exception; 28 | /** 29 | * Class IndexOutOfBoundsException 30 | * 31 | * @package doganoo\PHPAlgorithms\common\Exception 32 | */ 33 | class IndexOutOfBoundsException extends PHPAlgorithmsException { 34 | 35 | } -------------------------------------------------------------------------------- /src/Common/Exception/InvalidBitLengthException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Exception; 28 | /** 29 | * Class InvalidGraphTypeException 30 | * 31 | * @package doganoo\PHPAlgorithms\common\Exception 32 | */ 33 | class InvalidGraphTypeException extends PHPAlgorithmsException { 34 | 35 | } -------------------------------------------------------------------------------- /src/Common/Exception/InvalidKeyTypeException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Exception; 28 | /** 29 | * Class InvalidKeyTypeException 30 | * 31 | * @package doganoo\PHPAlgorithms\common\Exception 32 | */ 33 | class InvalidKeyTypeException extends PHPAlgorithmsException { 34 | 35 | } -------------------------------------------------------------------------------- /src/Common/Exception/InvalidSearchComparisionException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Exception; 28 | 29 | use Exception; 30 | 31 | /** 32 | * Class PHPAlgorithmsException 33 | * @package doganoo\PHPAlgorithms\Common\Exception 34 | */ 35 | class PHPAlgorithmsException extends Exception { 36 | 37 | protected $message = 'no message specified ¯\_(ツ)_/¯'; 38 | 39 | } -------------------------------------------------------------------------------- /src/Common/Exception/UnsupportedKeyTypeException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Exception; 28 | /** 29 | * Class UnsupportedKeyTypeException 30 | * 31 | * @package doganoo\PHPAlgorithms\common\Exception 32 | */ 33 | class UnsupportedKeyTypeException extends PHPAlgorithmsException { 34 | 35 | } -------------------------------------------------------------------------------- /src/Common/Exception/ValueNotAllowedException.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Interfaces; 28 | 29 | /** 30 | * Interface IBinaryNode 31 | * 32 | * @package doganoo\PHPAlgorithms\Common\Interfaces 33 | */ 34 | interface IBinaryNode extends INode { 35 | 36 | /** 37 | * @return mixed 38 | */ 39 | public function getValue(); 40 | 41 | /** 42 | * @return IBinaryNode|null 43 | */ 44 | public function getLeft(): ?IBinaryNode; 45 | 46 | /** 47 | * @param IBinaryNode|null $node 48 | */ 49 | public function setLeft(?IBinaryNode $node): void; 50 | 51 | /** 52 | * @return IBinaryNode|null 53 | */ 54 | public function getRight(): ?IBinaryNode; 55 | 56 | /** 57 | * @param IBinaryNode|null $node 58 | */ 59 | public function setRight(?IBinaryNode $node): void; 60 | 61 | /** 62 | * @return int 63 | */ 64 | public function getHeight(): int; 65 | 66 | } -------------------------------------------------------------------------------- /src/Common/Interfaces/ICache.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Interfaces; 28 | 29 | /** 30 | * Interface ICache 31 | * 32 | * @package doganoo\PHPAlgorithms\common\Interfaces 33 | */ 34 | interface ICache extends IComparable, \JsonSerializable { 35 | 36 | /** 37 | * adds a new key value pair 38 | * 39 | * @param $key 40 | * @param $value 41 | * @return bool 42 | */ 43 | public function put($key, $value); 44 | 45 | /** 46 | * retrieves a value 47 | * 48 | * @param $key 49 | * @return mixed 50 | */ 51 | public function get($key); 52 | 53 | /** 54 | * returns the last accessed, non-deleted value 55 | * 56 | * @return mixed 57 | */ 58 | public function last(); 59 | 60 | /** 61 | * deletes a given key 62 | * 63 | * @param $key 64 | * @return bool 65 | */ 66 | public function delete($key): bool; 67 | 68 | } -------------------------------------------------------------------------------- /src/Common/Interfaces/IComparable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Interfaces; 28 | 29 | /** 30 | * Interface IComparable 31 | * 32 | * @package doganoo\PHPAlgorithms\Common\Interfaces 33 | */ 34 | interface IComparable { 35 | 36 | public const IS_LESS = -1; 37 | public const EQUAL = 0; 38 | public const IS_GREATER = 1; 39 | 40 | /** 41 | * @param mixed $object 42 | * 43 | * @return int 44 | */ 45 | public function compareTo($object): int; 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/Common/Interfaces/IGraphSortable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Interfaces; 28 | 29 | interface IHashable { 30 | 31 | public function getHash(): string; 32 | 33 | } -------------------------------------------------------------------------------- /src/Common/Interfaces/IHeap.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Interfaces; 28 | 29 | use JsonSerializable; 30 | 31 | /** 32 | * Interface INode 33 | * 34 | * @package doganoo\PHPAlgorithms\common\Interfaces 35 | */ 36 | interface INode extends IComparable, JsonSerializable { 37 | /** 38 | * @return mixed 39 | */ 40 | public function getValue(); 41 | } -------------------------------------------------------------------------------- /src/Common/Interfaces/ISortable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Common\Iterator; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractLinkedList; 30 | use doganoo\PHPAlgorithms\Datastructure\Lists\Node; 31 | use Iterator; 32 | 33 | /** 34 | * Class LinkedListIterator 35 | * @package doganoo\PHPAlgorithms\Common\Iterator 36 | */ 37 | class LinkedListIterator implements Iterator { 38 | 39 | private AbstractLinkedList $linkedList; 40 | private ?Node $root; 41 | private int $i; 42 | 43 | /** 44 | * LinkedListIterator constructor. 45 | * @param AbstractLinkedList $linkedList 46 | */ 47 | public function __construct(AbstractLinkedList $linkedList) { 48 | $this->linkedList = $linkedList; 49 | $this->root = $this->linkedList->getHead(); 50 | $this->i = $this->root->size() + 1; 51 | } 52 | 53 | /** 54 | * @inheritDoc 55 | */ 56 | public function current(): mixed { 57 | return $this->root; 58 | } 59 | 60 | /** 61 | * @inheritDoc 62 | */ 63 | public function next(): void { 64 | $this->root = $this->root->getNext(); 65 | $this->i++; 66 | } 67 | 68 | /** 69 | * @inheritDoc 70 | */ 71 | public function key(): mixed { 72 | $key = $this->root->getKey(); 73 | 74 | if (true === is_int($key) || true === is_string($key)) { 75 | return $key; 76 | } 77 | 78 | return $this->i; 79 | } 80 | 81 | /** 82 | * @inheritDoc 83 | */ 84 | public function valid(): bool { 85 | return null !== $this->root; 86 | } 87 | 88 | /** 89 | * @inheritDoc 90 | */ 91 | public function rewind(): void { 92 | $this->i = $this->root->size() + 1; 93 | $this->root = $this->linkedList->getHead(); 94 | } 95 | 96 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Graph/UndirectedGraph.php: -------------------------------------------------------------------------------- 1 | nodeList->add($node); 56 | } 57 | 58 | /** 59 | * @param Node $startNode 60 | * @param Node $endNode 61 | * @return bool 62 | * @throws IndexOutOfBoundsException 63 | * @throws NodeNotFoundException 64 | */ 65 | public function addEdge(Node $startNode, Node $endNode): bool { 66 | $hasStart = $this->nodeList->containsValue($startNode); 67 | $hasEnd = $this->nodeList->containsValue($endNode); 68 | if (false === $hasStart) { 69 | throw new NodeNotFoundException(); 70 | } 71 | if (false === $hasEnd) { 72 | throw new NodeNotFoundException(); 73 | } 74 | $indexOfStartNode = $this->nodeList->indexOf($startNode); 75 | /** @var Node $startNode */ 76 | $startNode = $this->nodeList->get($indexOfStartNode); 77 | $indexOfEndNode = $this->nodeList->indexOf($endNode); 78 | /** @var Node $endNode */ 79 | $endNode = $this->nodeList->get($indexOfEndNode); 80 | 81 | if (!$startNode->hasAdjacent($endNode)) { 82 | //TODO notify caller 83 | return false; 84 | } 85 | $startNode->addAdjacent($endNode); 86 | $endNode->incrementInbound(); 87 | 88 | $this->nodeList->set($indexOfStartNode, $startNode); 89 | return true; 90 | } 91 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/AVLTree/Node.php: -------------------------------------------------------------------------------- 1 | getLeft()) ? 0 : $this->getLeft()->getHeight(); 59 | $rightHeight = (null === $this->getRight()) ? 0 : $this->getRight()->getHeight(); 60 | return $leftHeight - $rightHeight; 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/BinaryTree.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractBinaryNode; 30 | 31 | /** 32 | * Class BinaryNode 33 | * 34 | * @package doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree 35 | */ 36 | class BinaryNode extends AbstractBinaryNode { 37 | // silence is golden 38 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/BinaryTree/BinarySearchNode.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractBinaryNode; 30 | 31 | /** 32 | * Class BinarySearchNode 33 | * 34 | * @package doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree 35 | */ 36 | class BinarySearchNode extends AbstractBinaryNode { 37 | // silence is golden 38 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/Trie/EndOfWordNode.php: -------------------------------------------------------------------------------- 1 | getValue() === $object->getValue()) return 0; 55 | if ($this->getValue() < $object->getValue()) return -1; 56 | if ($this->getValue() > $object->getValue()) return 1; 57 | } 58 | return -1; 59 | } 60 | 61 | /** 62 | * Specify data which should be serialized to JSON 63 | * 64 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php 65 | * @return array data which can be serialized by json_encode, 66 | * which is a value of any type other than a resource. 67 | * @since 5.4.0 68 | */ 69 | public function jsonSerialize():array { 70 | $serializable = parent::jsonSerialize(); 71 | $serializable["type"] = EndOfWordNode::END_OF_WORD; 72 | return $serializable; 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/Trie/Node.php: -------------------------------------------------------------------------------- 1 | getChildNode($position); 48 | } 49 | 50 | /** 51 | * @param int $position 52 | * @return Node|null 53 | */ 54 | public function getChildNode(int $position): ?Node { 55 | if (isset($this->children[$position])) { 56 | return $this->children[$position]; 57 | } 58 | return null; 59 | } 60 | 61 | /** 62 | * @param int $position 63 | */ 64 | public function createChildNode(int $position): void { 65 | $node = new Node(); 66 | $node->setValue($position); 67 | $this->children[$position] = $node; 68 | } 69 | 70 | /** 71 | * creates an node that indicates the end of the word 72 | */ 73 | public function createEndOfWordNode(): void { 74 | $this->children[] = new EndOfWordNode(); 75 | } 76 | 77 | /** 78 | * indicates whether it is the end of the node 79 | * @return bool 80 | */ 81 | public function isEndOfWordNode(): bool { 82 | return $this->children[0] instanceof EndOfWordNode; 83 | } 84 | 85 | /** 86 | * @param $object 87 | * @return int 88 | */ 89 | public function compareTo($object): int { 90 | if ($object instanceof Node) { 91 | if ($this->getValue() === $object->getValue()) return 0; 92 | if ($this->getValue() < $object->getValue()) return -1; 93 | if ($this->getValue() > $object->getValue()) return 1; 94 | } 95 | return -1; 96 | } 97 | 98 | /** 99 | * @return mixed 100 | */ 101 | public function getValue() { 102 | return $this->value; 103 | } 104 | 105 | /** 106 | * @param mixed $value 107 | */ 108 | public function setValue($value): void { 109 | $this->value = $value; 110 | } 111 | 112 | /** 113 | * Specify data which should be serialized to JSON 114 | * 115 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php 116 | * @return array data which can be serialized by json_encode, 117 | * which is a value of any type other than a resource. 118 | * @since 5.4.0 119 | */ 120 | public function jsonSerialize(): array { 121 | return [ 122 | "value" => $this->getValue() 123 | , "children" => $this->children, 124 | ]; 125 | } 126 | 127 | } -------------------------------------------------------------------------------- /src/Datastructure/Graph/Tree/Trie/RootNode.php: -------------------------------------------------------------------------------- 1 | setValue(self::ROOT_NODE); 48 | } 49 | 50 | /** 51 | * @param $object 52 | * @return int 53 | */ 54 | public function compareTo($object): int { 55 | if ($object instanceof RootNode) { 56 | if ($this->getValue() === $object->getValue()) return 0; 57 | if ($this->getValue() < $object->getValue()) return -1; 58 | if ($this->getValue() > $object->getValue()) return 1; 59 | } 60 | return -1; 61 | } 62 | 63 | public function jsonSerialize(): array { 64 | $serializable = parent::jsonSerialize(); 65 | $serializable["type"] = RootNode::ROOT_NODE; 66 | return $serializable; 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /src/Datastructure/Lists/LinkedList/DoublyLinkedList.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Datastructure\Lists\LinkedList; 30 | 31 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractLinkedList; 32 | use doganoo\PHPAlgorithms\Datastructure\Lists\Node; 33 | 34 | /** 35 | * Class DoublyLinkedList 36 | * 37 | * @package doganoo\PHPAlgorithms\LinkedList 38 | */ 39 | class DoublyLinkedList extends AbstractLinkedList { 40 | 41 | /** 42 | * appends an node on top of the list 43 | * 44 | * @param Node|null $node 45 | * @return bool 46 | */ 47 | public function append(?Node $node): bool { 48 | if ($node === null) { 49 | return false; 50 | } 51 | 52 | /* 53 | * need to clone the object otherwise the object 54 | * references are going crazy. 55 | * 56 | * Furthermore, setting previous and next to null 57 | * as they will be set later. 58 | */ 59 | $newNode = clone $node; 60 | $newNode->setPrevious(null); 61 | $newNode->setNext(null); 62 | 63 | if ($this->getHead() === null) { 64 | $this->setHead($newNode); 65 | return true; 66 | } 67 | 68 | $head = $this->getHead(); 69 | $i = 0; 70 | while ($head->getNext() !== null) { 71 | $head = $head->getNext(); 72 | $i++; 73 | } 74 | $newNode->setPrevious($head); 75 | $head->setNext($newNode); 76 | return true; 77 | } 78 | 79 | /** 80 | * prepends a node on top of the list 81 | * 82 | * @param Node|null $node 83 | * @return bool 84 | */ 85 | public function prepend(?Node $node): bool { 86 | if ($node === null) { 87 | return false; 88 | } 89 | /* 90 | * need to clone the object otherwise the object 91 | * references are going crazy. 92 | * 93 | * Furthermore, setting previous and next to null 94 | * as they will be set later. 95 | */ 96 | $newNode = clone $node; 97 | $newNode->setPrevious(null); 98 | $newNode->setNext(null); 99 | 100 | if ($this->getHead() === null) { 101 | $this->setHead($newNode); 102 | return true; 103 | } 104 | $head = $this->getHead(); 105 | $head->setPrevious($newNode); 106 | $newNode->setNext($head); 107 | $this->setHead($newNode); 108 | return true; 109 | } 110 | 111 | } -------------------------------------------------------------------------------- /src/Datastructure/Lists/LinkedList/SinglyLinkedList.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Datastructure\Lists\LinkedList; 30 | 31 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractLinkedList; 32 | use doganoo\PHPAlgorithms\Datastructure\Lists\Node; 33 | 34 | /** 35 | * Class SinglyLinkedList 36 | * 37 | * @package doganoo\PHPAlgorithms\LinkedList 38 | */ 39 | class SinglyLinkedList extends AbstractLinkedList { 40 | 41 | /** 42 | * $node is added to the end of the list. 43 | * The method checks the following: 44 | * 45 | * 1. given node is null. Terminate method and return false 46 | * 2. head equals to null. Set head = $node, terminate and return true 47 | * 3. iterate over temporary node until you have reached the last 48 | * node (iterate until next !== null) 49 | * 50 | * once you have reached the end, set $node as next of your 51 | * temporary node 52 | * 53 | * @param Node $node 54 | * @return bool 55 | */ 56 | public function append(?Node $node): bool { 57 | if ($node === null) { 58 | return false; 59 | } 60 | $head = $this->getHead(); 61 | if ($head === null) { 62 | $this->setHead($node); 63 | return true; 64 | } 65 | while ($head->getNext() !== null) { 66 | $head = $head->getNext(); 67 | } 68 | $head->setNext($node); 69 | return true; 70 | } 71 | 72 | /** 73 | * the prepend method simply checks first if the node is still valid. 74 | * If it does not equal to null, the next pointer of the new node is 75 | * set to head and the head is set to the new node in order to create 76 | * the new head. 77 | * 78 | * @param Node $node 79 | * @return bool 80 | */ 81 | public function prepend(?Node $node): bool { 82 | if ($node === null) { 83 | return false; 84 | } 85 | $node->setNext($this->getHead()); 86 | $this->setHead($node); 87 | return true; 88 | } 89 | 90 | } -------------------------------------------------------------------------------- /src/Datastructure/Map/Map.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithms\Datastructure\Map; 30 | 31 | use doganoo\PHPAlgorithms\Common\Util\Comparator; 32 | use function array_fill; 33 | use function array_filter; 34 | use function count; 35 | use const ARRAY_FILTER_USE_BOTH; 36 | 37 | /** 38 | * Class Map 39 | * 40 | * @package doganoo\PHPAlgorithms\Datastructure\Map 41 | */ 42 | class Map { 43 | 44 | /** @var int MAX_SIZE */ 45 | public const MAX_SIZE = 128; 46 | 47 | private array $map = []; 48 | 49 | /** 50 | * Map constructor. 51 | */ 52 | public function __construct() { 53 | $this->clear(); 54 | } 55 | 56 | /** 57 | * @return bool 58 | */ 59 | public function clear(): bool { 60 | $this->map = array_fill(0, Map::MAX_SIZE, null); 61 | return true; 62 | } 63 | 64 | /** 65 | * @param $key 66 | * @param $value 67 | */ 68 | public function add($key, $value): void { 69 | $this->map[$key] = $value; 70 | } 71 | 72 | /** 73 | * @return int 74 | */ 75 | public function size(): int { 76 | $array = array_filter( 77 | $this->map, 78 | static function ($v, $k) { 79 | return $v !== null; 80 | }, 81 | ARRAY_FILTER_USE_BOTH 82 | ); 83 | return count($array); 84 | } 85 | 86 | /** 87 | * @param $value 88 | * @return bool 89 | */ 90 | public function containsValue($value): bool { 91 | foreach ($this->map as $key => $val) { 92 | if (Comparator::equals($value, $val)) { 93 | return true; 94 | } 95 | } 96 | return false; 97 | } 98 | 99 | /** 100 | * @param $key 101 | * @return bool 102 | */ 103 | public function containsKey($key): bool { 104 | foreach ($this->map as $k => $val) { 105 | if (Comparator::equals($key, $k)) { 106 | return true; 107 | } 108 | } 109 | return false; 110 | } 111 | 112 | } -------------------------------------------------------------------------------- /src/Datastructure/Stackqueue/FixedQueue.php: -------------------------------------------------------------------------------- 1 | maxSize = $maxSize; 46 | } 47 | 48 | /** 49 | * Specify data which should be serialized to JSON 50 | * 51 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php 52 | * @return array data which can be serialized by json_encode, 53 | * which is a value of any type other than a resource. 54 | * @since 5.4.0 55 | */ 56 | public function jsonSerialize(): array { 57 | $serializable = parent::jsonSerialize(); 58 | $serializable["max_size"] = $this->maxSize; 59 | return $serializable; 60 | } 61 | 62 | /** 63 | * returns whether the element is valid or not. 64 | * Checks among other things also the number of elements 65 | * 66 | * @return bool 67 | */ 68 | protected function isValid(): bool { 69 | $parent = parent::isValid(); 70 | $maxSize = parent::size() < $this->maxSize; 71 | return $parent && $maxSize; 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/Datastructure/Stackqueue/FixedStack.php: -------------------------------------------------------------------------------- 1 | maxSize = $maxSize; 46 | } 47 | 48 | /** 49 | * returns whether the element is valid or not. 50 | * Checks among other things also the number of elements 51 | * 52 | * @return bool 53 | */ 54 | protected function isValid(): bool { 55 | $parent = parent::isValid(); 56 | $maxSize = parent::size() < $this->maxSize; 57 | return $parent && $maxSize; 58 | } 59 | 60 | /** 61 | * Specify data which should be serialized to JSON 62 | * 63 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php 64 | * @return mixed data which can be serialized by json_encode, 65 | * which is a value of any type other than a resource. 66 | * @since 5.4.0 67 | */ 68 | public function jsonSerialize(): array { 69 | $serializable = parent::jsonSerialize(); 70 | $serializable["max_size"] = $this->maxSize; 71 | return $serializable; 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/Datastructure/Table/ConsistentHashTable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Datastructure\Table; 28 | 29 | use doganoo\PHPAlgorithms\Common\Exception\InvalidKeyTypeException; 30 | use doganoo\PHPAlgorithms\Common\Exception\UnsupportedKeyTypeException; 31 | use doganoo\PHPAlgorithms\Common\Util\MapUtil; 32 | 33 | /** 34 | * Class ConsistentHashTable 35 | * @package doganoo\PHPAlgorithms\Datastructure\Table 36 | * @author Dogan Ucar 37 | * TODO implement! 38 | */ 39 | class ConsistentHashTable { 40 | 41 | private HashTable $nodes; 42 | private int $ringSize = PHP_INT_MAX; 43 | 44 | public function __construct() { 45 | $this->nodes = new HashTable(); 46 | } 47 | 48 | /** 49 | * @param mixed $key 50 | * @return mixed|null 51 | * @throws InvalidKeyTypeException 52 | * @throws UnsupportedKeyTypeException 53 | */ 54 | public function getNode($key) { 55 | $angle = $this->getAngle($this->getHash($key)); 56 | $i = $angle; 57 | 58 | while ($i >= 0) { 59 | 60 | if ($this->nodes->containsKey($i)) { 61 | return $this->nodes->get($i); 62 | } 63 | $i--; 64 | } 65 | 66 | return null; 67 | } 68 | 69 | public function addNode($key, $node): void { 70 | $angle = $this->getAngle($this->getHash($key)); 71 | $this->nodes->put($angle, $node); 72 | } 73 | 74 | private function getAngle(int $hash): int { 75 | // (1633428562 / 10^10) * 360 76 | return ($hash / $this->ringSize) * 360; 77 | } 78 | 79 | /** 80 | * returns the hash that is used to calculate the 81 | * bucket index. 82 | * 83 | * @param $key 84 | * 85 | * @return int 86 | * @throws InvalidKeyTypeException 87 | * @throws UnsupportedKeyTypeException 88 | */ 89 | private function getHash($key): int { 90 | $key = MapUtil::normalizeKey($key); 91 | return crc32((string) $key); 92 | } 93 | 94 | } -------------------------------------------------------------------------------- /src/Datastructure/Table/SimpleTable.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithms\Datastructure\Table; 28 | 29 | use doganoo\PHPAlgorithms\Common\Abstracts\AbstractTable; 30 | 31 | /** 32 | * Class SimpleTable 33 | * @package doganoo\PHPAlgorithms\Datastructure\Table 34 | */ 35 | class SimpleTable extends AbstractTable { 36 | 37 | private array $table; 38 | 39 | /** 40 | * SimpleTable constructor. 41 | */ 42 | public function __construct() { 43 | $this->table = []; 44 | } 45 | 46 | /** 47 | * @param $key 48 | * @param $value 49 | */ 50 | public function put($key, $value): void { 51 | $this->table[$key] = $value; 52 | } 53 | 54 | /** 55 | * @param $key 56 | * @return mixed 57 | */ 58 | public function get($key) { 59 | return $this->table[$key] ?? null; 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /src/Datastructure/Various/Enum.php: -------------------------------------------------------------------------------- 1 | nullAllowed = $nullAllowed; 50 | $this->allowedValues = $allowedValues; 51 | } 52 | 53 | /** 54 | * @param $value 55 | * @throws NullNotAllowedException 56 | * @throws ValueNotAllowedException 57 | */ 58 | public function setValue($value): void { 59 | $isNull = $this->isNull($value); 60 | 61 | if (false === $this->nullAllowed && true === $isNull) { 62 | throw new NullNotAllowedException(); 63 | } 64 | 65 | if (false === in_array($value, $this->allowedValues)) { 66 | throw new ValueNotAllowedException(); 67 | } 68 | 69 | $this->value = $value; 70 | 71 | } 72 | 73 | /** 74 | * @return mixed 75 | */ 76 | public function getValue() { 77 | return $this->value; 78 | } 79 | 80 | /** 81 | * @param $value 82 | * @return bool 83 | */ 84 | private function isNull($value): bool { 85 | return "" === $value || null === $value; 86 | } 87 | 88 | 89 | /** 90 | * @param $object 91 | * @return int 92 | */ 93 | public function compareTo($object): int { 94 | if ($object instanceof Enum) { 95 | if (count($this->value) === count($object->value)) return IComparable::EQUAL; 96 | } 97 | return IComparable::IS_LESS; 98 | } 99 | 100 | } -------------------------------------------------------------------------------- /tests/Cache/LRUCacheTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Cache; 28 | 29 | use doganoo\PHPAlgorithms\common\Exception\InvalidKeyTypeException; 30 | use doganoo\PHPAlgorithms\common\Exception\UnsupportedKeyTypeException; 31 | use doganoo\PHPAlgorithms\Datastructure\Cache\LRUCache; 32 | use PHPUnit\Framework\TestCase; 33 | 34 | class LRUCacheTest extends TestCase { 35 | 36 | /** 37 | * @throws InvalidKeyTypeException 38 | * @throws UnsupportedKeyTypeException 39 | */ 40 | public function testCache() { 41 | $cache = new LRUCache(); 42 | $cache->put("a", 1); 43 | $cache->put("b", 2); 44 | $value = $cache->get("a"); 45 | $this->assertTrue($value === 1); 46 | $last = $cache->last(); 47 | $this->assertTrue($last === "a"); 48 | $deleted = $cache->delete("a"); 49 | $this->assertTrue($deleted === true); 50 | $last = $cache->last(); 51 | $this->assertTrue($last === "b"); 52 | } 53 | 54 | /** 55 | * @throws InvalidKeyTypeException 56 | * @throws UnsupportedKeyTypeException 57 | */ 58 | public function testCacheWithSize() { 59 | $cache = new LRUCache(2); 60 | $cache->put("a", 1); 61 | $cache->put("b", 2); 62 | $this->assertTrue($cache->last() === "b"); 63 | $cache->put("c", 3); 64 | $this->assertTrue($cache->get("a") === null); 65 | $value = $cache->get("b"); 66 | $this->assertTrue($value === 2); 67 | $cache->put("d", 4); 68 | $this->assertTrue($cache->get("c") === null); 69 | } 70 | 71 | } -------------------------------------------------------------------------------- /tests/Comparator/ComparatorTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithmsTest\Comparator; 30 | 31 | use doganoo\PHPAlgorithms\Common\Util\Comparator; 32 | use doganoo\PHPAlgorithms\Datastructure\Graph\Graph\Node; 33 | use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\ArrayList; 34 | use PHPUnit\Framework\TestCase; 35 | 36 | class ComparatorTest extends TestCase { 37 | 38 | public function testComparator() { 39 | $node = new Node(1); 40 | $node2 = new Node(2); 41 | $this->assertTrue(Comparator::equals($node, $node2) === false); 42 | 43 | 44 | $node = new Node(1); 45 | $node2 = new Node(1); 46 | $this->assertTrue(Comparator::equals($node, $node2) === true); 47 | 48 | 49 | $node = new Node(1); 50 | $value = "test"; 51 | $this->assertTrue(Comparator::equals($node, $value) === false); 52 | 53 | $node = "test"; 54 | $value = "test"; 55 | $this->assertTrue(Comparator::equals($node, $value) === true); 56 | 57 | $node = "1"; 58 | $value = 1; 59 | $this->assertTrue(Comparator::equals($node, $value) === true); 60 | 61 | $node = new Node(1); 62 | $value = new ArrayList(); 63 | $this->assertTrue(Comparator::equals($node, $value) === false); 64 | } 65 | 66 | } -------------------------------------------------------------------------------- /tests/Graph/graph/DirectedGraphTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Graph\graph; 28 | 29 | 30 | use doganoo\PHPAlgorithms\Datastructure\Graph\Graph\DirectedGraph; 31 | use doganoo\PHPAlgorithms\Datastructure\Graph\Graph\Node; 32 | use PHPUnit\Framework\TestCase; 33 | 34 | class DirectedGraphTest extends TestCase { 35 | 36 | public function testAdd() { 37 | $graph = new DirectedGraph(); 38 | $this->assertTrue($graph->addNode(new Node(1)) === true); 39 | } 40 | 41 | public function testSubGraphSize() { 42 | $one = new Node(1); 43 | $nine = new Node(9); 44 | $five = new Node(5); 45 | 46 | $one->addAdjacent($nine); 47 | $one->addAdjacent($five); 48 | 49 | $two = new Node(2); 50 | $four = new Node(4); 51 | 52 | $two->addAdjacent($four); 53 | 54 | $six = new Node(6); 55 | 56 | $graph = new DirectedGraph(); 57 | $graph->addNode($one); 58 | $graph->addNode($two); 59 | $graph->addNode($six); 60 | 61 | $this->assertTrue(3 === $graph->numberOfSubGraph()); 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /tests/Graph/trees/AVLTree.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Graph\trees; 28 | 29 | 30 | use PHPUnit\Framework\TestCase; 31 | 32 | class AVLTree extends TestCase { 33 | 34 | 35 | public function testTree() { 36 | 37 | $this->markTestSkipped("need to implement - There is one bug remaining"); 38 | 39 | // $avlTree = new AVLTreee(); 40 | // $avlTree->insertValue(10); 41 | // $avlTree->insertValue(20); 42 | // $avlTree->insertValue(30); 43 | // $avlTree->insertValue(40); 44 | // $avlTree->insertValue(50); 45 | // $avlTree->insertValue(25); 46 | 47 | // $array = []; 48 | // $preOrder = new PreOrder($avlTree); 49 | // $preOrder->setCallable(function ($v) use (&$array){ 50 | // $array[] = $v; 51 | // }); 52 | // $preOrder->traverse(); 53 | // 54 | // print_r($array); 55 | // $this->assertTrue($array === [30, 20, 10, 25, 40, 50]); 56 | 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /tests/Graph/trees/BinaryTreeTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Graph\trees; 28 | 29 | use doganoo\PHPAlgorithms\Algorithm\Traversal\InOrder; 30 | use doganoo\PHPAlgorithms\Algorithm\Traversal\PostOrder; 31 | use doganoo\PHPAlgorithms\Algorithm\Traversal\PreOrder; 32 | use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree; 33 | use doganoo\PHPAlgorithmsTest\Util\TreeUtil; 34 | use PHPUnit\Framework\TestCase; 35 | 36 | class BinaryTreeTest extends TestCase { 37 | 38 | /** 39 | * tests addition and height 40 | */ 41 | public function testAdd() { 42 | /** @var BinaryTree $bst */ 43 | $bst = TreeUtil::getBinaryTree(); 44 | $node = $bst->search(1); 45 | $this->assertTrue($node !== null); 46 | } 47 | 48 | /** 49 | * tests in order Traversal 50 | */ 51 | public function testInOrder() { 52 | /** @var BinaryTree $bst */ 53 | $bst = TreeUtil::getBinaryTree(); 54 | $array = []; 55 | $traversal = new InOrder($bst); 56 | $traversal->setCallable(function ($value) use (&$array) { 57 | $array[] = $value; 58 | }); 59 | $traversal->traverse(); 60 | $this->assertTrue($array === [1, 2, 5, 6]); 61 | } 62 | 63 | /** 64 | * tests pre order Traversal 65 | */ 66 | public function testPreOrder() { 67 | /** @var BinaryTree $bst */ 68 | $bst = TreeUtil::getBinaryTree(); 69 | $array = []; 70 | $traversal = new PreOrder($bst); 71 | $traversal->setCallable(function ($value) use (&$array) { 72 | $array[] = $value; 73 | }); 74 | $traversal->traverse(); 75 | $this->assertTrue($array === [5, 2, 1, 6]); 76 | } 77 | 78 | /** 79 | * tests post order Traversal 80 | */ 81 | public function testPostOrder() { 82 | /** @var BinaryTree $bst */ 83 | $bst = TreeUtil::getBinaryTree(); 84 | $array = []; 85 | $traversal = new PostOrder($bst); 86 | $traversal->setCallable(function ($value) use (&$array) { 87 | $array[] = $value; 88 | }); 89 | $traversal->traverse(); 90 | $this->assertTrue($array === [1, 2, 6, 5]); 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /tests/Graph/trees/trie/TrieTest.php: -------------------------------------------------------------------------------- 1 | insert("Test"); 41 | $found = $trie->search("Test"); 42 | $this->assertTrue($found === true); 43 | $found = $trie->search("Te", true); 44 | $this->assertTrue($found === true); 45 | } 46 | 47 | public function testWordCount(): void { 48 | $this->markTestSkipped("need to repair :-("); 49 | $trie = new Trie(); 50 | $trie->insert("this"); 51 | $trie->insert("is"); 52 | $trie->insert("a"); 53 | $trie->insert("very"); 54 | $trie->insert("long"); 55 | $trie->insert("word"); 56 | 57 | $this->assertTrue(6 === $trie->countWords()); 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /tests/Lists/ArrayList/StringBuilderTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithmsTest\Lists\ArrayList; 30 | 31 | use doganoo\PHPAlgorithms\Datastructure\Lists\ArrayList\StringBuilder; 32 | use PHPUnit\Framework\TestCase; 33 | 34 | class StringBuilderTest extends TestCase { 35 | 36 | public function testConstructor() { 37 | $nullStringBuilder = new StringBuilder(); 38 | $this->assertTrue($nullStringBuilder->capacity() === 0); 39 | $this->assertTrue($nullStringBuilder == ""); 40 | 41 | $stringBuilder = new StringBuilder("phpalgorithms"); 42 | $this->assertTrue($stringBuilder->capacity() === 13); 43 | $this->assertTrue($stringBuilder == "phpalgorithms"); 44 | 45 | $intStringBuilder = new StringBuilder(10); 46 | $this->assertTrue($intStringBuilder->capacity() === 10); 47 | $this->assertTrue($intStringBuilder == ""); 48 | } 49 | 50 | public function testAppend() { 51 | $stringBuilder = new StringBuilder(); 52 | $stringBuilder->append("p"); 53 | $stringBuilder->append("h"); 54 | $stringBuilder->append("p"); 55 | $this->assertTrue($stringBuilder->length() === 3); 56 | $this->assertTrue($stringBuilder == "php"); 57 | $this->assertTrue($stringBuilder->charAt(1) === "h"); 58 | 59 | $stringBuilder = new StringBuilder(); 60 | $stringBuilder->append("p"); 61 | $stringBuilder->append("h"); 62 | $stringBuilder->append("p"); 63 | $stringBuilder->insert(1, "tes"); 64 | $this->assertTrue($stringBuilder->capacity() === 4); 65 | $this->assertTrue($stringBuilder->charAt(1) === "t"); 66 | } 67 | 68 | public function testReverse() { 69 | $stringBuilder = new StringBuilder(); 70 | $stringBuilder->append("phpalgorithms"); 71 | $stringBuilder = $stringBuilder->reverse(); 72 | $this->assertTrue($stringBuilder == "smhtiroglaphp"); 73 | } 74 | 75 | public function testDelete() { 76 | $stringBuilder = new StringBuilder(); 77 | $stringBuilder->append("p"); 78 | $stringBuilder->append("h"); 79 | $stringBuilder->append("p"); 80 | $stringBuilder->delete(0, 1); 81 | $this->assertTrue($stringBuilder == "p"); 82 | $this->assertTrue($stringBuilder->length() === 1); 83 | $stringBuilder->deleteCharAt(0); 84 | $this->assertTrue($stringBuilder == ""); 85 | $this->assertTrue($stringBuilder->length() === 0); 86 | } 87 | 88 | public function testIndexOf() { 89 | $stringBuilder = new StringBuilder(); 90 | $stringBuilder->append("p"); 91 | $stringBuilder->append("h"); 92 | $stringBuilder->append("p"); 93 | 94 | $this->assertTrue($stringBuilder->indexOf("h") === 1); 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /tests/Lists/LinkedList/SinglyLinkedListTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithmsTest\Lists\LinkedList; 30 | 31 | use doganoo\PHPAlgorithms\Datastructure\Lists\LinkedList\SinglyLinkedList; 32 | use doganoo\PHPAlgorithmsTest\Util\LinkedListUtil; 33 | use PHPUnit\Framework\TestCase; 34 | 35 | /** 36 | * Class SinglyLinkedListTest PHPUnit test class 37 | */ 38 | class SinglyLinkedListTest extends TestCase { 39 | 40 | /** 41 | * tests appending a new node to the list 42 | * 43 | * note that the underlying LinkedList methods are already tested 44 | * by DoublyLinkedListTest class and do not need to be tested here. 45 | */ 46 | public function testAppend(): void { 47 | $list = LinkedListUtil::getSinglyLinkedList(); 48 | $node = LinkedListUtil::getNode(4, 1); 49 | $list->append($node); 50 | $this->assertTrue($list->size() === 4); 51 | $this->assertTrue($list->getHead()->getKey() === 1); 52 | $this->assertTrue($list->getHead()->getValue() === "one"); 53 | } 54 | 55 | /** 56 | * tests prepending a new node to the list 57 | */ 58 | public function testPrepend(): void { 59 | $list = LinkedListUtil::getSinglyLinkedList(); 60 | $node = LinkedListUtil::getNode(4, 1); 61 | $list->prepend($node); 62 | $this->assertTrue($list->size() === 4); 63 | $this->assertTrue($list->getHead()->getKey() === 4); 64 | $this->assertTrue($list->getHead()->getValue() === 1); 65 | } 66 | 67 | public function testContains(): void { 68 | $list = LinkedListUtil::getSinglyLinkedList(); 69 | $contains = $list->containsKey(1); 70 | $this->assertTrue($contains === true); 71 | 72 | $list->add("test", 2); 73 | $this->assertTrue($list->size() === 4); 74 | $this->assertTrue($list->containsKey("testw") === false); 75 | $this->assertTrue($list->containsKey("test") === true); 76 | } 77 | 78 | public function testRemove(): void { 79 | $singlyLinkedList = new SinglyLinkedList(); 80 | $singlyLinkedList->add("calorie_tracker", new class { 81 | 82 | }); 83 | $singlyLinkedList->add("tnc", new class { 84 | 85 | }); 86 | 87 | $this->assertTrue(2 === $singlyLinkedList->size()); 88 | $singlyLinkedList->remove("calorie_tracker"); 89 | $this->assertTrue(1 === $singlyLinkedList->size()); 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /tests/Map/NodeTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithmsTest\Map; 30 | 31 | use doganoo\PHPAlgorithms\Datastructure\Lists\Node; 32 | use PHPUnit\Framework\TestCase; 33 | 34 | /** 35 | * Class NodeTest PHPUnit test class 36 | */ 37 | class NodeTest extends TestCase { 38 | 39 | /** 40 | * tests node assignments 41 | */ 42 | public function testNodeReference(): void { 43 | $a = new Node(); 44 | $a->setKey(1); 45 | $a->setValue("1"); 46 | 47 | $b = new Node(); 48 | $b->setKey(2); 49 | $b->setValue("2"); 50 | 51 | $c = new Node(); 52 | $c->setKey(3); 53 | $c->setValue("3"); 54 | 55 | $b->setNext($c); 56 | $a->setNext($b); 57 | 58 | $d = $a; 59 | $d = $d->getNext(); 60 | $this->assertTrue(null !== $d && $d->size() == 2); 61 | $this->assertTrue(null !== $d && $a->size() == 3); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /tests/Set/HashSetTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * @author Eugene Kirillov 9 | * 10 | * Permission is hereby granted, free of charge, to any person obtaining a copy 11 | * of this software and associated documentation files (the "Software"), to deal 12 | * in the Software without restriction, including without limitation the rights 13 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | * copies of the Software, and to permit persons to whom the Software is 15 | * furnished to do so, subject to the following conditions: 16 | * 17 | * The above copyright notice and this permission notice shall be included in all 18 | * copies or substantial portions of the Software. 19 | * 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | * SOFTWARE. 27 | */ 28 | 29 | namespace doganoo\PHPAlgorithmsTest\Set; 30 | 31 | use doganoo\PHPAlgorithms\Common\Exception\InvalidKeyTypeException; 32 | use doganoo\PHPAlgorithms\Common\Exception\UnsupportedKeyTypeException; 33 | use doganoo\PHPAlgorithms\Datastructure\Set\HashSet; 34 | use PHPUnit\Framework\TestCase; 35 | 36 | /** 37 | * Class HashSetTest PHPUnit test class 38 | */ 39 | class HashSetTest extends TestCase { 40 | 41 | /** 42 | * @throws InvalidKeyTypeException 43 | * @throws UnsupportedKeyTypeException 44 | */ 45 | public function testAdd(): void { 46 | $hashSet = new HashSet(); 47 | $hashSet->add("test"); 48 | $this->assertTrue($hashSet->size() === 1); 49 | 50 | $hashSet->addAll(["one", "two", "three", "four"]); 51 | $this->assertTrue($hashSet->size() === 5); 52 | $added = $hashSet->add("one"); 53 | $this->assertTrue($added === false); 54 | $this->assertTrue($hashSet->size() === 5); 55 | } 56 | 57 | /** 58 | * @throws UnsupportedKeyTypeException 59 | * @throws InvalidKeyTypeException 60 | */ 61 | public function testContains(): void { 62 | $hashSet = new HashSet(); 63 | $hashSet->add("test"); 64 | 65 | $this->assertTrue($hashSet->size() === 1); 66 | $this->assertTrue($hashSet->contains("test")); 67 | 68 | $hashSet->addAll(["one", "two", "three", "four"]); 69 | 70 | $contains = $hashSet->containsAll([ 71 | "one" 72 | , "two" 73 | , "three" 74 | , "four" 75 | , "five" 76 | , "test", 77 | ]); 78 | $this->assertTrue($contains === false); 79 | } 80 | 81 | /** 82 | * @throws InvalidKeyTypeException 83 | * @throws UnsupportedKeyTypeException 84 | */ 85 | public function testClear(): void { 86 | $hashSet = new HashSet(); 87 | $hashSet->addAll(["one", "two", "three", "four"]); 88 | $this->assertTrue($hashSet->size() === 4); 89 | $hashSet->clear(); 90 | $this->assertTrue($hashSet->size() === 0); 91 | $this->assertTrue($hashSet->isEmpty()); 92 | } 93 | 94 | /** 95 | * @throws UnsupportedKeyTypeException 96 | * @throws InvalidKeyTypeException 97 | */ 98 | public function testRemove(): void { 99 | $hashSet = new HashSet(); 100 | $hashSet->addAll(["one", "two", "three", "four"]); 101 | $this->assertTrue($hashSet->contains("one") === true); 102 | $hashSet->remove("one"); 103 | $this->assertTrue($hashSet->contains("one") === false); 104 | } 105 | 106 | } -------------------------------------------------------------------------------- /tests/StackQueue/CircularBufferTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\StackQueue; 28 | 29 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\CircularBuffer; 30 | use PHPUnit\Framework\TestCase; 31 | 32 | /** 33 | * Class CircularBufferTest 34 | */ 35 | class CircularBufferTest extends TestCase { 36 | 37 | public function testMinimalSize(): void { 38 | $buffer = new CircularBuffer(2); 39 | $this->assertTrue($buffer->isEmpty() === true); 40 | $buffer->enqueue("A"); 41 | $this->assertTrue($buffer->isEmpty() === false); 42 | $this->assertTrue($buffer->isFull() === true); 43 | } 44 | 45 | public function testBigBuffer(): void { 46 | $buffer = new CircularBuffer(8); 47 | $this->assertTrue($buffer->isEmpty() === true); 48 | $buffer->enqueue("A"); 49 | $this->assertTrue($buffer->isEmpty() === false); 50 | $this->assertTrue($buffer->isFull() === false); 51 | $buffer->dequeue(); 52 | $this->assertTrue($buffer->isEmpty() === true); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /tests/StackQueue/FixedStackTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\StackQueue; 28 | 29 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\FixedQueue; 30 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\FixedStack; 31 | use Exception; 32 | use PHPUnit\Framework\TestCase; 33 | use stdClass; 34 | 35 | /** 36 | * Class StackQueueTest class testing Stacks and Queues 37 | */ 38 | class FixedStackTest extends TestCase { 39 | 40 | /** 41 | * Stack class test 42 | */ 43 | public function testStack(): void { 44 | $stack = new FixedStack(2); 45 | $added = $stack->push(new stdClass()); 46 | $this->assertTrue($added === true); 47 | $stack->push(new Exception()); 48 | $this->assertTrue($stack->isEmpty() == false); 49 | $this->assertTrue($stack->size() === 2); 50 | $added = $stack->push(new stdClass()); 51 | $this->assertTrue($added === false); 52 | $this->assertTrue($stack->size() === 2); 53 | 54 | $class = $stack->pop(); 55 | $this->assertTrue($class instanceof Exception); 56 | $this->assertTrue($stack->isEmpty() == false); 57 | 58 | $class = $stack->pop(); 59 | $this->assertTrue($class instanceof stdClass); 60 | $this->assertTrue($stack->isEmpty() == true); 61 | } 62 | 63 | /** 64 | * Queue class test 65 | */ 66 | public function testQueue(): void { 67 | $queue = new FixedQueue(2); 68 | $queue->enqueue(new stdClass()); 69 | $queue->enqueue(new Exception()); 70 | $this->assertTrue($queue->isEmpty() == false); 71 | $added = $queue->enqueue(new Exception()); 72 | $this->assertTrue($added === false); 73 | $this->assertTrue($queue->size() === 2); 74 | 75 | $class = $queue->dequeue(); 76 | $this->assertTrue($class instanceof stdClass); 77 | $this->assertTrue($queue->isEmpty() == false); 78 | 79 | $class = $queue->dequeue(); 80 | $this->assertTrue($class instanceof Exception); 81 | $this->assertTrue($queue->isEmpty() == true); 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /tests/StackQueue/StackSetTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\StackQueue; 28 | 29 | use doganoo\PHPAlgorithms\Common\Exception\IndexOutOfBoundsException; 30 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\StackSet; 31 | use PHPUnit\Framework\TestCase; 32 | 33 | /** 34 | * Class StackSetTest 35 | * 36 | * @package StackQueue 37 | */ 38 | class StackSetTest extends TestCase { 39 | 40 | /** 41 | * @throws IndexOutOfBoundsException 42 | */ 43 | public function testStackSet(): void { 44 | $stackSet = new StackSet(2); 45 | $stackSet->push("Hallo"); 46 | $stackSet->push("Hallo 2"); 47 | $this->assertTrue($stackSet->stackCount() === 1); 48 | $stackSet->push("Hallo 3"); 49 | $this->assertTrue($stackSet->stackCount() === 2); 50 | $element = $stackSet->pop(); 51 | $this->assertTrue($element === "Hallo 3"); 52 | $this->assertTrue($stackSet->stackCount() === 1); 53 | } 54 | 55 | /** 56 | * @throws IndexOutOfBoundsException 57 | */ 58 | public function testHugeStackSet(): void { 59 | $setSize = 1024; 60 | $factor = 4; 61 | $stackSet = new StackSet(1024); 62 | for ($i = 0; $i < $setSize * $factor; $i++) { 63 | $stackSet->push($i); 64 | } 65 | $this->assertTrue($stackSet->stackCount() === $factor); 66 | for ($i = 0; $i < $setSize + 1; $i++) { 67 | $stackSet->pop(); 68 | } 69 | $this->assertTrue($stackSet->stackCount() === 3); 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /tests/StackQueue/StackTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\StackQueue; 28 | 29 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\Queue; 30 | use doganoo\PHPAlgorithms\Datastructure\Stackqueue\Stack; 31 | use Exception; 32 | use PHPUnit\Framework\TestCase; 33 | use stdClass; 34 | 35 | /** 36 | * Class StackQueueTest class testing Stacks and Queues 37 | */ 38 | class StackTest extends TestCase { 39 | 40 | /** 41 | * Stack class test 42 | */ 43 | public function testStack(): void { 44 | $stack = new Stack(); 45 | $stack->push(new stdClass()); 46 | $stack->push(new Exception()); 47 | $this->assertTrue(false === $stack->isEmpty()); 48 | 49 | $class = $stack->pop(); 50 | $this->assertTrue($class instanceof Exception); 51 | $this->assertTrue($stack->isEmpty() == false); 52 | 53 | $class = $stack->pop(); 54 | $this->assertTrue($class instanceof stdClass); 55 | $this->assertTrue($stack->isEmpty() == true); 56 | } 57 | 58 | /** 59 | * Queue class test 60 | */ 61 | public function testQueue(): void { 62 | $queue = new Queue(); 63 | $queue->enqueue(new stdClass()); 64 | $queue->enqueue(new Exception()); 65 | $this->assertTrue($queue->isEmpty() === false); 66 | 67 | $class = $queue->dequeue(); 68 | $this->assertTrue($class instanceof stdClass); 69 | $this->assertTrue($queue->isEmpty() == false); 70 | 71 | $class = $queue->dequeue(); 72 | $this->assertTrue($class instanceof Exception); 73 | $this->assertTrue($queue->isEmpty() == true); 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /tests/Table/Entity/HashableObject.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Table\Entity; 28 | 29 | use doganoo\PHPAlgorithms\Common\Interfaces\IHashable; 30 | 31 | class HashableObject implements IHashable { 32 | 33 | private string $id; 34 | 35 | public function __construct(string $id) { 36 | $this->id = $id; 37 | } 38 | 39 | public function getHash(): string { 40 | return $this->id; 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /tests/Util/HashTableUtil.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Util; 28 | 29 | use doganoo\PHPAlgorithms\Datastructure\Lists\Node; 30 | use doganoo\PHPAlgorithms\Datastructure\Table\HashTable; 31 | 32 | /** 33 | * Class HashMapUtil - utility class for testing hash maps 34 | */ 35 | class HashTableUtil { 36 | 37 | /** 38 | * HashMapUtil constructor is private in order to ensure that the class is not instantiable. 39 | */ 40 | public function __construct() { 41 | } 42 | 43 | /** 44 | * creates a hash map with $number elements 45 | * 46 | * @param int $number 47 | * @return HashTable 48 | * @throws \doganoo\PHPAlgorithms\common\Exception\InvalidKeyTypeException 49 | * @throws \doganoo\PHPAlgorithms\common\Exception\UnsupportedKeyTypeException 50 | */ 51 | public static function getHashTable(int $number): HashTable { 52 | $hashMap = new HashTable(); 53 | for ($i = 0; $i < $number; $i++) { 54 | $node = new Node(); 55 | $node->setKey($i); 56 | $node->setValue(md5((string) $i)); 57 | $hashMap->addNode($node); 58 | } 59 | return $hashMap; 60 | } 61 | 62 | } -------------------------------------------------------------------------------- /tests/Util/TreeUtil.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Util; 28 | 29 | use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinarySearchTree; 30 | use doganoo\PHPAlgorithms\Datastructure\Graph\Tree\BinaryTree; 31 | 32 | /** 33 | * Class TreeUtil 34 | * 35 | * @package doganoo\PHPAlgorithms\common\Util 36 | */ 37 | class TreeUtil { 38 | 39 | /** 40 | * TreeUtil constructor. 41 | */ 42 | private function __construct() { 43 | } 44 | 45 | /** 46 | * @return BinarySearchTree 47 | */ 48 | public static function getBinarySearchTree(): BinarySearchTree { 49 | $bst = new BinarySearchTree(); 50 | $bst->insertValue(5); 51 | $bst->insertValue(2); 52 | $bst->insertValue(6); 53 | $bst->insertValue(1); 54 | return $bst; 55 | } 56 | 57 | /** 58 | * @return BinaryTree 59 | */ 60 | public static function getBinaryTree(): BinaryTree { 61 | $bt = new BinaryTree(); 62 | $bt->insertValue(5); 63 | $bt->insertValue(2); 64 | $bt->insertValue(6); 65 | $bt->insertValue(1); 66 | return $bt; 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /tests/Various/EnumTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Various; 28 | 29 | use doganoo\PHPAlgorithms\Common\Exception\NullNotAllowedException; 30 | use doganoo\PHPAlgorithms\Common\Exception\ValueNotAllowedException; 31 | use doganoo\PHPAlgorithms\Datastructure\Various\Enum; 32 | use PHPUnit\Framework\TestCase; 33 | 34 | /** 35 | * Class EnumTest 36 | * @package doganoo\PHPAlgorithmsTest\Various 37 | */ 38 | class EnumTest extends TestCase { 39 | 40 | /** 41 | * @throws NullNotAllowedException 42 | * @throws ValueNotAllowedException 43 | */ 44 | public function testEnum(): void { 45 | $enum = new Enum([ 46 | "1" 47 | , "2" 48 | ]); 49 | $assigned = false; 50 | 51 | $enum->setValue("2"); 52 | 53 | $this->assertTrue("2" === $enum->getValue()); 54 | 55 | try { 56 | $enum->setValue("5"); 57 | $assigned = true; 58 | } catch (NullNotAllowedException $e) { 59 | $assigned = false; 60 | } catch (ValueNotAllowedException $e) { 61 | $assigned = false; 62 | } 63 | 64 | $this->assertTrue(false === $assigned); 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /tests/Various/PermutationTest.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * Permission is hereby granted, free of charge, to any person obtaining a copy 9 | * of this software and associated documentation files (the "Software"), to deal 10 | * in the Software without restriction, including without limitation the rights 11 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | * copies of the Software, and to permit persons to whom the Software is 13 | * furnished to do so, subject to the following conditions: 14 | * 15 | * The above copyright notice and this permission notice shall be included in all 16 | * copies or substantial portions of the Software. 17 | * 18 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | * SOFTWARE. 25 | */ 26 | 27 | namespace doganoo\PHPAlgorithmsTest\Various; 28 | 29 | use doganoo\PHPAlgorithms\Algorithm\Various\Permutation; 30 | use PHPUnit\Framework\TestCase; 31 | 32 | class PermutationTest extends TestCase { 33 | 34 | 35 | public function testStringPermutation(): void { 36 | $permutation = new Permutation(); 37 | $permutations = $permutation->stringPermutations("abcd"); 38 | $this->assertTrue(24 === \count($permutations)); 39 | 40 | $permutations = $permutation->stringPermutations("abc"); 41 | $this->assertTrue(\in_array("cba", $permutations)); 42 | $this->assertTrue(\in_array("bac", $permutations)); 43 | $this->assertTrue(\in_array("acb", $permutations)); 44 | 45 | $permutations = $permutation->stringPermutations("a"); 46 | $this->assertTrue(1 === \count($permutations)); 47 | } 48 | 49 | public function testNumberPermutation(): void { 50 | $permutation = new Permutation(); 51 | $permutations = $permutation->numberPermutations(1234); 52 | $this->assertTrue(24 === \count($permutations)); 53 | 54 | $permutations = $permutation->numberPermutations(1234); 55 | $this->assertTrue(\in_array(4321, $permutations)); 56 | 57 | $permutations = $permutation->numberPermutations(1); 58 | $this->assertTrue(1 === \count($permutations)); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | php: 4 | - '7.1' --------------------------------------------------------------------------------