├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── custom.md │ └── feature_request.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README-EN.md ├── README.md ├── SECURITY.md ├── _config.yml ├── composer.json ├── docker-compose.yml ├── phpunit.xml ├── src ├── Features │ ├── SystemSwitch.php │ └── YieldExample.php ├── Other │ ├── AntsClimb.php │ ├── BidirectionalQueue.php │ ├── BigSmallReplace.php │ ├── CartesianProduct.php │ ├── ColorBricks.php │ ├── DynamicProgramming.php │ ├── ElevatorDispatch.php │ ├── Encryption.php │ ├── Factorial.php │ ├── Fibonacci.php │ ├── GetCattle.php │ ├── HanoiGames.php │ ├── HashTable.php │ ├── Interval.php │ ├── Judge.php │ ├── Knapsack.php │ ├── Maze.php │ ├── MonkeyKing.php │ ├── NQueen.php │ ├── OnlyNumbers.php │ ├── PointInTriangle.php │ ├── PokerGames.php │ ├── Prim.php │ ├── Rectangle.php │ ├── RotateSort.php │ ├── RotationSort.php │ ├── Solution.php │ ├── Square.php │ └── StealingApples.php ├── Query │ ├── BFSQuery.php │ ├── BinaryQuery.php │ ├── DijkstraQuery.php │ ├── FibonacciQuery.php │ ├── InsertQuery.php │ ├── Kmp.php │ └── QuickQuery.php ├── Sort │ ├── BubbleSort.php │ ├── ChineseTextNumberSort.php │ ├── HeapSort.php │ ├── InsertSort.php │ ├── MergeSort.php │ ├── QuickSort.php │ ├── SelectSort.php │ ├── ShellSort.php │ └── ShuttleSort.php └── Structure │ ├── BinarySearchTree.php │ ├── KitchenQueue.php │ ├── LinearChain.php │ ├── LinearOrder.php │ └── StackExample.php └── tests ├── BootStrapTest.php └── Sort ├── ChineseTextNumberExtractTest.php ├── ChineseTextNumberSortModelTest.php └── ChineseTextNumberSortTest.php /.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 | .DS_Store 3 | composer.lock 4 | vendor -------------------------------------------------------------------------------- /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 542684913@qq.com. 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 | What does “open source” mean? 2 | 3 | When a project is open source, that means anybody can view, use, modify, and distribute your project for any purpose. These permissions are enforced through an open source license. 4 | 5 | Open source is powerful because it lowers the barriers to adoption, allowing ideas to spread quickly. 6 | 7 | To understand how it works, imagine your friend is having a potluck, and you bring a cherry pie. 8 | 9 | Everybody tries the pie (use) 10 | The pie is a hit! They ask you for the recipe, which you provide (view) 11 | One friend, Alex, who’s a pastry chef, suggests reducing the sugar (modify) 12 | Another friend, Lisa, asks to use it for a dinner next week (distribute) 13 | By comparison, a closed source process would be going to a restaurant and ordering a slice of cherry pie. You must pay a fee to eat the pie, and the restaurant probably won’t give you their recipe. If you copied their pie exactly and sold it under your own name, the restaurant could take action against you. 14 | 15 | Why do people open source their work? 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Shaowei pu 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 | -------------------------------------------------------------------------------- /README-EN.md: -------------------------------------------------------------------------------- 1 | ​

:whale:A collection of algorithms that are implemented in PHP:whale:

2 | 3 |

4 | 5 | php 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |

20 | 21 |

中文版 

22 | 23 | ## Simple structure, 24 | 25 | ``` 26 | ├──Package 27 | │ ├── Sort 28 | │ │ ├── BubbleSort.php 29 | │ │ ├── QuickSort.php 30 | │ │ ├── ShellSort.php 31 | │ │ ├── MergeSort.php 32 | │ │ ├── InsertSort.php 33 | │ │ └── SelectSort.php 34 | │ │ 35 | │ ├── Query 查找篇 36 | │ │ ├── BinaryQuery.php 37 | │ │ ├── InseertQuery.php 38 | │ │ ├── FibonacciQuery.php 39 | │ │ ├── BFSQuery.php 40 | │ │ ├── Kmp.php 41 | │ │ ├── DijkstraQuery.php 42 | │ │ └── QulickQuery.php 43 | │ │ 44 | │ └── Other 其他 45 | │ ├── MonkeyKing.php 46 | │ ├── DynamicProgramming.php 47 | │ ├── Fibonacci.php 48 | │ ├── StealingApples.php 49 | │ ├── HanoiGames.php 50 | │ ├── BidirectionalQueue.php 51 | │ ├── ColorBricks.php 52 | │ ├── GetCattle.php 53 | │ ├── OnlyNumbers.php 54 | │ ├── Interval.php 55 | │ ├── Maze.php 56 | │ ├── AntsClimb.php 57 | │ ├── Encryption.php 58 | │ ├── ElevatorDispatch.php 59 | │ ├── kmp.php 60 | │ ├── TraversalOfBinary.php 61 | │ ├── PointInTriangle.php 62 | │ └── BigSmallReplace.php 63 | │ └── Knapsack.php 64 | │ └── Solution.php 65 | │ └── RotationSort.php 66 | │ └── Square.php 67 | │ └── Prim.php 68 | │ └── CartesianProduct.php 69 | │ └── Square.php 70 | │ └── Judge.php 71 | │ └── Factorial.php 72 | | └── HashTable.php 73 | | └── RotateSort.php 74 | │ 75 | ├──LICENSE 76 | └──README.md 77 | ``` 78 | 79 | ## What to do? 80 | 81 | ``` 82 | To record their understanding algorithms, data structure, the process of simple comprehensive and detailed as possible, let the learning algorithm using flexible, refueling(ง •̀_•́)ง 83 | ``` 84 | 85 | ## logarithmic 86 | 87 | log10100 It's equivalent to saying, "how many tens do you multiply?" the answer is, of course, two 88 | so log10100=2,The logarithmic operation is the inverse of the power operation 89 | 90 | | left | right | 91 | | ------------------ | --------------------- | 92 | | 23 = 8 | log28 = 3 | 93 | | 24 = 16 | log216 = 4 | 94 | | 25 = 32 | log232 = 5 | 95 | 96 | If you don't, we won't wait for you 97 | 98 | ## The elapsed time 99 | 100 | Take binary search for example, how much time can you save by using it? Simply look for the Numbers and if the list contains 100 Numbers, you need to guess 100 times. 101 | In other words, the number of guesses is the same as the length of the list, which is called linear time, while binary search is different if the list contains 100 elements 102 | It takes up to seven times, and if the list contains four billion digits, it should be guessed 32 times, while the running time of the subsearch is logarithmic time `O(log)` 103 | 104 | ## Big O notation 105 | 106 | The big O notation is a special representation of how fast the algorithm can be. There's a diaosi. In fact, you often have to copy other people's code. 107 | In this case, you know how fast these algorithms are 108 | 109 | - The running time of the algorithm increases at different speeds 110 | - For example, the difference between a simple find and a binary search 111 | 112 | | element | Easy to find | Binary search | 113 | | ------------- | ------------ | ------------- | 114 | | 100 | 100ms | 7ms | 115 | | 10000 | 10s | 14ms | 116 | | 1 000 000 000 | 11day | 30ms | 117 | 118 | - ` O ` said hair is pointed out that how fast algorithms, such as list contains ` n ` element, a simple search need to check each element, so you need to perform ` n ` time operations 119 | Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` 120 | - Some common big O runtime 121 | - O(log n) ,It's also called log time, and this algorithm includes binary algorithms 122 | - O(n),Also known as linear time, this algorithm includes simple lookups. 123 | - O(n * log n) Quick sort 124 | - O(n2),Selection sort 125 | - O(n!) Factorial time 126 | - Here is the point 127 | - The speed of the algorithm is not the time, but the growth of operands 128 | - When we talk about the speed of the algorithm, what we're talking about is how fast will it run as the input increases 129 | - The running time of the algorithm is expressed in large O notation 130 | - O(log n) is faster than O (n), and the more elements that need to be searched, the more the former is faster than the latter 131 | 132 | ## A simple comparison of recursion and loops: 133 | 134 | 1. From a procedural point of view, the recursion manifests itself as calling itself, and the loop does not have this form. 135 | 2. Recursive proceed from the ultimate goal of the problem, and gradually to a complex problem into a simple problem, and simple question solution and complicated problem, at the same time the presence of the benchmark, can eventually get a problem, is the reverse. And the circulation is from the simple question, step by step forward development, finally get the question, is positive. 136 | 3. Any cycle can be represented by recursion, but it is necessary to use the loop to achieve recursion (except for one-way recursion and tail recursion), and the stack structure must be introduced to stack the stack. 137 | 4.In general, non-recursive efficiency is higher than recursion. And recursive function calls are expensive and recursive times are limited by stack size. 138 | 139 | ## Progressive learning 140 | 141 | 1. Fork 我的项目并提交你的 `idea` 142 | 2. Pull Request 143 | 3. Merge 144 | 145 | ## 纠错 146 | 147 | If you find something wrong, you can initiate a [issue](https://github.com/PuShaoWei/designPatterns-go/issues)or [pull request](https://github.com/PuShaoWei/designPatterns-go/pulls),I will correct it in time 148 | 149 | > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) 150 | 151 | ## Contributors 152 | 153 | Thanks for the issue or pull request of the following friends: 154 | 155 | - [hailwood ](https://github.com/hailwood) 156 | 157 | - [zhangxuanru](https://github.com/zhangxuanru) 158 | 159 | - [ifreesec](https://github.com/ifreesec) 160 | 161 | - [openset](https://github.com/openset) 162 | 163 | - [Neroxiezi](https://github.com/Neroxiezi) 164 | 165 | ## License 166 | 167 | MIT 168 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ​

:whale: 用 PHP 的方式实现的各类算法合集 :whale:

2 | 3 |

4 | 5 | php 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |

20 | 21 |

English 

22 | 23 | > 每周最少一更,求出题,求虐待 At least once a week, ask for problems and abuse 24 | 25 | ## 简易结构 26 | 27 | ``` 28 | ├──Package 29 | │ ├── Sort 排序篇 30 | │ │ ├── BubbleSort.php 冒泡排序 31 | │ │ ├── HeapSort.php 堆排序 大根堆 32 | │ │ ├── MBaseSort.php 基数排序 MSD 33 | │ │ ├── LBaseSort.php 基数排序 LSD 34 | │ │ ├── QuickSort.php 快速排序 35 | │ │ ├── ShuttleSort.php 飞梭排序 36 | │ │ ├── ShellSort.php 希尔排序 37 | │ │ ├── MergeSort.php 归并排序 38 | │ │ ├── InsertSort.php 插入排序 39 | │ │ └── SelectSort.php 选择排序 40 | │ │ 41 | │ ├── Query 查找篇 42 | │ │ ├── BinaryQuery.php 二分查找 43 | │ │ ├── InseertQuery.php 插入查找 44 | │ │ ├── FibonacciQuery.php 斐波那契查找 45 | │ │ ├── BFSQuery.php 广度优先查找 46 | │ ├── Kmp.php 算法导论-KMP算法 47 | │ ├── DijkstraQuery.php 迪克斯特拉算法 48 | │ │ └── QulickQuery.php 快速查找 49 | │ │ 50 | │ ├── Structure 数据结构 51 | │ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) 52 | │ │ ├── LinearChain.php 线性表 单链存储 53 | │ │ └── LinearOrder.php 线性表 顺序存储 54 | │ │ └── BinarySearchTree.php 二叉搜索树 55 | │ │ 56 | │ ├── Tools 小工具集 57 | │ │ └── SystemSwitch.php 堆栈实现进制转换 58 | │ │ 59 | │ └── Other 其他 60 | │ ├── MonkeyKing.php 约瑟夫环 61 | │ ├── DynamicProgramming.php 动态规划 62 | │ ├── Fibonacci.php 斐波那契数列 63 | │ ├── StealingApples.php 偷苹果求余 64 | │ ├── HanoiGames.php 汉诺塔游戏 65 | │ ├── BidirectionalQueue.php 双向队列 66 | │ ├── ColorBricks.php 彩色砖块 67 | │ ├── GetCattle.php 牛年求牛 68 | │ ├── OnlyNumbers.php 求唯一数 69 | │ ├── PokerGames.php 洗扑克牌 70 | │ ├── Interval.php 抽奖区间算法 71 | │ ├── Maze.php 迷宫寻址算法 72 | │ ├── AntsClimb.php 蚂蚁爬杆算法 73 | │ ├── Encryption.php 对称加密算法 74 | │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 75 | │ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 76 | │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 77 | │ ├── Knapsack.php 贪心算法之背包问题实现 78 | │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow 79 | │ └── Solution.php Facebook面试题之岛屿周长算法 80 | │ └── RotationSort.php Facebook面试题之顺时针回旋算法 81 | │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 82 | │ └── Prim.php Prim算法(最小生成树算法) 83 | │ └── CartesianProduct.php 笛卡尔积算法 84 | │ └── Square.php 面试题之平面任意四点能否组成一个矩形 85 | │ └── Judge.php 面试题之扑克牌中任选五张判断是不是顺子 86 | │ └── Factorial.php 面试题之N的阶乘末尾有多少个0 87 | | └── HashTable.php HashTable 88 | | └── RotateSort.php 面试题之风车旋转排序算法 89 | │ 90 | ├──LICENSE 91 | └──README.md 92 | ``` 93 | 94 | ## 要做什么? 95 | 96 | ``` 97 | 记录自己理解算法,数据结构的过程,尽可能的简单全面以及详细,让算法学习运用灵活自如,加油(ง •̀_•́)ง 98 | ``` 99 | 100 | ## 当然 101 | 102 | ``` 103 | 用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这决不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 104 | ``` 105 | 106 | ## 什么是算法? 107 | 108 | 直白地说,算法就是任何明确定义的计算过程,它接收一些值或集合作为输入,并产生一些值或集合作为输出。这样,算法就是将输入转换为输出的一系列计算过程。来源:Thomas H. Cormen, Chales E. Leiserson (2009), 《算法导论第三版》。 109 | 110 | 简而言之,我们可以说算法就是用来解决一个特定任务的一系列步骤(是的,不止计算机在使用算法,人类也同样如此)。目前,一个有效的算法应该含有三个重要特性: 111 | 112 | - 它必须是有限的:如果你设计的算法永无休止地尝试解决问题,那么它是无用的。 113 | - 它必须具备明确定义的指令:算法的每一步都必须准确定义,在任何场景下指令都应当没有歧义。 114 | - 它必须是有效的:一个算法被设计用以解决某个问题,那么它就应当能解决这个问题,并且仅仅使用纸和笔就能证明该算法是收敛的。 115 | 116 | ## 对数 117 | 118 | log10100 相当于问"将多少个10相乘的结果为100",答案当然是2个了 119 | 因此log10100=2,即对数运算是幂运算的逆运算 120 | 121 | | left | right | 122 | | ------------------ | --------------------- | 123 | | 23 = 8 | log28 = 3 | 124 | | 24 = 16 | log216 = 4 | 125 | | 25 = 32 | log232 = 5 | 126 | 127 | ## 运行时间 128 | 129 | 以二分查找为例,使用它可节省多少时间呢?简单查找逐个地检查数字,如果列表包含100个数字,最多需要猜100次。 130 | 换而言之最多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 131 | 最多需要7次,如果列表包含40亿个数字,最多需猜32次,而分查找的运行时间为对数时间 `O(log)` 132 | 133 | ## 大O表示法 134 | 135 | 大O表示法是一种特殊的表示法 ,指出了算法的速度有多快。有个屌用啊,实际上,你经常要去复制别人的代码。 136 | 在这种情况下,知道这些算法的速度有快有慢 137 | 138 | - 算法的运行时间以不同的速度增加 139 | - 例如简单查找与二分查找的区别 140 | 141 | | 元素 | 简单查找 | 二分查找 | 142 | | ----------------- | ----- | ---- | 143 | | 100个元素 | 100ms | 7ms | 144 | | 10000个元素 | 10s | 14ms | 145 | | 1 000 000 000 个元素 | 11天 | 30ms | 146 | 147 | - 大`O`表示法指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 148 | 使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` 149 | - 一些常见的大O运行时间 150 | - O(log n) ,也叫对数时间,这样的算法包括二分算法 151 | - O(n),也叫线性时间,这样的算法包括简单查找。 152 | - O(n * log n) 快速排序 153 | - O(n2),选择排序 154 | - O(n!) 即阶乘时间 155 | - 这里是重点 156 | - 算法的速度指的并非时间,而是操作数的增速 157 | - 谈论算法的速度时间时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加 158 | - 算法的运行时间用大O表示法表示 159 | - O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 160 | 161 | ## 编写解决实际问题的程序过程 162 | 163 | - 如何用数据形式描述问题,即将问题抽象为一个数学模型 164 | - 问题所涉及到的数据量的大小及数据之间的关系 165 | - 如何在计算机中储存数据及体现数据之间的关系 166 | - 处理数据时需要对数据执行的操作 167 | - 编写的程序的性能是否良好 168 | 169 | ## 数据(Data) 170 | 171 | - 是客观事物的符号表示,在计算机科学中指的是所有能输入到计算机中并被计算机程序处理的符号的总称。 172 | - 数据元素(Data Element) :是数据的基本单位,在程序中通常作为一个整体来进行考虑和处理。一个数据元素可由若干个数据项(Data Item)组成。 173 | - 数据项(Data Item) : 是数据的不可分割的最小单位。数据项是对客观事物某一方面特性的数据描述。 174 | - 数据对象(Data Object) :是性质相同的数据元素的集合,是数据的一个子集。如字符集合C={‘A’,’B’,’C,…} 。 175 | - 数据结构 :相互之间具有一定联系的数据元素的集合。 176 | - 数据的逻辑结构 : 数据元素之间的相互关系称为逻辑结构。 177 | - 数据操作 : 对数据要进行的运算 178 | - 数据类型(Data Type):指的是一个值的集合和定义在该值集上的一组操作的总称。 179 | 180 | ## 数据的逻辑结构有四种基本类型 181 | 182 | - 集合:结构中数据元素之间除了“属于同一个集合"外,再也没有其他的关系 183 | - 线性结构:结构中的数据元素存在一对一的关系 184 | - 树形结构:结构中的数据元素存在一对多的关系 185 | - 网状或者图状结构:结构中的数据元素存在多对多的关系 186 | 187 | ## 数据结构的储存方式 188 | 189 | 由数据元素之间的关系在计算机中有两种不同的表示方法——顺序表示和非顺序表示,从则导出两种储存方式,顺序储存结构和链式储存结构 190 | 191 | - 顺序存储结构:用数据元素在存储器中的相对位置来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是连续的 192 | - 链式存储结构:在每一个数据元素中增加一个存放另一个元素地址的指针(pointer),用该指针来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是否连续没有要求 193 | 194 | 数据的逻辑结构和物理结构是密不可分的两个方面,一个算法的设计取决于所选定的逻辑结构,而算法的实现依赖于所采用的存储结构 195 | 196 | ## 算法(Algorithm) 197 | 198 | 是对特定问题求解方法(步骤)的一种描述,是指令的有限序列,其中每一条指令表示一个或多个操作。 199 | 200 | > 算法具有以下五个特性 201 | 202 | - 有穷性: 一个算法必须总是在执行有穷步之后结束,且每一步都在有穷时间内完成 203 | - 确定性:算法中每一条指令必须有确切的含义,不存在二义性,且算法只有一个入口和一个出口 204 | - 可行性: 一个算法是能行的,即算法描述的操作都可以通过已经实现的基本运算执行有限次来实现 205 | - 输入: 一个算法有零个或多个输入,这些输入取自于某个特定的对象集合 206 | - 输出: 一个算法有一个或多个输出,这些输出是同输入有着某些特定关系的量 207 | 208 | > 算法和程序是两个不同的概念 209 | 210 | 一个计算机程序是对一个算法使用某种程序设计语言的具体实现。算法必须可终止意味着不是所有的计算机程序都是算法。 211 | 212 | > 评价一个好的算法有以下几个标准 213 | 214 | - 正确性(Correctness ): 算法应满足具体问题的需 215 | - 可读性(Readability): 算法应容易供人阅读和交流,可读性好的算法有助于对算法的理解和修改 216 | - 健壮性(Robustness): 算法应具有容错处理,当输入非法或错误数据时,算法应能适当地作出反应或进行处理,而不会产生莫名其妙的输出结果 217 | - 通用性(Generality): 算法应具有一般性 ,即算法的处理结果对于一般的数据集合都成立 218 | 219 | > 效率与存储量需求: 效率指的是算法执行的时间;存储量需求指算法执行过程中所需要的最大存储空间,一般地,这两者与问题的规模有关 220 | 221 | ## 算法的时间复杂度 222 | 223 | 算法中基本操作重复执行的次数是问题规模n的某个函数,其时间量度记作T(n)=O(f(n)),称作算法的渐近时间复杂度(Asymptotic Time complexity),简称时间复杂度 224 | 225 | ## 算法的空间复杂度 226 | 227 | 是指算法编写成程序后,在计算机中运行时所需存储空间大小的度量,记作:S(n)=O(f(n)),其中n为问题规模 228 | 229 | ## 递归和循环的简单比较: 230 | 231 | 1. 从程序上看,递归表现为自己调用自己,循环则没有这样的形式。 232 | 2. 递归是从问题的最终目标出发,逐渐将复杂问题化为简单问题,并且简单的问题的解决思路和复杂问题一样,同时存在基准情况,就能最终求得问题,是逆向的。而循环是从简单问题出发,一步步的向前发展,最终求得问题,是正向的。 233 | 3. 任意循环都是可以用递归来表示的,但是想用循环来实现递归(除了单向递归和尾递归),都必须引入栈结构进行压栈出栈。 234 | 4. 一般来说,非递归的效率高于递归。而且递归函数调用是有开销的,递归的次数受堆栈大小的限制。 235 | 236 | ## 一起进步学习 237 | 238 | 1. Fork 我的项目并提交你的 `idea` 239 | 2. Pull Request 240 | 3. Merge 241 | 242 | ## 纠错 243 | 244 | 如果大家发现有什么不对的地方,可以发起一个[issue](https://github.com/PuShaoWei/arithmetic-php/issues)或者[pull request](https://github.com/PuShaoWei/arithmetic-php/pulls),我会及时纠正 245 | 246 | > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) 247 | 248 | ## 致谢 249 | 250 | 感谢以下朋友的issue或pull request: 251 | 252 | - [hailwood ](https://github.com/hailwood) 253 | 254 | - [zhangxuanru](https://github.com/zhangxuanru) 255 | 256 | - [ifreesec](https://github.com/ifreesec) 257 | 258 | - [openset](https://github.com/openset) 259 | 260 | - [Neroxiezi](https://github.com/Neroxiezi) 261 | 262 | ## License 263 | 264 | MIT 265 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Please report security issues to 18 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algorithm-php", 3 | "description": "algorithm-php", 4 | "minimum-stability": "stable", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "pushaowei" 9 | } 10 | ], 11 | "require-dev": { 12 | "phpunit/phpunit": "~6.0", 13 | "mockery/mockery": "~0.9" 14 | }, 15 | "autoload": { 16 | "classmap": [ 17 | "./src" 18 | ] 19 | }, 20 | "autoload-dev": { 21 | "classmap": [ 22 | "tests/" 23 | ] 24 | }, 25 | "prefer-stable": true, 26 | "config": { 27 | "optimize-autoloader": true 28 | }, 29 | "repositories": { 30 | "packagist": { 31 | "type": "composer", 32 | "url": "https://packagist.phpcomposer.com" 33 | } 34 | }, 35 | "require": { 36 | "ext-json": "*", 37 | "ext-ctype": "*", 38 | "ext-openssl": "*", 39 | "php": ">=5.6.4", 40 | "ext-curl": "*", 41 | "stojg/recommend": "^1.0", 42 | "ext-iconv": "*" 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2.0' 2 | services: 3 | php71-dev: 4 | image: "m9rco/php:7.1-dev" 5 | ports: 6 | - "2222:22" 7 | - "29000:9000" 8 | volumes: 9 | - $PWD:/app:rw -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ./tests 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Features/SystemSwitch.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/10/16 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 十进制整数转换为二、八、十六进制整数 n = (n div d) * d + n mod d 11 | * ------------------------------------------------------------- 12 | */ 13 | class SystemSwitch 14 | { 15 | /** 16 | * @var array 17 | */ 18 | protected $systemGather; 19 | 20 | /** 21 | * @var int 22 | */ 23 | protected $input; 24 | 25 | /** 26 | * @var mixed 27 | */ 28 | protected $output; 29 | 30 | /** 31 | * SystemSwitch constructor. 32 | * 33 | * @param $input 34 | * @param $output 35 | */ 36 | public function __construct($input, $output) 37 | { 38 | $this->systemGather = array (2, 8, 16); 39 | $this->input = $input; 40 | $this->output = $output; 41 | } 42 | 43 | public function run() 44 | { 45 | $before = $this->input; 46 | $stack = new StackExample(); 47 | while ($this->input != 0) { 48 | $mod = $this->input % $this->output; 49 | $stack->setPushStack($mod); 50 | $this->input = (int)($this->input - $mod) / $this->output; 51 | } 52 | $output = ''; 53 | if ($this->output == 16) { 54 | $output .= '0x'; 55 | } else if ($this->output == 8) { 56 | $output .= '0'; 57 | } 58 | 59 | foreach ($stack->getAllPopStack() as $value) { 60 | if ($this->output == 16) { 61 | switch ($value) { 62 | case 10: 63 | $value = 'A'; 64 | break; 65 | case 11: 66 | $value = 'B'; 67 | break; 68 | case 12: 69 | $value = 'C'; 70 | break; 71 | case 13: 72 | $value = 'D'; 73 | break; 74 | case 14: 75 | $value = 'E'; 76 | break; 77 | case 15: 78 | $value = 'F'; 79 | break; 80 | } 81 | } 82 | $output .= $value; 83 | } 84 | // 因为输出语句会自动将整型的数转换为10进制输出 85 | // 也即如果转换后的结果为0xff,直接将0xff输出会得到255,所以返回一数组 86 | return array ( 87 | 'before' => $before, // 转换之前 88 | 'after' => intval($output, $this->output), // 转换后的整型数(整型) 89 | 'string' => $output // 转换后的整型数的字符串表示(字符串型) 90 | ); 91 | } 92 | } 93 | 94 | // load the stack 95 | define("DS", DIRECTORY_SEPARATOR); 96 | require_once dirname(__DIR__) . DS . 'Structure' . DS . 'StackExample.php'; 97 | $systemObj = new SystemSwitch(6, 16); 98 | $result = $systemObj->run(); 99 | var_dump($result); -------------------------------------------------------------------------------- /src/Other/AntsClimb.php: -------------------------------------------------------------------------------- 1 | 6 | * @date 2018/1/11 7 | * @license MIT 8 | * ------------------------------------------------------------- 9 | * 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。 10 | * 木杆很细,不能同时通过一只蚂蚁。开始 时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头, 11 | * 但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。 12 | * ------------------------------------------------------------- 13 | * 编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间 14 | */ 15 | 16 | // +-------------------------------------------------------------------------- 17 | // | 解题方式 18 | // +-------------------------------------------------------------------------- 19 | 20 | class AntsClimb 21 | { 22 | /** 23 | * @var array 蚂蚁位置集合 24 | */ 25 | protected $position; 26 | 27 | /** 28 | * AntsClimb constructor. 29 | * 30 | * @param array $position 31 | */ 32 | public function __construct(array $position) 33 | { 34 | $this->position = $position; 35 | } 36 | 37 | /** 38 | * run 39 | * 40 | * @return void 41 | */ 42 | public function run() 43 | { 44 | $pathCalculate = $this->path($this->position); 45 | echo '

计算-';
 46 |         print_r($pathCalculate);
 47 |         echo '排序-';
 48 |         asort($pathCalculate);
 49 |         print_r($pathCalculate);
 50 |     }
 51 | 
 52 |     /**
 53 |      * add2
 54 |      *
 55 |      * @param $directionArr
 56 |      * @param $count
 57 |      * @param $i
 58 |      * @return mixed
 59 |      */
 60 |     protected function add2($directionArr, $count, $i)
 61 |     {
 62 |         if (0 > $i) {
 63 |             return $directionArr;
 64 |         }
 65 |         if (0 === $directionArr[$i]) {
 66 |             $directionArr[$i] = 1;
 67 |             return $directionArr;
 68 |         }
 69 |         $directionArr[$i] = 0;
 70 |         return $this->add2($directionArr, $count, $i - 1);
 71 |     }
 72 | 
 73 |     /**
 74 |      * path
 75 |      *
 76 |      * @param $positionArr
 77 |      * @return array
 78 |      */
 79 |     protected function path($positionArr)
 80 |     {
 81 |         // 生成测试路径
 82 |         $pathCalculate = array ();
 83 |         $count         = count($positionArr);
 84 |         $directionArr  = array_fill(0, $count, 0);
 85 | 
 86 |         // 朝向
 87 |         $end = str_repeat('1', $count);
 88 |         while (true) {
 89 |             $path                         = implode('', $directionArr);
 90 |             $total                        = $this->calculate($positionArr, $directionArr);
 91 |             $pathCalculate['路径:' . $path] = $total;
 92 |             if ($end == $path) { // 遍历完成
 93 |                 break;
 94 |             }
 95 |             $directionArr = $this->add2($directionArr, $count, $count - 1);
 96 |         }
 97 |         return $pathCalculate;
 98 |     }
 99 | 
100 |     /**
101 |      * calculate
102 |      *
103 |      * @param $positionArr
104 |      * @param $directionArr
105 |      * @return int
106 |      */
107 |     protected function calculate($positionArr, $directionArr)
108 |     {
109 |         $total = 0;
110 |         // 总用时
111 |         $length = 27;
112 |         // 木杆长度
113 |         while ($positionArr) {
114 |             $total++; // 步增耗时
115 |             $nextArr = array (); // 下一步位置
116 |             foreach ($positionArr as $key => $value) {
117 |                 if (0 == $directionArr[$key]) {
118 |                     $next = $value - 1; // 向0方向走一步
119 |                 } else {
120 |                     $next = $value + 1; // 向1方向走一步
121 |                 }
122 |                 if (0 == $next) { // 在0方向走出
123 |                     continue;
124 |                 }
125 |                 if ($length == $next) { // 在1方向走出
126 |                     continue;
127 |                 }
128 |                 $nextArr[$key] = $next;
129 |             }
130 |             $positionArr = $nextArr;// 将$positionArr置为临时被查找数组
131 | 
132 |             foreach ($nextArr as $key => $value) {
133 |                 $findArr = array_keys($positionArr, $value);
134 |                 if (count($findArr) < 2) {
135 |                     // 没有重合的位置
136 |                     continue;
137 |                 }
138 |                 foreach ($findArr as $findIndex) {
139 |                     $directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1;
140 |                     // 反向处理
141 |                     unset($positionArr[$findIndex]);
142 |                     // 防止重复查找计算
143 |                 }
144 |             }
145 |             $positionArr = $nextArr;
146 |             // 将$positionArr置为下一步结果数组
147 |         }
148 |         return $total;
149 |     }
150 | }
151 | 
152 | // +--------------------------------------------------------------------------
153 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
154 | // +--------------------------------------------------------------------------
155 | 
156 | // 蚂蚁位置
157 | $position = array (3, 7, 11, 17, 23);
158 | // 测试用例
159 | (new AntsClimb($position))->run();


--------------------------------------------------------------------------------
/src/Other/BidirectionalQueue.php:
--------------------------------------------------------------------------------
  1 | 
  7 |  * @date     2018/1/11
  8 |  * @license  MIT
  9 |  * -------------------------------------------------------------
 10 |  * 双向队列的实现及应用
 11 |  * -------------------------------------------------------------
 12 |  * 思路分析: 考察PHP几个内置数组的函数
 13 |  * 双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素
 14 |  */
 15 | 
 16 | // +--------------------------------------------------------------------------
 17 | // | 解题方式    | 这儿,可能有用的解决方案
 18 | // +--------------------------------------------------------------------------
 19 | 
 20 | class BidirectionalQueue
 21 | {
 22 |     /**
 23 |      * @var array
 24 |      */
 25 |     public $queue     = [];
 26 |     public $maxLength = 0;  // 对列最大长度,0表示不限
 27 |     public $type      = 0;  // 对列类型
 28 |     public $frontNum  = 0;  // 前端插入的数量
 29 |     public $rearNum   = 0;  // 后端插入的数量
 30 | 
 31 |     const C_AT_BOTH_ENDS        = 1;   // 1:两端均可输入输出
 32 |     const C_FRONT_ONLY_INPUT    = 2;   // 2:前端只能输入,后端可输入输出
 33 |     const C_FRONT_ONLY_OUTPUT   = 3;   // 3:前端只能输出,后端可输入输出
 34 |     const C_BACK_ONLY_INPUT     = 4;   // 4:后端只能输入,前端可输入输出
 35 |     const C_BACK_ONLY_OUTPUT    = 5;   // 5:后端只能输出,前端可输入输出
 36 |     const C_BOTH_WAY_ONLY_INPUT = 6;   // 6:两端均可输入输出,在哪端输入只能从哪端输出
 37 | 
 38 |     /**
 39 |      * BidirectionalQueue 初始化.
 40 |      *
 41 |      * @param int $type
 42 |      * @param int $maxLength
 43 |      */
 44 |     public function __construct($type = self::C_AT_BOTH_ENDS, $maxLength = 0)
 45 |     {
 46 |         var_dump($this->getConfig());
 47 |         $this->_type      = in_array($type, [1, 2, 3, 4, 5, 6]) ? $type : self::C_AT_BOTH_ENDS;
 48 |         $this->_maxLength = intval($maxLength);
 49 |     }
 50 | 
 51 |     /**
 52 |      * addFirst   前端入列
 53 |      *
 54 |      * @param $item
 55 |      * @return int
 56 |      */
 57 |     public function addFirst($item)
 58 |     {
 59 |         return array_unshift($this->queue, $item);
 60 |     }
 61 | 
 62 |     /**
 63 |      * addLast 尾部入列
 64 |      *
 65 |      * @param $item
 66 |      * @return int
 67 |      */
 68 |     public function addLast($item)
 69 |     {
 70 |         return array_push($this->queue, $item);
 71 |     }
 72 | 
 73 |     /**
 74 |      * removeFirst 头部出列
 75 |      *
 76 |      * @return mixed
 77 |      */
 78 |     public function removeFirst()
 79 |     {
 80 |         return array_shift($this->queue);
 81 |     }
 82 | 
 83 |     /**
 84 |      * removeLast 尾部出列
 85 |      *
 86 |      * @return mixed
 87 |      */
 88 |     public function removeLast()
 89 |     {
 90 |         return array_pop($this->queue);
 91 |     }
 92 | 
 93 |     /**
 94 |      * 清空队列
 95 |      */
 96 |     public function makeEmpty()
 97 |     {
 98 |         unset($this->queue);
 99 |     }
100 | 
101 |     /**
102 |      * 获取列头
103 |      *
104 |      * @return mixed
105 |      */
106 |     public function getFirst()
107 |     {
108 |         return reset($this->queue);
109 |     }
110 | 
111 |     /**
112 |      * 获取列尾
113 |      *
114 |      * @return mixed
115 |      */
116 |     public function getLast()
117 |     {
118 |         return end($this->queue);
119 |     }
120 | 
121 |     /**
122 |      * 获取长度
123 |      *
124 |      * @return int
125 |      */
126 |     public function getLength()
127 |     {
128 |         return count($this->queue);
129 |     }
130 | 
131 |     /**
132 |      * 获取配置常量
133 |      */
134 |     protected function getConfig()
135 |     {
136 |         return [
137 |             self::C_AT_BOTH_ENDS,          // 1:两端均可输入输出
138 |             self::C_FRONT_ONLY_INPUT,      // 2:前端只能输入,后端可输入输出
139 |             self::C_FRONT_ONLY_OUTPUT,     // 3:前端只能输出,后端可输入输出
140 |             self::C_BACK_ONLY_INPUT,       // 4:后端只能输入,前端可输入输出
141 |             self::C_BACK_ONLY_OUTPUT,      // 5:后端只能输出,前端可输入输出
142 |             self::C_BOTH_WAY_ONLY_INPUT,   // 6:两端均可输入输出,在哪端输入只能从哪端输出
143 |         ];
144 |     }
145 | }
146 | 
147 | // +--------------------------------------------------------------------------
148 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
149 | // +--------------------------------------------------------------------------
150 | 
151 | 
152 | new BidirectionalQueue();


--------------------------------------------------------------------------------
/src/Other/BigSmallReplace.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2018/1/11
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * Hello World 输出 Olleh Dlrow
11 |  * -------------------------------------------------------------
12 |  * SWAT 输出 TAWS
13 |  * I am A sTudent 输出 I ma A tNeduts
14 |  */
15 | 
16 | // +--------------------------------------------------------------------------
17 | // | 解题方式    | 这儿,可能有用的解决方案
18 | // +--------------------------------------------------------------------------
19 | 
20 | /**
21 |  * BigSmallReplace
22 |  *
23 |  * @param $str
24 |  * @return string
25 |  */
26 | function BigSmallReplace($str)
27 | {
28 |     // Cutting words
29 |     $first  = preg_split("/[\s]+/", $str);
30 |     $result = [];
31 | 
32 |     // Start
33 |     foreach ($first as $f_value) {
34 |         $str_len = strlen($f_value) - 1;
35 |         $i       = 0;
36 |         $temp    = '';
37 |         while ($str_len >= 0) {
38 |             if (ord($f_value[$str_len]) > 64 && ord($f_value[$str_len]) < 91) {
39 |                 $temp .= strtoupper($f_value[$i]);
40 |             } else if (ord($f_value[$str_len]) > 96 && ord($f_value[$str_len]) < 123) {
41 |                 $temp .= strtolower($f_value[$i]);
42 |             }
43 |             $i++;
44 |             $str_len--;
45 |         }
46 |         array_push($result, strrev($temp));
47 |     }
48 |     return implode(' ', $result);
49 | }
50 | 
51 | // +--------------------------------------------------------------------------
52 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
53 | // +--------------------------------------------------------------------------
54 | 
55 | var_dump(BigSmallReplace('Hello World'));
56 | 


--------------------------------------------------------------------------------
/src/Other/CartesianProduct.php:
--------------------------------------------------------------------------------
 1 | params = func_get_args();
15 |     }
16 |     public function combineDika()
17 |     {
18 |         $result = [];
19 |         if(count($this->params[0])!=count($this->params[0], 1)){
20 |             $this->params = $this->params[0];
21 |         }
22 |         $cnt = count($this->params);
23 |         foreach($this->params[0] as $item) {
24 |             $result[] = [$item];
25 |         }
26 |         for($i = 1; $i < $cnt; $i++) {
27 |             $result = $this->combineArray($result,$this->params[$i]);
28 |         }
29 |         return $result;
30 |     }
31 | 
32 |     private function combineArray($arr_a, $arr_b)
33 |     {
34 |         $result = [];
35 |         foreach ($arr_a as $item) {
36 |             foreach ($arr_b as $item2) {
37 |                 $temp = $item;
38 |                 $temp[] = $item2;
39 |                 $result[] = $temp;
40 |             }
41 |         }
42 |         return $result;
43 |     }
44 | }
45 | 
46 | $color = array('白色','黑色','红色');
47 | $size = array('透气','防滑');
48 | $local = array('37码','38码','39码');
49 | 
50 | $obj = new CartesianProduct($color,$size,$local);
51 | print_r($obj->combineDika());
52 | 
53 | $sets = array(
54 |     array('白色','黑色','红色'),
55 |     array('透气','防滑'),
56 |     array('37码','38码','39码'),
57 |     array('男款','女款')
58 | );
59 | 
60 | $obj1  = new CartesianProduct($sets);
61 | print_r($obj1->combineDika());


--------------------------------------------------------------------------------
/src/Other/ColorBricks.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2017/9/1
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 思路分析:
11 |  *  例如: s = "ABAB",那么小易有六种排列的结果:
12 |  *  "AABB","ABAB","ABBA","BAAB",    "BBAA"   "BABA",
13 |  *      1-2     0      2-3    0-1       0-3      1-2
14 |  *    "ABAB",   0
15 |  *    "BAAB",   0-1
16 |  *    "AABB",   0-2
17 |  *    "BABA"    0-3
18 |  *    "ABBA",   1-2
19 |  *    "BBAA"    1-3
20 |  * -------------------------------------------------------------
21 |  * 小易有一些彩色的砖块。每种颜色由一个大写字母表示。各个颜色砖块看起来都完全一样。
22 |  * 现在有一个给定的字符串s,s中每个字符代表小易的某个砖块的颜色。小易想把他所有的砖块排成一行。
23 |  * 如果最多存在一对不同颜色的相邻砖块,那么这行砖块就很漂亮的。
24 |  * -------------------------------------------------------------
25 |  * 请你帮助小易计算有多少种方式将他所有砖块排成漂亮的一行。(如果两种方式所对应的砖块颜色序列是相同的,那么认为这两种方式是一样的。)
26 |  * -------------------------------------------------------------
27 |  *  例如: s = "ABAB",那么小易有六种排列的结果:
28 |  *    "AABB","ABAB","ABBA","BAAB","BABA","BBAA"
29 |  *     其中只有"AABB"和"BBAA"满足最多只有一对不同颜色的相邻砖块。
30 |  *  -------
31 |  *  输入描述:
32 |  *           输入包括一个字符串s,字符串s的长度length(1 ≤ length ≤ 50), [s中的每一个字符都为一个大写字母(A到Z)]。
33 |  *  输出描述:
34 |  *           输出一个整数,表示小易可以有多少种方式。
35 |  *  -------
36 |  *  输入例子1:
37 |  *           ABAB
38 |  *  输出例子1:
39 |  *           2
40 |  */
41 | 
42 | // +--------------------------------------------------------------------------
43 | // | 解题方式    | 这儿,可能有用的解决方案
44 | // +--------------------------------------------------------------------------
45 | 
46 | /**
47 |  * ColorBricks
48 |  *
49 |  * @param $inputting
50 |  * @return bool|int
51 |  */
52 | function ColorBricks($inputting)
53 | {
54 |     $count = strlen($inputting);
55 |     $ascii = ord($inputting);
56 | 
57 |     if (!($ascii > 64 && $ascii < 91)) {
58 |         return false;
59 |     }
60 |     if (!(1 <= $count && $count <= 50)) {
61 |         return false;
62 |     }
63 | 
64 |     $container = array ();
65 |     $max       = floor($count / 2);
66 | 
67 |     for ($i = 0; $i < $max; $i++) {
68 |         for ($j = 1; $j < $count; $j++) {
69 |             $temp          = $inputting[$j];
70 |             $inputting[$j] = $inputting[0];
71 |             $inputting[0]  = $temp;
72 |             array_push($container, $inputting);
73 |         }
74 |     }
75 |     $containerCount = count($container);
76 |     $counter   = 0;
77 | 
78 |     for ($i = 0; $i < $max; $i++) {
79 |         $success = false;
80 |         for ($j = 0; $j < $containerCount; $j++) {
81 |             $str = $container[$j];
82 |             if ($str[$i] == $str[0]) {
83 |                 $success = true;
84 |             }
85 |         }
86 |         if ($success) {
87 |             $counter++;
88 |         }
89 |     }
90 |     return $counter;
91 | }
92 | 
93 | 
94 | // +--------------------------------------------------------------------------
95 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
96 | // +--------------------------------------------------------------------------
97 | 
98 | echo ColorBricks("AABB");


--------------------------------------------------------------------------------
/src/Other/DynamicProgramming.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2017/8/28
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 思路分析:动态规划原理思想,max(opt(i-1,w),wi+opt(i-1,w-wi)) 当中最大值,opt(i-1,w-wi)指上一个最优解
11 |  * -------------------------------------------------------------
12 |  * 一个承受最大重量为W的背包,现在有n个物品,每个物品重量为t, 每个物品的价值为v。
13 |  * 要使得这个背包重量最大(但不能超过W),同时又需要背包的价值最大
14 |  */
15 | 
16 | // +--------------------------------------------------------------------------
17 | // | 解题方式    | 这儿,可能有用的解决方案
18 | // +--------------------------------------------------------------------------
19 | 
20 | /**
21 |  * DynamicProgramming
22 |  *
23 |  * @param $maxSize
24 |  * @param $goods
25 |  * @param $cost
26 |  * @return mixed
27 |  */
28 | function DynamicProgramming($maxSize, $goods, $cost)
29 | {
30 |     $container  = [];
31 |     $goodsCount = count($goods);
32 | 
33 |     //初始化
34 |     for ($i = 0; $i <= $maxSize; $i++) {
35 |         $container[0][$i] = 0;
36 |     }
37 |     for ($j = 0; $j <= $goodsCount; $j++) {
38 |         $container[$j][0] = 0;
39 |     }
40 |     for ($j = 1; $j <= $goodsCount; $j++) {
41 |         for ($i = 1; $i <= $maxSize; $i++) {
42 |             $container[$j][$i] = $container[$j - 1][$i];
43 |             //不大于最大的w=15
44 |             if ($goods[$j - 1] <= $maxSize) {
45 |                 if (!isset($container[$j - 1][$i - $goods[$j - 1]])) {
46 |                     continue;
47 |                 }
48 |                 //wi+opt(i-1,wi)
49 |                 $tmp = $container[$j - 1][$i - $goods[$j - 1]] + $cost[$j - 1];
50 |                 //opt(i-1,w),wi+opt(i-1,w-wi) => 进行比较
51 |                 if ($tmp > $container[$j][$i]) {
52 |                     $container[$j][$i] = $tmp;
53 |                 }
54 |             }
55 |         }
56 |     }
57 |     return $container[$j - 1][$i - 1];
58 | }
59 | 
60 | // +--------------------------------------------------------------------------
61 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
62 | // +--------------------------------------------------------------------------
63 | 
64 | echo DynamicProgramming(15, array (3, 4, 5, 6), array (8, 7, 4, 9));
65 | 


--------------------------------------------------------------------------------
/src/Other/ElevatorDispatch.php:
--------------------------------------------------------------------------------
  1 | 
  7 |  * @date     2018/1/11
  8 |  * @license  MIT
  9 |  * -------------------------------------------------------------
 10 |  * 解决方案:
 11 |  * (1)使用简单的方法,直接将楼层从1到n开始遍历
 12 |  *      sum(person[i] *  |i - j| ) 此表达式为一个双重循环,i与j均为1-n的循环。
 13 |  *      j下标表示电梯停靠的楼层。
 14 |  *      person数组表示,对应i层的下电梯的人数。此算法负责度为o(n*n)
 15 |  *      对应的j是上述和为最小的一层即为所求。 上面的算法复杂度为o(n)
 16 |  *
 17 |  * (2)下面考虑一个简单的算法,使其复杂度达到o(n)
 18 |  *      考虑假如电梯停靠在某一楼层i处,假设在i处下楼的客人为$first_layer,
 19 |  *      在i以上楼层的客人数目为$first_layer_above ,在i一下楼层的客人数目为$first_layer_below。
 20 |  *      且将电梯在i层停止时,全部人员的路程之和记为T。
 21 |  *
 22 |  *      那么加入电梯在i-1层停的话,则原来i层之上的人需要多爬一层,即增加了$first_layer_above
 23 |  *      第i层的人需要多爬一层,则结果增加了$first_layer,  i层之下的人则少爬了一层,结果减去$first_layer_below
 24 |  *      所以第i-1层的结果为$time- $first_layer_below + $first_layer + $first_layer_above 。即结果可以即为$time-($first_layer_below - $first_layer - $first_layer_above)
 25 |  *
 26 |  *
 27 |  * 下面考虑在i+1层的结果,若电梯在i+1层停止的话,原来i层之上的客户都会少爬一层,
 28 |  * 则结果减少$first_layer_above ,而i层之下的人员则都会多爬一层即增加了$first_layer_below ,第i层的人员都会多爬一层
 29 |  * 即为增加了$first_layer 。则结果为$time+ $first_layer_below + $first_layer - $first_layer_above
 30 |  *
 31 |  * 综上我们得出,
 32 |  *      (1)若$first_layer_below > $first_layer + $first_layer_above的时候, 我们在第i-1层 选择电梯停止最好。
 33 |  *      (2)若$first_layer_below + $first_layer < $first_layer_above的时候, 我们选择在第i+1层停止电梯最好。
 34 |  *
 35 |  * 下面我们可以先计算出来当i=1时候的T ,然后判断是否需要在i+1层停止,若是i+1层的花费
 36 |  * 大于i层,则我们可以继续计算,否则退出。
 37 |  */
 38 | 
 39 | 
 40 | // +--------------------------------------------------------------------------
 41 | // | 解题方式    | 这儿,可能有用的解决方案
 42 | // +--------------------------------------------------------------------------
 43 | 
 44 | class ElevatorDispatch
 45 | {
 46 |     protected $n = 10;
 47 |     protected $person;
 48 |     protected $time = 0; //先计算出在第一层停止的时候 所需要的花费
 49 |     protected $first_layer_below = 0;   //在第一层以下下的人数
 50 |     protected $first_layer;
 51 |     protected $first_layer_above = 0;//在第一层之上下电梯的人数
 52 |     public $floor = 1;//存储停靠的楼层
 53 | 
 54 |     public function __construct($person = [])
 55 |     {
 56 |         if (empty($person)) {
 57 |             $this->person = [0, 2, 5, 7, 3, 5, 2, 6, 2, 6, 3];
 58 |         }
 59 |         $this->first_layer = $this->person[1]; //在第一层处下的人数
 60 | 
 61 |     }
 62 | 
 63 |     public function compute()
 64 |     {
 65 | 
 66 |         //先计算出第1层停止需要爬取的楼层数目
 67 |         for ($i = 2; $i <= $this->n; $i++) {
 68 |             $this->time += $this->person[$i] * ($i - 1);
 69 |             $this->first_layer_above += $this->person[$i];
 70 |         }
 71 |         for ($j = 2; $j <= $this->n; $j++) {
 72 |             if ($this->first_layer_below + $this->first_layer <= $this->first_layer_above) { //说明第i+1层的结果会大于第i层
 73 |                 $this->time += $this->first_layer_below + $this->first_layer - $this->first_layer_above;
 74 |                 $this->first_layer_below += $this->first_layer;
 75 |                 $this->first_layer = $this->person[$j];
 76 |                 $this->first_layer_above -= $this->person[$j];
 77 |                 $this->floor = $j;
 78 |             } else {
 79 |                 //否则第i层的结果已经最小,故不需要计算第i+1层
 80 |                 break;
 81 |             }
 82 |         }
 83 |         return $this->floor;
 84 |     }
 85 | 
 86 |     public function computeTwo()
 87 |     {
 88 |         $min = 6553;//存储最小值 ;
 89 |         for ($i = 1; $i <= $this->n; $i++) { //表示第i楼层电梯停靠
 90 |             $this->time = 0;
 91 |             for ($j = 1; $j < $this->n; $j++) {
 92 |                 $this->time += abs(($i - $j)) * $this->person[$j];
 93 |             }
 94 |             if ($min > $this->time) {
 95 |                 $min = $this->time;
 96 |                 $this->floor = $i;
 97 |             }
 98 |         }
 99 |         return $this->floor;
100 |     }
101 | 
102 | }
103 | 
104 | // +--------------------------------------------------------------------------
105 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
106 | // +--------------------------------------------------------------------------
107 | 
108 | 
109 | $obj = new ElevatorDispatch();
110 | var_dump($obj->compute());
111 | var_dump($obj->computeTwo());


--------------------------------------------------------------------------------
/src/Other/Encryption.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2018/1/11
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 位运算进行加密
11 |  */
12 | 
13 | // +--------------------------------------------------------------------------
14 | // | 解题方式    | 这儿,可能有用的解决方案
15 | // +--------------------------------------------------------------------------
16 | 
17 | /**
18 |  * 加密函数
19 |  *
20 |  * @param $txt
21 |  * @param $key
22 |  * @return string
23 |  */
24 | function passport_encrypt($txt, $key)
25 | {
26 |     $encrypt_key = md5(rand(0, 32000));
27 |     $ctr = 0;
28 |     $tmp = '';
29 |     for ($i = 0; $i < strlen($txt); $i++) {
30 |         $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
31 |         $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
32 |     }
33 |     return base64_encode(passport_key($tmp, $key));
34 | }
35 | 
36 | /**
37 |  * 解密函数
38 |  *
39 |  * @param $txt
40 |  * @param $key
41 |  * @return string
42 |  */
43 | function passport_decrypt($txt, $key)
44 | {
45 |     $txt = passport_key(base64_decode($txt), $key);
46 | 
47 |     $tmp = '';
48 |     for ($i = 0; $i < strlen($txt); $i++) {
49 |         $md5 = $txt[$i];
50 |         $tmp .= $txt[++$i] ^ $md5;
51 |     }
52 |     return $tmp;
53 | }
54 | 
55 | /**
56 |  * passport_key
57 |  *
58 |  * @param $txt
59 |  * @param $encrypt_key
60 |  * @return string
61 |  */
62 | function passport_key($txt, $encrypt_key)
63 | {
64 |     $encrypt_key = md5($encrypt_key);
65 |     $ctr = 0;
66 |     $tmp = '';
67 |     for ($i = 0; $i < strlen($txt); $i++) {
68 |         $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
69 |         $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
70 |     }
71 |     return $tmp;
72 | }
73 | 
74 | 
75 | // +--------------------------------------------------------------------------
76 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
77 | // +--------------------------------------------------------------------------
78 | 
79 | 


--------------------------------------------------------------------------------
/src/Other/Factorial.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2017/8/25
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 思路分析:
11 |  * -------------------------------------------------------------
12 |  * 斐波那契数列(Fibonacci Sequence)又称黄金分割数列 兔子数列
13 |  * 指的是这样一个数列:1、1、2、3、5、8、13、21
14 |  * 在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。
15 |  */
16 | 
17 | 
18 | // +--------------------------------------------------------------------------
19 | // | 解题方式    | 这儿,可能有用的解决方案
20 | // +--------------------------------------------------------------------------
21 | 
22 | 
23 | /**
24 |  * 递归方式
25 |  *
26 |  * @param $n
27 |  * @return mixed
28 |  */
29 | function FibonacciRecursive($n)
30 | {
31 |     if ($n <= 1) {
32 |         return $n;
33 |     }
34 |     return Fibonacci($n - 1) + Fibonacci($n - 2);
35 | }
36 | 
37 | /**
38 |  * 非递归方式
39 |  *
40 |  * @param $n
41 |  * @return mixed
42 |  */
43 | function Fibonacci($n)
44 | {
45 |     if ($n <= 1) {
46 |         return $n;
47 |     }
48 |     for ($fib = [0, 1], $i = 2; $i <= $n; $i++) {
49 |         $fib[$i] = $fib[$i - 1] + $fib[$i - 2];
50 |     }
51 |     return $fib[$n];
52 | }
53 | 
54 | 
55 | 
56 | // +--------------------------------------------------------------------------
57 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
58 | // +--------------------------------------------------------------------------
59 | 
60 | echo Fibonacci(10);
61 | echo FibonacciRecursive(10);
62 | 


--------------------------------------------------------------------------------
/src/Other/GetCattle.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2017/8/24
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 思路分析:见下方注释 
11 |  * -------------------------------------------------------------
12 |  *
13 |  * 牛年求牛:
14 |  *      有一母牛,到4岁可生育,每年一头,所生均是一样的母牛
15 |  *          15岁绝育,不再能生,
16 |  *          20岁死亡,问n年后有多少头牛。
17 |  *
18 |  */
19 | 
20 | // +--------------------------------------------------------------------------
21 | // | 解题方式    | 这儿,可能有用的解决方案
22 | // +--------------------------------------------------------------------------
23 | 
24 | /**
25 |  * getCattle
26 |  *
27 |  * @param $n
28 |  * @return int
29 |  */
30 | function getCattle($n)
31 | {
32 |     static $num = 1;
33 |     for ($i = 1; $i <= $n; $i++) {
34 |         if ($i == 20) {
35 |             $num--; //死亡需减一
36 |         } else if ($i >= 4 && $i < 15) {
37 |             $num++; //生小母牛(这里有小母牛)
38 |             getCattle($n - $i); //小母牛生小母牛(这里不包含小母牛)
39 |         }
40 |     }
41 |     return $num;
42 | }
43 | 
44 | 
45 | // +--------------------------------------------------------------------------
46 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
47 | // +--------------------------------------------------------------------------
48 | 
49 | echo '牛年共有:' . getCattle(10);
50 | 
51 | /*
52 | 123456789
53 |    123456
54 |       123
55 |        12
56 | 9 - 11
57 | 
58 | ---
59 | 
60 |  */


--------------------------------------------------------------------------------
/src/Other/HanoiGames.php:
--------------------------------------------------------------------------------
 1 | 
 7 |  * @date     2017/8/26
 8 |  * @license  MIT
 9 |  * -------------------------------------------------------------
10 |  * 思路分析:
11 |  * -------------------------------------------------------------
12 |  * 汉诺塔(又称河内塔)问题是印度的一个古老的传说。
13 |  * 开天辟地的神勃拉玛在一个庙里留下了三根金刚石的棒,
14 |  * 第一根上面套着64个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去,
15 |  * 庙里的众僧不倦地把它们一个个地从这根棒搬到另一根棒上,规定可利用中间的一根棒作为帮助,
16 |  * 但每次只能搬一个,而且大的不能放在小的上面。
17 |  * 面对庞大的数字(移动圆片的次数)18446744073709551615,看来,众僧们耗尽毕生精力也不可能完成金片的移动。
18 |  * 后来,这个传说就演变为汉诺塔游戏:
19 |  * 1.有三根杆子A,B,C。A杆上有若干碟子
20 |  * 2.每次移动一块碟子,小的只能叠在大的上面
21 |  * 3.把所有碟子从A杆全部移到C杆上
22 |  * 经过研究发现,汉诺塔的破解很简单,就是按照移动规则向一个方向移动金片:
23 |  * 如3阶汉诺塔的移动:A→C,A→B,C→B,A→C,B→A,B→C,A→C
24 |  * 此外,汉诺塔问题也是程序设计中的经典递归问题。
25 |  */
26 | 
27 | // +--------------------------------------------------------------------------
28 | // | 解题方式    | 这儿,可能有用的解决方案
29 | // +--------------------------------------------------------------------------
30 | 
31 | /**
32 |  * HanoiGames
33 |  *
34 |  * @param $n
35 |  * @param $x
36 |  * @param $y
37 |  * @param $z
38 |  */
39 | function HanoiGames($n, $x, $y, $z)
40 | {
41 |     if ($n == 1) {
42 |         echo 'move disk 1 from ' . $x . ' to ' . $z . "\n";
43 |     } else {
44 |         HanoiGames($n - 1, $x, $z, $y);
45 |         echo 'move disk ' . $n . ' from ' . $x . ' to ' . $z . "\n";
46 |         HanoiGames($n - 1, $y, $x, $z);
47 |     }
48 | }
49 | 
50 | 
51 | // +--------------------------------------------------------------------------
52 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
53 | // +--------------------------------------------------------------------------
54 | 
55 | HanoiGames(3, 'A', 'B', 'C');
56 | 
57 | //  move disk 1 from A to C
58 | //  move disk 2 from A to B
59 | //  move disk 1 from C to B
60 | //  move disk 3 from A to C
61 | //  move disk 1 from B to A
62 | //  move disk 2 from B to C
63 | //  move disk 1 from A to C
64 | 


--------------------------------------------------------------------------------
/src/Other/HashTable.php:
--------------------------------------------------------------------------------
  1 | 
  6 |  * @date     2019/5/9
  7 |  * @license  MIT
  8 |  * -------------------------------------------------------------
  9 |  * HashTable
 10 |  */
 11 | 
 12 | 
 13 | define('TABLE_SIZE', 100);
 14 | 
 15 | class KeyValue
 16 | {
 17 |     public $key;
 18 |     public $value;
 19 | 
 20 |     public function __construct($key, $value)
 21 |     {
 22 |         $this->key = $key;
 23 |         $this->value = $value;
 24 |     }
 25 | }
 26 | 
 27 | class HashTable
 28 | {
 29 |     public $size = 0;
 30 |     public $data = [];
 31 | }
 32 | 
 33 | function create_table($size = TABLE_SIZE)
 34 | {
 35 |     $table = new HashTable();
 36 |     for ($i = 0; $i < $size; ++$i) {
 37 |         $table->data[$i] = null;
 38 |     }
 39 |     $table->size = 100;
 40 | 
 41 |     return $table;
 42 | }
 43 | 
 44 | function destroy_table(&$table)
 45 | {
 46 |     unset($table);
 47 | }
 48 | 
 49 | function hash_key($key, $size = TABLE_SIZE)
 50 | {
 51 |     $len = strlen($key);
 52 |     $hash = 0;
 53 |     for ($i = 0; $i < $len; ++$i) {
 54 |         $hash = $hash * 31 + ord($key[$i]);
 55 |     }
 56 | 
 57 |     return abs($hash % $size);
 58 | }
 59 | 
 60 | function print_debug($table)
 61 | {
 62 |     for ($i = 0; $i < $table->size; ++$i) {
 63 |         if (null === $table->data[$i]) {
 64 |             echo $i, "\n";
 65 |         } else {
 66 |             echo $i, ' key=', $table->data[$i]->key, ', value=', $table->data[$i]->value , "\n";
 67 |         }
 68 |     }
 69 | }
 70 | 
 71 | function exists(&$table, $key)
 72 | {
 73 |     $index = hash_key($key);
 74 |     if (null === $table->data[$index]) {
 75 |         return false;
 76 |     }
 77 | 
 78 |     if (0 === strcmp($key, $table->data[$index]->key)) {
 79 |         return true;
 80 |     }
 81 | 
 82 |     return false;
 83 | }
 84 | 
 85 | function add(&$table, $key, KeyValue $object)
 86 | {
 87 |     $index = hash_key($key);
 88 |     $table->data[$index] = $object;
 89 | }
 90 | 
 91 | function get(&$table, $key)
 92 | {
 93 |     $index = hash_key($key);
 94 |     if (0 === strcmp($key, $table->data[$index]->key)) {
 95 |         return $table->data[$index]->value;
 96 |     }
 97 | }
 98 | 
 99 | function delete(&$table, $key)
100 | {
101 |     $index = hash_key($key);
102 |     if (null === $table->data[$index]) {
103 |         return;
104 |     }
105 |     if (0 === strcmp($key, $table->data[$index]->key)) {
106 |         return $table->data[$index] = null;
107 |     }
108 | }
109 | 
110 | $hash_table = create_table();
111 | print_debug($hash_table);
112 | 
113 | add($hash_table, 'Wang', new KeyValue('Wang', '50'));
114 | add($hash_table, 'Li', new KeyValue('Li', '20'));
115 | add($hash_table, 'Chow', new KeyValue('Chow', '23'));
116 | print_debug($hash_table);
117 | 
118 | //get
119 | echo "----------get-------------- \n";
120 | var_dump(get($hash_table, 'Wang'));
121 | 
122 | //delete
123 | echo "----------delete-------------- \n";
124 | delete($hash_table, 'Wang');
125 | var_dump(delete($hash_table, 'Wang'));
126 | 
127 | //exists
128 | echo "----------exists-------------- \n";
129 | var_dump(exists($hash_table, 'Wang'));
130 | var_dump(exists($hash_table, 'Li'));


--------------------------------------------------------------------------------
/src/Other/Interval.php:
--------------------------------------------------------------------------------
 1 | 
 6 |  * @date     2018/1/11
 7 |  * @license  MIT
 8 |  * -------------------------------------------------------------
 9 |  *
10 |  * 不同概率的抽奖原理就是把0到*(比重总数)的区间分块
11 |  * 分块的依据是物品占整个的比重,再根据随机数种子来产生0-* 中的某个数
12 |  * 判断这个数是落在哪个区间上,区间对应的就是抽到的那个物品。
13 |  * 随机数理论上是概率均等的,那么相应的区间所含数的多少就体现了抽奖物品概率的不同。
14 |  */
15 | 
16 | 
17 | // +--------------------------------------------------------------------------
18 | // | 解题方式    | 这儿,可能有用的解决方案
19 | // +--------------------------------------------------------------------------
20 | 
21 | /**
22 |  * get_rand
23 |  *
24 |  * @param $proArr
25 |  * @return array
26 |  */
27 | function get_rand($proArr)
28 | {
29 |     $result = array();
30 |     foreach ($proArr as $key => $val) {
31 |         $arr[$key] = $val['v'];
32 |     }
33 |     $proSum = array_sum($arr);      // 计算总权重
34 |     $randNum = mt_rand(1, $proSum);
35 |     $d1 = 0;
36 |     $d2 = 0;
37 |     for ($i = 0; $i < count($arr); $i++) {
38 |         $d2 += $arr[$i];
39 |         if ($i == 0) {
40 |             $d1 = 0;
41 |         } else {
42 |             $d1 += $arr[$i - 1];
43 |         }
44 |         if ($randNum >= $d1 && $randNum <= $d2) {
45 |             $result = $proArr[$i];
46 |         }
47 |     }
48 |     unset ($arr);
49 |     return $result;
50 | }
51 | 
52 | /**
53 |  * 使用较多的为这个方法
54 |  *
55 |  * @param $proArr
56 |  * @return array
57 |  */
58 | function get_rand1($proArr)
59 | {
60 |     $result = array();
61 |     foreach ($proArr as $key => $val) {
62 |         $arr[$key] = $val['v'];
63 |     }
64 |     // 概率数组的总概率
65 |     $proSum = array_sum($arr);
66 |     asort($arr);
67 |     // 概率数组循环
68 |     foreach ($arr as $k => $v) {
69 |         $randNum = mt_rand(1, $proSum);
70 |         if ($randNum <= $v) {
71 |             $result = $proArr[$k];
72 |             break;
73 |         } else {
74 |             $proSum -= $v;
75 |         }
76 |     }
77 |     return $result;
78 | }
79 | 
80 | 
81 | // +--------------------------------------------------------------------------
82 | // | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
83 | // +--------------------------------------------------------------------------
84 | 
85 | $arr = array(
86 |     array('id' => 1, 'name' => '特等奖', 'v' => 1),
87 |     array('id' => 2, 'name' => '一等奖', 'v' => 5),
88 |     array('id' => 3, 'name' => '二等奖', 'v' => 10),
89 |     array('id' => 4, 'name' => '三等奖', 'v' => 12),
90 |     array('id' => 5, 'name' => '四等奖', 'v' => 22),
91 |     array('id' => 6, 'name' => '没中奖', 'v' => 50)
92 | );
93 | 
94 | var_dump(get_rand($arr));
95 | 
96 | 


--------------------------------------------------------------------------------
/src/Other/Judge.php:
--------------------------------------------------------------------------------
 1 | weight = $weight;
19 |         $this->value =  $value;
20 |         $this->total_weight =  $total_weight;
21 |     }
22 | 
23 |     # 贪心算法去算最佳的物品
24 |     public function bag()
25 |     {
26 |         $product = [];
27 |         foreach ($this->weight as $k => $v) {
28 |             $product[] = ['weight' => $v, 'value' => $this->value[$k], 'pj_value' => ($this->value[$k] / $v)];
29 |         }
30 | 
31 |         $total_value = 0;
32 |         //按价值比去排序
33 |         $sorted_product = $this->sortByPj_value($product);
34 |         //print_r($sorted_product);
35 |         $total = 0;
36 |         foreach ($sorted_product as $k => $v) {
37 |             if ($total + $v['weight'] <= $this->total_weight) {
38 | 
39 |                 $total_value += $v['value'];
40 | 
41 |                 $total += $v['weight'];
42 |             } elseif ($total < $this->total_weight) {
43 | 
44 |                 for ($j = $k + 1; $j < count($sorted_product); $j++) {
45 |                     if (($sorted_product[$j]['weight'] + $total) <= 150) {
46 |                         $total_value += $sorted_product[$j]['value'];
47 |                         $total += $sorted_product[$j]['weight'];
48 |                     }
49 |                 }
50 | 
51 |                 break;
52 | 
53 |             }else{
54 | 
55 |                 break;
56 |             }
57 |         }
58 | 
59 |         return [$total ,$total_value ];
60 | 
61 |     }
62 | 
63 |     private function sortByPj_value($product)
64 |     {
65 |         for ($i = 0; $i < count($product); $i++) {
66 |             for ($j = $i + 1; $j < count($product); $j++) {
67 |                 if ($product[$i]['pj_value'] < $product[$j]['pj_value']) {
68 |                     $temp = $product[$i];
69 |                     $product[$i] = $product[$j];
70 |                     $product[$j] = $temp;
71 |                 }
72 |             }
73 | 
74 |         }
75 |         return $product;
76 |     }
77 | }
78 | 
79 | $obj = new Knapsack([35, 30, 60, 50, 40, 15, 10],[10, 40, 30, 50, 35, 40, 30],150);
80 | var_dump($obj->bag());
81 | 
82 | 
83 | 
84 | 


--------------------------------------------------------------------------------
/src/Other/Maze.php:
--------------------------------------------------------------------------------
  1 | 
  7 |  * @date     2018/1/11
  8 |  * @license  MIT
  9 |  * -------------------------------------------------------------
 10 |  *   构造迷宫二维数组
 11 |  */
 12 | 
 13 | // +--------------------------------------------------------------------------
 14 | // | 解题方式    | 这儿,可能有用的解决方案
 15 | // +--------------------------------------------------------------------------
 16 | 
 17 | 
 18 | //迷宫一
 19 | for ($l = 0; $l <= 5; $l++) {
 20 |     for ($m = 0; $m <= 5; $m++) {
 21 |         if ($l == 1 && $m <= 3)
 22 |             $arr[$l][$m] = 0;
 23 |         elseif ($l == 2 && ($m == 1 || $m == 3 || $m == 4))
 24 |             $arr[$l][$m] = 0;
 25 |         elseif ($l == 3 && $m <= 4 && $m != 0 && $m != 3)
 26 |             $arr[$l][$m] = 0;
 27 |         elseif ($l == 4 && ($m == 1 || $m >= 4))
 28 |             $arr[$l][$m] = 0;
 29 |         else
 30 |             $arr[$l][$m] = 1;
 31 | 
 32 |         echo $arr[$l][$m] . ' ';
 33 |     }
 34 |     echo '
'; 35 | } 36 | echo '


寻地址算法的实现:
'; 37 | 38 | /** 39 | * findPath 40 | * 41 | * @param $i 42 | * @param $j 43 | * @param $dir 44 | * @param $arr 45 | * @param $iline 46 | * @param $jline 47 | * @param $dirline 48 | * @return int 49 | */ 50 | function findPath($i, $j, $dir, $arr, $iline, $jline, $dirline) 51 | { 52 | 53 | //判断是否结束 54 | if ($i == 4 && $j == 5) return 1; 55 | $ifdirs = 0; 56 | $newdir = $dir; 57 | $lastdir = $dir; 58 | 59 | 60 | //如果该点为0,则前进 61 | if ($arr[$i][$j] == 0) { 62 | //判断方向增量 63 | switch ($dir) { 64 | case 0: 65 | $ii = 0; 66 | $jj = 1; 67 | break; 68 | case 1: 69 | $ii = 1; 70 | $jj = 0; 71 | break; 72 | case 2: 73 | $ii = 0; 74 | $jj = -1; 75 | break; 76 | case 3: 77 | $ii = -1; 78 | $jj = 0; 79 | break; 80 | } 81 | 82 | //判断是否路口 83 | for ($n = 1; $n <= 4; $n++) { 84 | switch ($newdir) { 85 | case 0: 86 | $aa = 0; 87 | $bb = 1; 88 | break; 89 | case 1: 90 | $aa = 1; 91 | $bb = 0; 92 | break; 93 | case 2: 94 | $aa = 0; 95 | $bb = -1; 96 | break; 97 | case 3: 98 | $aa = -1; 99 | $bb = 0; 100 | break; 101 | } 102 | if ($arr[($i + $aa)][($j + $bb)] == 0) { 103 | $ifdirs++; 104 | } 105 | $newdir = ($newdir + 1) % 4; 106 | } 107 | 108 | //判断是否路口,是则记录位置和方向 109 | if ($ifdirs > 2) { 110 | 111 | if (in_array($i, $iline) && in_array($j, $jline)) { 112 | } else { 113 | echo "该点是路口:|$i,$j,$dir|
"; 114 | $iline[] = $i; 115 | $jline[] = $j; 116 | $dirline[] = $dir; 117 | } 118 | } 119 | 120 | if ($ifdirs > 1) { 121 | //不是死路,前进 122 | if ($arr[($i + $ii)][($j + $jj)] == 0) { 123 | //方向不变,可以前进 124 | $i += $ii; 125 | $j += $jj; 126 | echo "方向不变,可以前进:|$i,$j,$dir|
"; 127 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 128 | } else { 129 | //方向改变,试探 130 | if ($ifdirs > 2) { 131 | //该点是路口,取来时方向为路口记录方向 132 | $lastdir = $dirline[(count($dirline) - 1)]; 133 | } else { 134 | //不是路口,则在改变方向前记录方向 135 | $lastdir = $dir; 136 | } 137 | 138 | //判断来时方向,不能走回头路 139 | switch ($lastdir) { 140 | case 0: 141 | $errdir = 2; 142 | break; 143 | case 1: 144 | $errdir = 3; 145 | break; 146 | case 2: 147 | $errdir = 0; 148 | break; 149 | case 3: 150 | $errdir = 1; 151 | break; 152 | } 153 | //改变方向 154 | $dir = ($dir + 1) % 4; 155 | 156 | //判断改变后方向是否为来时方向 157 | echo "不能走回头路:err:$errdir,dir:$dir
"; 158 | if ($dir != $errdir) { 159 | echo "turn:($i,$j,$dir)
"; 160 | switch ($dir) { 161 | case 0: 162 | $mm = 0; 163 | $nn = 1; 164 | break; 165 | case 1: 166 | $mm = 1; 167 | $nn = 0; 168 | break; 169 | case 2: 170 | $mm = 0; 171 | $nn = -1; 172 | break; 173 | case 3: 174 | $mm = -1; 175 | $nn = 0; 176 | break; 177 | } 178 | if ($arr[($i + $mm)][($j + $nn)] == 0) { 179 | $i += $mm; 180 | $j += $nn; 181 | echo "可以前进:$i,$j,$dir
"; 182 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 183 | } else { 184 | $dir = ($dir + 1) % 4; 185 | echo "再改变方向,试探:$i,$j,$dir
"; 186 | if ($dir != $errdir) { 187 | echo "turn:($i,$j,$dir)
"; 188 | switch ($dir) { 189 | case 0: 190 | $ii = 0; 191 | $jj = 1; 192 | break; 193 | case 1: 194 | $ii = 1; 195 | $jj = 0; 196 | break; 197 | case 2: 198 | $ii = 0; 199 | $jj = -1; 200 | break; 201 | case 3: 202 | $ii = -1; 203 | $jj = 0; 204 | break; 205 | } 206 | if ($arr[($i + $ii)][($j + $jj)] == 0) { 207 | $i += $ii; 208 | $j += $jj; 209 | echo "可以前进:$i,$j,$dir
"; 210 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 211 | } 212 | } else { 213 | $dir = ($dir + 1) % 4; 214 | echo "再改变方向,试探:$i,$j,$dir
"; 215 | switch ($dir) { 216 | case 0: 217 | $ii = 0; 218 | $jj = 1; 219 | break; 220 | case 1: 221 | $ii = 1; 222 | $jj = 0; 223 | break; 224 | case 2: 225 | $ii = 0; 226 | $jj = -1; 227 | break; 228 | case 3: 229 | $ii = -1; 230 | $jj = 0; 231 | break; 232 | } 233 | if ($arr[($i + $ii)][($j + $jj)] == 0) { 234 | $i += $ii; 235 | $j += $jj; 236 | echo "OK:$i,$j,$dir
"; 237 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 238 | } 239 | 240 | } 241 | } 242 | 243 | } else { 244 | $dir = ($dir + 1) % 4; 245 | echo "不能回头,再改变方向,试探:$i,$j,$dir
"; 246 | switch ($dir) { 247 | case 0: 248 | $ii = 0; 249 | $jj = 1; 250 | break; 251 | case 1: 252 | $ii = 1; 253 | $jj = 0; 254 | break; 255 | case 2: 256 | $ii = 0; 257 | $jj = -1; 258 | break; 259 | case 3: 260 | $ii = -1; 261 | $jj = 0; 262 | break; 263 | } 264 | if ($arr[($i + $ii)][($j + $jj)] == 0) { 265 | $i += $ii; 266 | $j += $jj; 267 | echo "可以前进:$i,$j,$dir
"; 268 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 269 | } 270 | } 271 | } 272 | } else { 273 | //是死路,需要返回到上个路口,改变方向,试探 274 | $dir = $dirline[(count($dirline) - 1)]; 275 | $i = $iline[(count($iline) - 1)]; 276 | $j = $jline[(count($jline) - 1)]; 277 | echo "是死路,返回到上个路口,记录为:#$i,$j,$dir#
"; 278 | $dir = ($dir + 1) % 4; 279 | findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); 280 | 281 | } 282 | 283 | } 284 | } 285 | 286 | $a[] = $b[] = $c[] = 0; 287 | echo '初始值=>节点:($i=1,$j=1),方向:($dir=0).

'; 288 | findPath(1, 1, 0, $arr, $a, $b, $c); -------------------------------------------------------------------------------- /src/Other/MonkeyKing.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/23 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:约瑟夫环问题 11 | * ------------------------------------------------------------- 12 | * 有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 13 | */ 14 | 15 | // +-------------------------------------------------------------------------- 16 | // | 解题方式 | 这儿,可能有用的解决方案 17 | // +-------------------------------------------------------------------------- 18 | 19 | 20 | class MonkeyKing 21 | { 22 | protected $next; 23 | protected $name; 24 | 25 | /** 26 | * MonkeyKing constructor. 27 | * 28 | * @param $name 29 | */ 30 | public function __construct($name) 31 | { 32 | $this->name = $name; 33 | } 34 | 35 | /** 36 | * whoIsKing 37 | * 38 | * @static 39 | * @param $count 40 | * @param $num 41 | * @return mixed 42 | */ 43 | public static function whoIsKing($count, $num) 44 | { 45 | // 构造单向循环链表 46 | $current = $first = new MonkeyKing(1); 47 | for ($i = 2; $i <= $count; $i++) { 48 | $current->next = new MonkeyKing($i); 49 | $current = $current->next; 50 | } 51 | // 最后一个指向第一个 52 | $current->next = $first; 53 | // 指向第一个 54 | $current = $first; 55 | // 定义一个数字 56 | $cn = 1; 57 | while ($current !== $current->next) { 58 | $cn++; 59 | if ($cn == $num) { 60 | $current->next = $current->next->next; 61 | $cn = 1; 62 | } 63 | $current = $current->next; 64 | } 65 | // 返回猴子姓名 66 | return $current->name; 67 | } 68 | } 69 | 70 | /** 71 | * whoIsKing 72 | * 73 | * @param $n 74 | * @param $m 75 | * @return int 76 | */ 77 | function whoIsKing($n, $m) 78 | { 79 | $r = 0; 80 | for ($i = 2; $i <= $n; $i++) { 81 | $r = ($r + $m) % $i; 82 | } 83 | return $r + 1; 84 | } 85 | 86 | /** 87 | * king 88 | * 89 | * @param $n 90 | * @param $m 91 | * @return mixed 92 | */ 93 | function king($n, $m) 94 | { 95 | $monkeys = range(1, $n); 96 | $i = 0; 97 | $k = $n; 98 | while (count($monkeys) > 1) { 99 | if (($i + 1) % $m == 0) { 100 | unset($monkeys[$i]); 101 | } else { 102 | array_push($monkeys, $monkeys[$i]); 103 | unset($monkeys[$i]); 104 | } 105 | $i++; 106 | } 107 | return current($monkeys); 108 | } 109 | 110 | 111 | 112 | // +-------------------------------------------------------------------------- 113 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 114 | // +-------------------------------------------------------------------------- 115 | 116 | 117 | // 共10个猴子每3个出圈 118 | var_dump(MonkeyKing::whoIsKing(10, 3)); 119 | 120 | 121 | var_dump(whoIsKing(10, 3)); 122 | 123 | 124 | $a = king(10, 3); 125 | var_dump($a); -------------------------------------------------------------------------------- /src/Other/NQueen.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2023/12/06 8 | * @license MIT 9 | */ 10 | /* 11 | |-------------------------------------------------------------------------- 12 | | NQueen Algorithm 13 | |-------------------------------------------------------------------------- 14 | | 15 | | Arrange N queens on an NxN chessboard without attacking each other diagonally, 16 | | horizontally, or vertically—a classic problem in combinatorial optimization and 17 | | recursion. 18 | | 19 | */ 20 | 21 | class NQueen 22 | { 23 | 24 | //Variable to store the dimensions of the chessboard 25 | protected int $n; 26 | 27 | //Chessboard represented as an array 28 | protected array $board; 29 | 30 | //Constructor to initialize the chessboard dimensions and fill it with zeros 31 | public function __construct(int $n) 32 | { 33 | $this->n = $n; 34 | $this->board = array_fill(0, $this->n, array_fill(0, $this->n, 0)); 35 | } 36 | 37 | public function solve_n_queen($col = 0): void 38 | { 39 | if ($col >= $this->n) { 40 | $this->print_result(); 41 | } 42 | 43 | //Iterating through each row in the current column 44 | for ($row = 0; $row < $this->n; $row++) { 45 | if ($this->move_is_promising($row, $col)) { 46 | //Placing the queen at the current position 47 | $this->board[$row][$col] = 1; 48 | //Recursively solving for the next column 49 | $this->solve_n_queen($col + 1); 50 | //Backtracking by removing the queen from the current position 51 | $this->board[$row][$col] = 0; 52 | } 53 | } 54 | } 55 | 56 | public function move_is_promising($row, $col): bool 57 | { 58 | //Checking if there is no queen in the same row 59 | for ($index = 0; $index < $col; $index++) 60 | if ($this->board[$row][$index]) 61 | return false; 62 | 63 | //Checking if there is no queen on the upper-left diagonal 64 | for ($i = $row, $j = $col; $i >= 0 && $j >= 0; $i--, $j--) 65 | if ($this->board[$i][$j]) 66 | return false; 67 | 68 | //Checking if there is no queen on the lower-left diagonal 69 | for ($i = $row, $j = $col; $i < $this->n && $j >= 0; $i++, $j--) 70 | if ($this->board[$i][$j]) 71 | return false; 72 | 73 | //If no conflicts are found, the move is promising 74 | return true; 75 | } 76 | 77 | public function print_result(): void 78 | { 79 | for ($i = 0; $i < $this->n; $i++) { 80 | for ($j = 0; $j < $this->n; $j++) 81 | echo $this->board[$i][$j]; 82 | echo "\n"; 83 | } 84 | echo "\n"; 85 | } 86 | } 87 | 88 | $dimensions = 4; 89 | (new NQueen($dimensions))->solve_n_queen(); 90 | -------------------------------------------------------------------------------- /src/Other/OnlyNumbers.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/30 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:快排同时做唯一标示 11 | * ------------------------------------------------------------- 12 | * 一个数组里只有唯一一个元素是不同于别的元素,其余元素是两两相等如何得到这个元素 13 | * 14 | */ 15 | 16 | // +-------------------------------------------------------------------------- 17 | // | 解题方式 18 | // +-------------------------------------------------------------------------- 19 | 20 | /** 21 | * OnlyNumbers 22 | * 23 | * @param array $container 24 | * @return array|bool 25 | */ 26 | function OnlyNumbers(array $container) 27 | { 28 | $count = count($container); 29 | if ($count <= 1) { 30 | return $container; 31 | } 32 | $exist = []; 33 | for ($i = 0; $i < $count; $i++) { 34 | if (isset($exist[$container[$i]])) { 35 | unset($exist[$container[$i]]); 36 | continue; 37 | } 38 | $exist[$container[$i]] = true; 39 | } 40 | return !empty($exist) ? array_keys($exist)[0] : false; 41 | } 42 | 43 | // +---------------------------------------------------------------------- 44 | // | 方法二 45 | // +---------------------------------------------------------------------- 46 | /** 47 | * @author Openset 48 | * @link https://github.com/openset 49 | * @date 2017/9/7 50 | * @param array $container 51 | * @return null 52 | */ 53 | function OnlyNumbersV2(array $container) 54 | { 55 | $res = array_flip(array_count_values($container)); 56 | 57 | return isset($res[1]) ? $res[1] : null; 58 | } 59 | 60 | // +---------------------------------------------------------------------- 61 | // | 方法三 62 | // +---------------------------------------------------------------------- 63 | /** 64 | * @author Openset 65 | * @link https://github.com/openset 66 | * @date 2018/2/24 67 | * @param array $container 68 | * @return null 69 | */ 70 | function OnlyNumbersV3(array $container) 71 | { 72 | $num = 0; 73 | foreach ($container as $v) { 74 | $num ^= $v; 75 | } 76 | 77 | return $num; 78 | } 79 | 80 | // +-------------------------------------------------------------------------- 81 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 82 | // +-------------------------------------------------------------------------- 83 | 84 | var_dump(OnlyNumbers([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); 85 | var_dump(OnlyNumbersV2([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); 86 | var_dump(OnlyNumbersV3([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); 87 | -------------------------------------------------------------------------------- /src/Other/PointInTriangle.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2018/1/11 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 利用向量叉集判断一个点是否在三角形中 11 | */ 12 | 13 | // +-------------------------------------------------------------------------- 14 | // | 解题方式 | 这儿,可能有用的解决方案 15 | // +-------------------------------------------------------------------------- 16 | 17 | class PointInTriangle 18 | { 19 | /** 20 | * @var array 21 | */ 22 | protected $point; 23 | /** 24 | * @var array 25 | */ 26 | protected $triangle; 27 | 28 | /** 29 | * PointInTriangle constructor. 30 | * 31 | * @param array $point 32 | * @param array $triangle 33 | */ 34 | public function __construct(array $point, array $triangle) 35 | { 36 | $this->point = $point; 37 | if (count($triangle) != 3) { 38 | exit('这个不是三角形'); 39 | } 40 | $this->triangle = $triangle; 41 | } 42 | 43 | /** 44 | * 向量叉集计算 45 | * 46 | * @param $a 47 | * @param $b 48 | * @param $p 49 | * @return mixed 50 | */ 51 | private function cross($a, $b, $p) 52 | { 53 | return ($b['x'] - $a['x']) * ($p['y'] - $a['y']) - ($b['y'] - $a['y']) * ($p['x'] - $a['x']); 54 | } 55 | 56 | /** 57 | * 判断是否在左边 58 | * 59 | * @param $a 60 | * @param $b 61 | * @param $p 62 | * @return bool 63 | */ 64 | private function toLeft($a, $b, $p) 65 | { 66 | return $this->cross($a, $b, $p) > 0; 67 | } 68 | 69 | /** 70 | * 开始构造三角形 71 | * 72 | * @return string 73 | */ 74 | public function inTriangle() 75 | { 76 | $res = $this->toLeft($this->triangle[0], $this->triangle[1], $this->point); 77 | 78 | if ($res != $this->toLeft($this->triangle[1], $this->triangle[2], $this->point)) { 79 | return '不在三角形中'; 80 | } 81 | if ($res != $this->toLeft($this->triangle[2], $this->triangle[0], $this->point)) { 82 | return '不在三角形中'; 83 | } 84 | 85 | if ($this->cross($this->triangle[0], $this->triangle[1], $this->triangle[2]) == 0) { 86 | return '不在三角形中'; 87 | } 88 | return '点' . json_encode($this->point) . '在三角形中'; 89 | } 90 | } 91 | 92 | 93 | // +-------------------------------------------------------------------------- 94 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 95 | // +-------------------------------------------------------------------------- 96 | 97 | $point = [ 98 | 'x' => 4, 99 | 'y' => 1 100 | ]; 101 | $point1 = [ 102 | 'x' => 4, 103 | 'y' => 5 104 | ]; 105 | $triangle = [ 106 | ['x' => 1, 'y' => 1], 107 | ['x' => 6, 'y' => 3], 108 | ['x' => 4, 'y' => 7], 109 | ]; 110 | 111 | $obj = new PointInTriangle($point1, $triangle); 112 | var_dump($obj->inTriangle()); 113 | exit; -------------------------------------------------------------------------------- /src/Other/PokerGames.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/9/18 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 随机玩法 11 | */ 12 | 13 | 14 | // +-------------------------------------------------------------------------- 15 | // | 解题方式 | 这儿,可能有用的解决方案 16 | // +-------------------------------------------------------------------------- 17 | 18 | /** 19 | * washCard 20 | * 21 | * @param $card_num 22 | * @return array 23 | */ 24 | function washCard($card_num) 25 | { 26 | $cards = range(1, $card_num); 27 | for ($i = $card_num - 1; $i > 0; $i--) { 28 | $rnd = rand(0, $i - 1); 29 | list($cards[$rnd], $cards[$i]) = array ($cards[$i], $cards[$rnd]); 30 | } 31 | return $cards; 32 | } 33 | 34 | 35 | /** 36 | * PokerGames 纯属娱乐,有空再优化, 这样够随机吧 37 | */ 38 | class PokerGames 39 | { 40 | /** 41 | * 42 | */ 43 | const RANDOM = "https://www.random.org/integers/?num=%d&min=1&max=%d&col=1&base=10&format=plain&rnd=new"; 44 | /** 45 | * 46 | */ 47 | const LIMIT = 10; 48 | 49 | /** 50 | * @var 51 | */ 52 | protected $resources; 53 | /** 54 | * @var 55 | */ 56 | protected $tally; 57 | /** 58 | * @var float 59 | */ 60 | protected $i; 61 | /** 62 | * @var 63 | */ 64 | protected $count; 65 | /** 66 | * @var bool 67 | */ 68 | protected $clear; 69 | /** 70 | * @var array 71 | */ 72 | protected $container = array (); 73 | /** 74 | * @var array 75 | */ 76 | protected $poker = array (); 77 | 78 | /** 79 | * PokerGames constructor. 80 | */ 81 | public function __construct() 82 | { 83 | $this->container = $this->makePoker(); 84 | $count = count($this->container); 85 | $this->i = $this->tally = round(100 / $count, 2); 86 | $this->clear = in_array(PHP_OS, array ('Darwin', 'Linux')); 87 | $this->taskJob($this->generator($count, round($count / 2))); 88 | } 89 | 90 | /** 91 | * 弄着玩,不推进实际生产里玩 | 无脑方法2 92 | * 93 | * @param \Generator $task 94 | */ 95 | public function taskJob(Generator $task) 96 | { 97 | foreach ($task as $value) { 98 | if (empty($value)) { 99 | break; 100 | } 101 | foreach ($value as $_value) { 102 | if (isset($this->container[$_value])) { 103 | array_push($this->poker, $this->container[$_value]); 104 | unset($this->container[$_value]); 105 | $this->clear && system("clear"); 106 | echo "正在洗牌中.. " . intval($this->tally) . "% \n"; 107 | $this->tally += $this->i; 108 | } 109 | continue; 110 | } 111 | } 112 | } 113 | 114 | /** 115 | * __destruct, 116 | */ 117 | public function __destruct() 118 | { 119 | curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 120 | $this->poker = array_merge($this->poker, array_diff_assoc($this->container, $this->poker)); 121 | var_dump($this->poker); 122 | } 123 | 124 | /** 125 | * generator 好像没别的用 就为了装 126 | * 127 | * @param $limit 128 | * @param $max 129 | * @return \Generator 130 | */ 131 | public function generator($max, $limit = 1) 132 | { 133 | while ($limit--) { 134 | yield $this->makeRand($max); 135 | } 136 | } 137 | 138 | /** 139 | * 创建一副扑克牌 140 | * 141 | * @return array 142 | */ 143 | public function makePoker() 144 | { 145 | $porker = array ('大王', '小王'); 146 | foreach (array ('红桃', '方块', '梅花', '黑桃') as $pValue) { 147 | $limit = 13; 148 | while ($limit--) { 149 | switch ($limit) { 150 | case 0: 151 | $temp = "J"; 152 | break; 153 | case 1: 154 | $temp = "A"; 155 | break; 156 | case 11: 157 | $temp = "Q"; 158 | break; 159 | case 12: 160 | $temp = "K"; 161 | break; 162 | default: 163 | $temp = $limit; 164 | break; 165 | } 166 | array_push($porker, $pValue . $temp); 167 | } 168 | } 169 | return $porker; 170 | } 171 | 172 | /** 173 | * 去大气噪音那里拿随机数 174 | * 175 | * @param $max 176 | * @return mixed 177 | */ 178 | public function makeRand($max) 179 | { 180 | $ch = curl_init(); 181 | curl_setopt_array($ch, [ 182 | CURLOPT_URL => sprintf(self::RANDOM, $max, $max), 183 | CURLOPT_SSL_VERIFYPEER => false, 184 | CURLOPT_RETURNTRANSFER => true, 185 | CURLOPT_HTTPHEADER => array ('Expect:'), 186 | CURLOPT_HEADER => false, 187 | CURLOPT_CONNECTTIMEOUT => self::LIMIT, 188 | CURLOPT_TIMEOUT => self::LIMIT, 189 | ]); 190 | $result = curl_exec($ch); 191 | $code = curl_getinfo($ch)['http_code']; 192 | $this->resources = $ch; 193 | if ($code == 200) { 194 | return explode(PHP_EOL, $result); 195 | } 196 | return false; 197 | } 198 | } 199 | 200 | // +-------------------------------------------------------------------------- 201 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 202 | // +-------------------------------------------------------------------------- 203 | 204 | $card_num = 54;//牌数 205 | var_dump(washCard($card_num)); 206 | new PokerGames(); 207 | -------------------------------------------------------------------------------- /src/Other/Prim.php: -------------------------------------------------------------------------------- 1 | lowcost[$i] = $graph[0][$i]; 32 | $mst[$i] = 0; 33 | } 34 | for ($i = 1; $i < $n; $i++) { 35 | $min = 65535; 36 | $minid = 0; 37 | for ($j = 1; $j < $n; $j++) { 38 | if ($this->lowcost[$j] < $min && $this->lowcost[$j] != 0) { 39 | $min = $this->lowcost[$j]; 40 | $minid = $j; 41 | } 42 | } 43 | echo '
';
44 |                 print_r($this->c[$mst[$minid]] ."到" . $this->c[$minid] . " 权值:" . $min);
45 |             echo '
'; 46 | 47 | $sum += $min; 48 | $this->lowcost[$minid] = 0; 49 | 50 | for ($j = 1; $j < $n; $j++) { 51 | if ($graph[$minid][$j] < $this->lowcost[$j]) { 52 | $this->lowcost[$j] = $graph[$minid][$j]; 53 | $mst[$j] = $minid; 54 | } 55 | } 56 | } 57 | print_r("sum:" . $sum); 58 | } 59 | 60 | public function main() 61 | { 62 | $map = [ 63 | [0, 10, 65535, 65535, 65535, 11, 65535, 65535, 65535], 64 | [10, 0, 18, 65535, 65535, 65535, 16, 65535, 12], 65 | [65535, 65535, 0, 22, 65535, 65535, 65535, 65535, 8], 66 | [65535, 65535, 22, 0, 20, 65535, 65535, 16, 21], 67 | [65535, 65535, 65535, 20, 0, 26, 65535, 7, 65535], 68 | [11, 65535, 65535, 65535, 26, 0, 17, 65535, 65535], 69 | [65535, 16, 65535, 65535, 65535, 17, 0, 19, 65535], 70 | [65535, 65535, 65535, 16, 7, 65535, 19, 0, 65535], 71 | [65535, 12, 8, 21, 65535, 65535, 65535, 65535, 0] 72 | ]; 73 | $this->prim_main($map, count($map)); 74 | } 75 | } 76 | 77 | $obj = new Prim(); 78 | $obj->main(); 79 | -------------------------------------------------------------------------------- /src/Other/Rectangle.php: -------------------------------------------------------------------------------- 1 | $value) { 32 | $x = abs($value[0]-$one[0]); 33 | $y = abs($value[1]-$one[1]); 34 | $data[$key] = sqrt(pow($x,2)+pow($y,2)); 35 | } 36 | 37 | asort($data); 38 | $keys = array_keys($data); 39 | $maxKey = array_pop($keys);//对焦点 40 | $length0 = $data[$maxKey];//对角线长度 41 | 42 | //左右两点 key 43 | $left = $keys[0]; 44 | $right = $keys[1]; 45 | 46 | //算第二条对角线长度 47 | $x = abs($array[$left][0]-$array[$right][0]); 48 | $y = abs($array[$left][1]-$array[$right][1]); 49 | $length = sqrt(pow($x,2)+pow($y,2)); 50 | 51 | if(!floatEq($length,$length0)) { 52 | return false; 53 | } 54 | 55 | //算直角 56 | $vertical = sqrt(pow($data[$left],2)+pow($data[$right],2)); 57 | 58 | if(!floatEq($length,$vertical)) { 59 | return false; 60 | } 61 | 62 | return true; 63 | 64 | } 65 | 66 | var_dump(rectangle([0,0],[0,1],[1,1],[1,0])); //true 67 | var_dump(rectangle([1,2],[0,1],[1,1],[1,0])); //false 68 | 69 | /** 70 | * 判断两个浮点数是不是相等 71 | * 72 | * @param $a float 73 | * @param $b float 74 | * @return bool 75 | */ 76 | function floatEq($floatNumber1,$floatNumber2) 77 | { 78 | if(!$floatNumber1 || !$floatNumber2) { 79 | return false; 80 | } 81 | //精度 82 | $epsilon = 0.00001; 83 | 84 | if(abs($floatNumber1-$floatNumber2) < $epsilon) { 85 | return true; 86 | } 87 | return false; 88 | } 89 | -------------------------------------------------------------------------------- /src/Other/RotateSort.php: -------------------------------------------------------------------------------- 1 | | 6 | * | Date: 2019/10/11 | 7 | * | Time: 下午2:56 | 8 | * ---------------------------------------- 9 | * | _____ ______ _ _ | 10 | * | | __ \| ____(_) | | | 11 | * | | |__) | |__ _ _ __ __ _| | | 12 | * | | ___/| __| | | '_ \ / _` | | | 13 | * | | | | | | | | | | (_| | | | 14 | * | |_| |_| |_|_| |_|\__,_|_| | 15 | * ---------------------------------------- 16 | * 说明: 面试遇到一个写一个函数 让输出效果 如风车一样旋转 如下 17 | * foo(4) 逆时针 18 | * 16,15,14,13 19 | * 5, 4, 3, 12 20 | * 6, 1, 2, 11 21 | * 7, 8, 9, 10 22 | * foo(4) 顺顺时针 23 | * 7, 8, 9, 10 24 | * 6, 1, 2, 11 25 | * 5, 4, 3, 12 26 | * 16,15, 14,13 27 | * 28 | */ 29 | 30 | $num = 4; 31 | $arr = foo($num); 32 | for ($i = 0; $i < $num; $i++) { 33 | echo implode(',', $arr[$i])."
"; 34 | } 35 | 36 | /** 37 | * @param $num 38 | * @param int $direction 方向 1 为 顺时针旋转 2 为逆时针旋转 39 | * @return mixed 40 | */ 41 | function foo($num, $direction = 1) 42 | { 43 | //填充map 44 | $data = new stdClass(); 45 | $data->x = 1; 46 | if ($direction == 1) { 47 | $data->y = $num; 48 | } elseif ($direction == 2) { 49 | $data->y = 1; 50 | } 51 | $data->num = $num; 52 | $data->len = $num * $num; 53 | $data->tmp_data = []; 54 | $data->rate = 1;//方向 55 | $data->struct = create_struct($num); 56 | for ($i = $data->len; $i >= 1; $i--) { 57 | $data->i = $i; 58 | $key = change_key($data, $direction); 59 | $data->tmp_data[$key] = $i; 60 | unset($data->struct[$key]); 61 | } 62 | 63 | //根据y坐标分组 64 | $data->struct = create_struct($num); 65 | foreach ($data->tmp_data as $key => $value) { 66 | $data->struct[$key] = $value; 67 | } 68 | for ($i = 1; $i <= $data->num; $i++) { 69 | $start = ($i - 1) * $data->num; 70 | $end = $data->num; 71 | $slice = array_slice($data->struct, $start, $end); 72 | $data->slice[] = $slice; 73 | } 74 | 75 | return $data->slice; 76 | } 77 | 78 | function create_struct($num) 79 | { 80 | $struct = []; 81 | for ($i = 1; $i <= $num; $i++) { 82 | //嵌套 83 | for ($m = 1; $m <= $num; $m++) { 84 | $key = $m.','.$i; 85 | $struct[$key] = ''; 86 | } 87 | } 88 | 89 | return $struct; 90 | } 91 | 92 | function change_key($data, $direction) 93 | { 94 | $key = $data->x.','.$data->y; 95 | if (isset($data->struct[$key])) { 96 | return $key; 97 | } 98 | switch ($data->rate) { 99 | // LEFT 方向 100 | case 1: 101 | $data->tmp_x = $data->x + 1; 102 | $key = $data->tmp_x.','.$data->y; 103 | if (isset($data->struct[$key])) { 104 | $data->x = $data->tmp_x; 105 | 106 | return $key; 107 | } else { 108 | if ($direction = 1) { 109 | $data->rate = 4; 110 | } elseif ($direction = 2) { 111 | $data->rate = 2; 112 | } 113 | } 114 | break; 115 | // DOWN 方向 116 | case 2: 117 | $data->tmp_y = $data->y + 1; 118 | $key = $data->x.','.$data->tmp_y; 119 | if (isset($data->struct[$key])) { 120 | $data->y = $data->tmp_y; 121 | 122 | return $key; 123 | } else { 124 | if ($direction = 1) { 125 | $data->rate = 1; 126 | } elseif ($direction = 2) { 127 | $data->rate = 3; 128 | } 129 | } 130 | break; 131 | // RIGHT 方向 132 | case 3: 133 | $data->tmp_x = $data->x - 1; 134 | $key = $data->tmp_x.','.$data->y; 135 | if (isset($data->struct[$key])) { 136 | $data->x = $data->tmp_x; 137 | 138 | return $key; 139 | } else { 140 | if ($direction = 1) { 141 | $data->rate = 2; 142 | } elseif ($direction = 2) { 143 | $data->rate = 4; 144 | } 145 | } 146 | break; 147 | // UP 方向 148 | case 4: 149 | $data->tmp_y = $data->y - 1; 150 | $key = $data->x.','.$data->tmp_y; 151 | if (isset($data->struct[$key])) { 152 | $data->y = $data->tmp_y; 153 | 154 | return $key; 155 | } else { 156 | if ($direction = 1) { 157 | $data->rate = 3; 158 | } elseif ($direction = 2) { 159 | $data->rate = 1; 160 | } 161 | } 162 | break; 163 | } 164 | 165 | return change_key($data, $direction); 166 | } -------------------------------------------------------------------------------- /src/Other/RotationSort.php: -------------------------------------------------------------------------------- 1 | row = $row; 18 | $this->col =$col; 19 | $this->start = $start; 20 | $this->print_matrix(); 21 | } 22 | 23 | private function print_matrix() 24 | { 25 | //当前遍历层数 26 | $small =$this->col < $this->row ?$this->col : $this->row; 27 | 28 | $count = ceil($small / 2); 29 | 30 | for($i=0; $i < $count; $i++) 31 | { 32 | $maxRight = $this->col -1 - $i; //右边最大坐标 33 | $maxBottom = $this->row -1 - $i; //下面最大坐标 34 | 35 | for($j=$i; $j<=$maxRight; $j++) 36 | { 37 | $this->res[$i][$j] = $this->start++; 38 | } 39 | for($j=$i; $j<$maxBottom; $j++) 40 | { 41 | $this->res[$j+1][$maxRight] = $this->start++; 42 | } 43 | for($j=$maxRight-1;$j>=$i; $j--) 44 | { 45 | if(isset($this->res[$maxBottom][$j])) break; 46 | $this->res[$maxBottom][$j] = $this->start++; 47 | } 48 | for($j=$maxBottom-1;$j>$i;$j--) 49 | { 50 | if(isset($this->res[$j][$i])) break; 51 | $this->res[$j][$i] = $this->start++; 52 | } 53 | } 54 | } 55 | 56 | /** 57 | * @return string 58 | * 输出回旋形状 59 | */ 60 | public function print_table() 61 | { 62 | $str = ''; 63 | for ($i = 0; $i < $this->row; $i++) { 64 | $str .=''; 65 | for ($j = 0; $j < $this->col; $j++) { 66 | $str .='"; 67 | } 68 | $str .=""; 69 | } 70 | $str .='
'.$this->res[$i][$j] . "
'; 71 | return $str; 72 | } 73 | } 74 | 75 | $obj = new RotationSort(7, 8); 76 | echo $obj->print_table(); -------------------------------------------------------------------------------- /src/Other/Solution.php: -------------------------------------------------------------------------------- 1 | grid = $grid; 31 | $this->islandPerimeter(); 32 | } 33 | 34 | public function islandPerimeter() 35 | { 36 | if (empty($this->grid) || empty($this->grid[0])) return 0; 37 | 38 | foreach ($this->grid as $key => $val) { 39 | 40 | foreach ($this->grid[0] as $k => $v) { 41 | if ($this->grid[$key][$k] == 0) continue; 42 | $this->result += 4; 43 | 44 | if ($key > 0 && $this->grid[$key - 1][$k] == 1) { 45 | $this->result -= 2; 46 | } 47 | if ($k > 0 && $this->grid[$key][$k - 1] == 1) { 48 | $this->result -= 2; 49 | } 50 | } 51 | } 52 | } 53 | } 54 | 55 | $arr = [ 56 | [0,1,0,0], 57 | [1,1,1,0], 58 | [0,1,0,0], 59 | [1,1,0,0] 60 | ]; 61 | 62 | $result = new Solution($arr); 63 | var_dump($result->result); -------------------------------------------------------------------------------- /src/Other/Square.php: -------------------------------------------------------------------------------- 1 | point = $point; 17 | } 18 | 19 | public function check() 20 | { 21 | $result = []; 22 | if (count($this->point) != 4) return false; 23 | for ($i = 0; $i < 4; $i++) { 24 | for ($j = $i + 1; $j < 4; $j++) { 25 | $result[]=$this->_calculation($i,$j); 26 | } 27 | } 28 | sort($result); 29 | if ($result[0] == $result[1] && $result[4] == $result[5] && $result[4] > $result[1]) { 30 | return true; 31 | } 32 | return false; 33 | 34 | } 35 | 36 | private function _calculation($i, $j) 37 | { 38 | return pow($this->point[$i][0] - $this->point[$j][0],2) + pow($this->point[$i][1] - $this->point[$j][1] ,2); 39 | } 40 | } 41 | 42 | $obj = new Square([[0, 0], [1, 0], [1, 1], [0, 1]]); 43 | var_dump($obj->check()); 44 | -------------------------------------------------------------------------------- /src/Other/StealingApples.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/26 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析: 11 | * ------------------------------------------------------------- 12 | * 有5个人偷了一堆苹果,准备在第二天分赃。 13 | * 晚上,有一人遛出来,把所有苹果分成5份,但是多了一个,顺手把这个扔给树上的猴了,自己先拿1/5藏了。 14 | * 没想到其他四人也都是这么想的,都如第一个人一样分成5份把多的那一个扔给了猴,偷走了1/5。 15 | * 第二天,大家分赃,也是分成5份多一个扔给猴了。最后一人分了一份。 16 | * 问:共有多少苹果?N 个人呢? 17 | * ------------------------------------------------------------- 18 | */ 19 | 20 | // +-------------------------------------------------------------------------- 21 | // | 解题方式 | 这儿,可能有用的解决方案 22 | // +-------------------------------------------------------------------------- 23 | 24 | $i = 1; 25 | while (true) { 26 | if ($i % 5 == 1) { 27 | //第一个人取五分之一,还剩$t 28 | $t = $i - round($i / 5) - 1; 29 | if ($t % 5 == 1) { 30 | //第二个人取五分之一,还剩$r 31 | $r = $t - round($t / 5) - 1; 32 | if ($r % 5 == 1) { 33 | //第三个人取五分之一,还剩$s 34 | $s = $r - round($r / 5) - 1; 35 | if ($s % 5 == 1) { 36 | //第四个人取五分之一,还剩$x 37 | $x = $s - round($s / 5) - 1; 38 | if ($x % 5 == 1) { 39 | //第五个人取五分之一,还剩$y 40 | $y = $x - round($x / 5) - 1; 41 | if ($y % 5 == 1) { 42 | echo $i; 43 | break; 44 | } 45 | } 46 | } 47 | } 48 | } 49 | } 50 | $i++; 51 | } 52 | 53 | // +---------------------------------------------------------------------- 54 | // | 方法二 55 | // +---------------------------------------------------------------------- 56 | /** 57 | * @author Openset 58 | * @link https://github.com/openset 59 | * @date 2017/9/7 60 | * @param int $n N个人 61 | * @param int $r 共有多少苹果 62 | */ 63 | for ($r = 1, $n = 5; ; $r++) { 64 | $t = $r; 65 | for ($i = 0; $i <= $n; $i++) { 66 | if ($t % $n == 1) { 67 | $t = $t - round($t / $n) - 1; 68 | } else { 69 | continue 2; 70 | } 71 | } 72 | echo $r; 73 | break; 74 | } 75 | 76 | //15621 77 | 78 | // +-------------------------------------------------------------------------- 79 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 80 | // +-------------------------------------------------------------------------- 81 | 82 | -------------------------------------------------------------------------------- /src/Query/BFSQuery.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/6/17 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析: BFS并不使用经验法则算法。从算法的观点,所有因为展开节点而得到的子节点都会被加进一个先进先出的队列中 11 | * 时间复杂度:O(n) 12 | * ------------------------------------------------------------- 13 | * 宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。 14 | * Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。 15 | * 其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。 16 | * 换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。 17 | */ 18 | class BFSQuery 19 | { 20 | /** 21 | * @var array 关系网络 22 | */ 23 | protected $relationship; 24 | /** 25 | * @var \SplQueue 处理队列 26 | */ 27 | protected $queue; 28 | 29 | /** 30 | * @var string 搜索结果 31 | */ 32 | protected $target; 33 | 34 | /** 35 | * BFSQuery constructor. 36 | * 37 | * @param array $relationship 38 | * @param string $target 39 | */ 40 | public function __construct(array $relationship, $target) 41 | { 42 | 43 | $this->relationship = $relationship; 44 | $this->queue = new SplQueue(); 45 | $this->target = $target; 46 | $this->generator($this->relationship); 47 | } 48 | 49 | /** 50 | * 开始入列 51 | * 52 | * @param array $relation 53 | * @return \Generator 54 | */ 55 | public function generator($relation) 56 | { 57 | foreach ($relation as $value) { 58 | $this->schedule($value); 59 | } 60 | } 61 | 62 | 63 | /** 64 | * 队列入队 65 | * 66 | * @param $item 67 | * @return int 68 | */ 69 | public function schedule($item) 70 | { 71 | $this->queue->enqueue($item); 72 | } 73 | 74 | /** 75 | * 队列中查找符合条件 76 | * 77 | * @return string 78 | */ 79 | public function run() 80 | { 81 | $result = $this->target . '没有人有~!'; 82 | while (!$this->queue->isEmpty()) { 83 | // 出队列 84 | $item = $this->queue->dequeue(); 85 | if (!isset($item['friend'])) { 86 | continue; 87 | } 88 | if (!isset($item['fruit'])) { 89 | continue; 90 | } 91 | $totalFruit = count($item['fruit']); 92 | $mark = 0; 93 | while ($totalFruit > $mark) { 94 | if ($item['fruit'][$mark] === $this->target) { 95 | $result = '找到了~!'; 96 | break 2; 97 | } 98 | $mark++; 99 | } 100 | $this->generator($item['friend']); 101 | } 102 | return $result; 103 | } 104 | } 105 | 106 | 107 | // +-------------------------------------------------------------------------- 108 | // | 方案测试 109 | // +-------------------------------------------------------------------------- 110 | // 你现在需要一个 `mango` ,所以你需要在你的朋友圈里搜刮,你可以先从Jack 与 tom 身上找, 111 | // 然后再从他们的朋友身上找,然后再从他们朋友的朋友哪里找 112 | 113 | $me = array ( 114 | 'jack' => array ( 115 | 'fruit' => array ('apple', 'banana', 'dragon'), 116 | 'friend' => array ( 117 | 'lucy' => array ( 118 | 'fruit' => array ('bear', 'watermelon'), 119 | 'friend' => array ( 120 | 'marco' => array ( 121 | 'fruit' => array ('mango', 'cherry'), // Mango 在这儿 122 | 'friend' => array ( 123 | '...', 124 | ) 125 | ), 126 | ), 127 | ), 128 | 'bob' => array ( 129 | 'fruit' => array ('orange', 'mangosteen', 'peach'), 130 | 'friend' => array ( 131 | '', 132 | ), 133 | ), 134 | 135 | ), 136 | ), 137 | 'tom' => array ( 138 | 'fruit' => array ( 139 | 'apple', 140 | 'banana', 141 | ), 142 | 'friend' => array ( 143 | 'lucy' => array ( 144 | 'fruit' => array (), 145 | 'friend' => array ( 146 | 'lucy' => array ( 147 | 'fruit' => array ('bear', 'watermelon'), 148 | 'friend' => array ( 149 | 'marco' => array ( 150 | 'fruit' => array ('mango', 'cherry'), // Mango 在这儿也有 151 | 'friend' => array ( 152 | '...', 153 | ) 154 | ), 155 | ), 156 | ), 157 | ), 158 | ), 159 | 'bob' => array ( 160 | 'fruit' => array ('apple', 'peach'), 161 | 'friend' => array ( 162 | 'marco' => array ( 163 | 'fruit' => array ('mango', 'cherry'), // Mango 在这儿也有 164 | 'friend' => array ( 165 | 'Marco 有无数多的盆友...', 166 | ) 167 | ), 168 | ) 169 | ), 170 | ), 171 | ) 172 | ); 173 | 174 | echo (new BFSQuery($me, 'mango'))->run(); -------------------------------------------------------------------------------- /src/Query/BinaryQuery.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/6/17 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:数组中间的值floor((low+top)/2)  11 | * ------------------------------------------------------------- 12 | * 先取数组中间的值floor((low+top)/2)然后通过与所需查找的数字进行比较, 13 | * 若比中间值大则将首值替换为中间位置下一个位置,继续第一步的操作; 14 | * 若比中间值小,则将尾值替换为中间位置上一个位置,继续第一步操作 15 | * 重复第二步操作直至找出目标数字 16 | */ 17 | 18 | // +-------------------------------------------------------------------------- 19 | // | 解题方式 | 这儿,可能有用的解决方案 20 | // +-------------------------------------------------------------------------- 21 | 22 | /** 23 | * 非递归版 二分查找 24 | * 25 | * @param array $container 26 | * @param $search 27 | * @return int|string 28 | */ 29 | function BinaryQuery(array $container, $search) 30 | { 31 | $top = count($container); 32 | $low = 0; 33 | while ($low <= $top) { 34 | $mid = intval(floor(($low + $top) / 2)); 35 | if (!isset($container[$mid])) { 36 | return '没找着哦'; 37 | } 38 | if ($container[$mid] == $search) { 39 | return $mid; 40 | } 41 | $container[$mid] < $search && $low = $mid + 1; 42 | $container[$mid] > $search && $top = $mid - 1; 43 | } 44 | } 45 | 46 | 47 | /** 48 | * 递归版 二分查找 49 | * 50 | * @param array $container 51 | * @param $search 52 | * @param int $low 53 | * @param string $top 54 | * @return int|string 55 | */ 56 | function BinaryQueryRecursive(array $container, $search, $low = 0, $top = 'default') 57 | { 58 | $top === 'default' && $top = count($container); 59 | if ($low <= $top) { 60 | $mid = intval(floor($low + $top) / 2); 61 | if (!isset($container[$mid])) { 62 | return '没找着哦'; 63 | } 64 | if ($container[$mid] == $search) { 65 | return $mid; 66 | } 67 | if ($container[$mid] < $search) { 68 | return BinaryQueryRecursive($container, $search, $mid + 1, $top); 69 | } else { 70 | return BinaryQueryRecursive($container, $search, $low, $mid - 1); 71 | } 72 | } 73 | } 74 | 75 | // +-------------------------------------------------------------------------- 76 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 77 | // +-------------------------------------------------------------------------- 78 | 79 | var_dump(BinaryQuery([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)); 80 | /* 81 | * double(8) 82 | */ 83 | var_dump(BinaryQueryRecursive([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)); 84 | /* 85 | array(7) { 86 | [0] => 87 | int(3) 88 | [1] => 89 | int(4) 90 | [2] => 91 | int(5) 92 | [3] => 93 | int(6) 94 | [4] => 95 | int(7) 96 | [5] => 97 | int(8) 98 | [6] => 99 | int(9) 100 | } 101 | */ 102 | -------------------------------------------------------------------------------- /src/Query/DijkstraQuery.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/23 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:单源最短路径问题 11 | * ------------------------------------------------------------- 12 | * Dijkstra 算法一般的表述通常有两种方式,一种用永久和临时标号方式,一种是用OPEN, CLOSE表的方式, 13 | * 这里均采用永久和临时标号的方式。注意该算法要求图中不存在负权边。 14 | * 因此,在包含负边全的图中要找出最短路径,可以使用另一种算法 -- 贝克曼-福德算法 15 | */ 16 | 17 | // +-------------------------------------------------------------------------- 18 | // | 解题方式 19 | // +-------------------------------------------------------------------------- 20 | 21 | /** 22 | * DijkstraQuery 23 | * 24 | * @uses PHPStorm 25 | * @version 1.0 26 | * @author Pu ShaoWei 27 | */ 28 | class DijkstraQuery 29 | { 30 | /** 31 | * @var array 32 | */ 33 | protected $graph; 34 | /** 35 | * @var array 36 | */ 37 | protected $processed; 38 | /** 39 | * @var int 40 | */ 41 | protected $infinity; 42 | /** 43 | * @var string 44 | */ 45 | protected $start; 46 | /** 47 | * @var string 48 | */ 49 | protected $end; 50 | 51 | /** 52 | * DijkstraQuery constructor. 53 | * 54 | * @param array $graph 55 | * @param $start 56 | * @param $end 57 | */ 58 | public function __construct(array $graph, $start, $end) 59 | { 60 | $this->graph = $graph; 61 | $this->start = $start; 62 | $this->end = $end; 63 | $this->processed = array (); 64 | $this->infinity = mt_getrandmax(); 65 | } 66 | 67 | /** 68 | * 最短路径 69 | * 70 | * @return string 71 | */ 72 | public function calculate() 73 | { 74 | $costs = $this->graph[$this->start]; 75 | $costs[$this->end] = $this->infinity; 76 | $node = $this->findLowestCostNode($costs); 77 | 78 | while (null !== $node) { 79 | $cost = $costs[$node]; 80 | $neighbors = $this->graph[$node] ?? array (); 81 | foreach ($neighbors as $neighbor => $distance) { 82 | $newCost = $cost + $distance; 83 | if ($costs[$neighbor] > $newCost) { 84 | $costs[$neighbor] = $newCost; 85 | } 86 | } 87 | array_push($this->processed, $node); 88 | $node = $this->findLowestCostNode($costs); 89 | } 90 | 91 | return 'The shortest distance for:' . $costs[$this->end]; 92 | } 93 | 94 | /** 95 | * findLowestCostNode 96 | * 97 | * @param $costs 98 | * @return null 99 | */ 100 | protected function findLowestCostNode($costs) 101 | { 102 | $lowestCost = $this->infinity; 103 | $lowestCostNode = null; 104 | foreach ($costs as $node => $cost) { 105 | if ($cost < $lowestCost && !in_array($node, $this->processed)) { 106 | $lowestCost = $cost; 107 | $lowestCostNode = $node; 108 | } 109 | } 110 | return $lowestCostNode; 111 | } 112 | } 113 | 114 | // +-------------------------------------------------------------------------- 115 | // | 验证 me --> claire 116 | // +-------------------------------------------------------------------------- 117 | // ∞ 118 | $graph = array ( 119 | 'me' => array ( 120 | 'alice' => 6, 121 | 'bob' => 2, 122 | ), 123 | 'alice' => array ( 124 | 'claire' => 1, 125 | ), 126 | 'bob' => array ( 127 | 'alice' => 3, 128 | 'claire' => 5, 129 | ), 130 | 'claire' => array (// 没有任何邻居 131 | 132 | ), 133 | ); 134 | echo (new DijkstraQuery($graph, 'me', 'claire'))->calculate(); -------------------------------------------------------------------------------- /src/Query/FibonacciQuery.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/23 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:斐波那契查找 利用黄金分割原理 11 | * ------------------------------------------------------------- 12 | * $num == $container[$mid],直接返回 13 | * $num < $container[$mid],新范围是第 $low 个到 $mid-1 个,此时范围个数为 produced($key-1)-1 个 14 | * $num > $container[$mid],新范围是第 $mid+1 个到 $high 个,此时范围个数为 produced($key-2)-1 个 15 | */ 16 | 17 | 18 | // +-------------------------------------------------------------------------- 19 | // | 解题方式 20 | // +-------------------------------------------------------------------------- 21 | 22 | class FibonacciQuery 23 | { 24 | /** 25 | * FibonacciQuery constructor. 26 | * 27 | * @param array $container 28 | * @param $num 29 | */ 30 | public function __construct(array $container, $num) 31 | { 32 | $count = count($container); 33 | $lower = $key = $result = 0; 34 | $high = $count - 1; 35 | //计算$count位于斐波那契数列的位置 36 | while ($count > ($this->produced($key) - 1)) { 37 | $key++; 38 | } 39 | //将不满的数值补全,补的数值为数组的最后一位 40 | for ($j = $count; $j < $this->produced($key) - 1; $j++) { 41 | $container[$j] = $container[$count - 1]; 42 | } 43 | //查找开始 44 | while ($lower <= $high) { 45 | //计算当前分隔的下标 46 | $mid = $lower + $this->produced($key - 1) - 1; 47 | if ($num < $container[$mid]) { 48 | $high = $mid - 1; 49 | $key -= 1; //斐波那契数列数列下标减一位 50 | } else if ($num > $container[$mid]) { 51 | $lower = $mid + 1; 52 | $key -= 2; //斐波那契数列数列下标减两位 53 | } 54 | if ($mid <= $count - 1) { 55 | $result = $mid; 56 | break; 57 | } else { //这里$mid大于$count-1说明是补全数值,返回$count-1 58 | $result = $count - 1; 59 | break; 60 | } 61 | } 62 | var_dump($result); 63 | } 64 | 65 | /** 66 | * 创建一个生产斐波那契数列 67 | * 68 | * @param $length 69 | * @return int 70 | */ 71 | public function produced($length) 72 | { 73 | if ($length < 2) { 74 | return ($length == 0 ? 0 : 1); 75 | } 76 | return $this->produced($length - 1) + $this->produced($length - 2); 77 | } 78 | } 79 | 80 | // +-------------------------------------------------------------------------- 81 | // | 方案测试 82 | // +-------------------------------------------------------------------------- 83 | 84 | new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8); -------------------------------------------------------------------------------- /src/Query/InsertQuery.php: -------------------------------------------------------------------------------- 1 | 6 | * @date 2017/8/25 7 | * @license MIT 8 | * ------------------------------------------------------------- 9 | * 思路分析:对于数组长度比较大,关键字分布又是比较均匀的来说,插值查找的效率比折半查找的效率高 10 | * ------------------------------------------------------------- 11 | * 它是二分查找的改进。 12 | * 在英文词典里查找“apple”,你下意识里翻开词典是翻前面的书页还是后面的书页呢?如果再查“zoo”,你又会怎么查? 13 | * 显然你不会从词典中间开始查起,而是有一定目的地往前或往后翻。 14 | * 15 | */ 16 | 17 | // +-------------------------------------------------------------------------- 18 | // | 解题方式 | 这儿,可能有用的解决方案 19 | // +-------------------------------------------------------------------------- 20 | /** 21 | * insertQuery 22 | * 23 | * @param array $container 24 | * @param $num 25 | * @return bool|float|int 26 | */ 27 | function insertQuery(array $container, $num) 28 | { 29 | $count = count($container); 30 | $lower = 0; 31 | $high = $count - 1; 32 | 33 | while ($lower <= $high) { 34 | if ($container[ $lower ] == $num) { 35 | return $lower; 36 | } 37 | if ($container[ $high ] == $num) { 38 | return $high; 39 | } 40 | 41 | $left = intval($lower + $num - $container[ $lower ]); 42 | $right = ($container[ $high ] - $container[ $lower ]) * ($high - $lower); 43 | 44 | $middle = $left /$right; 45 | 46 | if ($num < $container[ $middle ]) { 47 | $high = $middle - 1; 48 | } else if ($num > $container[ $middle ]) { 49 | $lower = $middle + 1; 50 | } else { 51 | return $middle; 52 | } 53 | } 54 | return false; 55 | } 56 | 57 | 58 | // +-------------------------------------------------------------------------- 59 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 60 | // +-------------------------------------------------------------------------- 61 | echo insertQuery([4, 5, 7, 8, 9, 10, 8], 8); 62 | // 6 -------------------------------------------------------------------------------- /src/Query/Kmp.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2018/1/11 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * KMP算法是一种改进的字符串匹配算法 11 | * KMP精要:KMP在进行朴素匹配时,如果发现不匹配字符时,通过对已经匹配的那部分字符串的最大前缀来快速找到下一个模式串需要匹配的位置。 12 | * KMP对模式进行预处理时间复杂度O(m),匹配时间复杂度O(n),总的KMP时间复杂度为O(m+n)。 13 | * 参考 字符串匹配的KMP算法 — 阮一峰 14 | */ 15 | 16 | 17 | // +-------------------------------------------------------------------------- 18 | // | 解题方式 | 这儿,可能有用的解决方案 19 | // +-------------------------------------------------------------------------- 20 | 21 | class KMP 22 | { 23 | public $haystack; 24 | public $needle; 25 | private $_haystackLen; 26 | private $_needleLen; 27 | private $_matchTable; 28 | private $_isMatch; 29 | 30 | //构造函数 31 | function __construct($haystack, $needle) 32 | { 33 | $this->haystack = $haystack; 34 | $this->needle = $needle; 35 | //初始化一些参数 36 | $this->_haystackLen = $this->getLen($this->haystack); 37 | $this->_needleLen = $this->getLen($this->needle); 38 | $this->_matchTable = $this->getMatchTable(); 39 | $this->_isMatch = false; 40 | } 41 | 42 | 43 | //类似strpos函数功能 44 | public function strpos() 45 | { 46 | //haystack 47 | $haystackIdx = $matchNum = 0; 48 | while ($haystackIdx <= $this->_haystackLen - $this->_needleLen) { 49 | //needle 50 | $needIdx = 0; 51 | for (; $needIdx < $this->_needleLen; $needIdx++) { 52 | if (strcmp($this->haystack[$haystackIdx], $this->needle[$needIdx]) <> 0) { 53 | if ($matchNum > 0) { 54 | $lastMatchValue = $this->getLastMatchValue($needIdx - 1); 55 | $haystackIdx += $this->getStep($matchNum, $lastMatchValue); 56 | $matchNum = 0; 57 | } else { 58 | $haystackIdx++; 59 | } 60 | break; 61 | } else { 62 | $haystackIdx++; 63 | $matchNum++; 64 | if ($matchNum == $this->_needleLen) { 65 | $this->_isMatch = true; 66 | break; 67 | } 68 | } 69 | } 70 | if ($this->_isMatch == true) { 71 | break; 72 | } 73 | } 74 | return $this->_isMatch ? $haystackIdx - $this->_needleLen : false; 75 | } 76 | 77 | //获取字符长度 78 | private function getLen($str) 79 | { 80 | return mb_strlen($str, 'utf-8'); 81 | } 82 | 83 | //获取部分匹配表 84 | private function getMatchTable() 85 | { 86 | $matchTable = []; 87 | for ($i = 0; $i < $this->_needleLen; $i++) { 88 | $intersectLen = 0; 89 | $nowStr = mb_substr($this->needle, 0, $i + 1, 'utf-8'); 90 | $preFixArr = $this->getPreFix($nowStr); 91 | $sufFixArr = $this->getSufFix($nowStr); 92 | if ($preFixArr && $sufFixArr) { 93 | $intersectArr = array_intersect($preFixArr, $sufFixArr); 94 | if (!empty($intersectArr)) { 95 | $intersect = array_pop($intersectArr); 96 | $intersectLen = mb_strlen($intersect, 'utf-8'); 97 | } 98 | } 99 | $matchTable[$i] = $intersectLen; 100 | } 101 | return $matchTable; 102 | } 103 | 104 | //获取前缀数组 105 | private function getPreFix($str) 106 | { 107 | $outArr = []; 108 | $strLen = $this->getLen($str); 109 | if ($strLen > 1) { 110 | for ($i = 1; $i < $strLen; $i++) { 111 | $outArr[] = mb_substr($str, 0, $i, 'utf-8'); 112 | } 113 | } 114 | return $outArr; 115 | } 116 | 117 | //获取后缀数组 118 | private function getSufFix($str) 119 | { 120 | $outArr = []; 121 | $strLen = $this->getLen($str); 122 | if ($strLen > 1) { 123 | for ($i = 1; $i < $strLen; $i++) { 124 | $outArr[] = mb_substr($str, $i, null, 'utf-8'); 125 | } 126 | } 127 | return $outArr; 128 | } 129 | 130 | //计算步长 131 | private function getStep($matchNum, $lastMatchValue) 132 | { 133 | return $matchNum - $lastMatchValue; 134 | } 135 | 136 | //获取最后匹配值 137 | private function getLastMatchValue($index) 138 | { 139 | return isset($this->_matchTable[$index]) ? $this->_matchTable[$index] : 0; 140 | } 141 | 142 | } 143 | 144 | // +-------------------------------------------------------------------------- 145 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 146 | // +-------------------------------------------------------------------------- 147 | 148 | $str = 'a b a c a a b a c a b a c a b a a b b'; 149 | $subStr = 'a b a c a b'; 150 | $kmp = new KMP($str, $subStr); 151 | var_dump($kmp->strpos()); 152 | $kmp->haystack = 'pull requests'; 153 | $kmp->needle = 'sts'; 154 | var_dump($kmp->strpos()); 155 | $kmp->haystack = 'i love you'; 156 | $kmp->needle = 'hate'; 157 | var_dump($kmp->strpos()); -------------------------------------------------------------------------------- /src/Query/QuickQuery.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/8/23 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:数组中间的值floor((low+top)/2)  11 | * ------------------------------------------------------------- 12 | * 重复第二步操作直至找出目标数字 13 | */ 14 | 15 | /** 16 | * QuickQuery 17 | * 18 | * @param $array 19 | * @param $k 20 | * @param int $low 21 | * @param int $high 22 | * @return int 23 | */ 24 | function QuickQuery($array, $k, $low = 0, $high = 0) 25 | { 26 | //判断是否为第一次调用 27 | if (count($array) != 0 and $high == 0) { 28 | $high = count($array); 29 | } 30 | //如果还存在剩余的数组元素 31 | if ($low <= $high) { 32 | //取$low和$high的中间值 33 | $mid = intval(($low + $high) / 2); 34 | //如果找到则返回 35 | if ($array[$mid] == $k) { 36 | return $mid; 37 | } else if ($k < $array[$mid]) {//如果没有找到,则继续查找 38 | return QuickQuery($array, $k, $low, $mid - 1); 39 | } else { 40 | return QuickQuery($array, $k, $mid + 1, $high); 41 | } 42 | } 43 | return -1; 44 | } 45 | 46 | echo QuickQuery([4, 5, 7, 8, 9, 10, 8], 8); -------------------------------------------------------------------------------- /src/Sort/BubbleSort.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/6/16 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:就是像冒泡一样,每次从数组当中 冒一个最大的数出来。  11 | * ------------------------------------------------------------- 12 | * 你可以这样理解:(从小到大排序)存在10个不同大小的气泡, 13 | * 由底至上的把较少的气泡逐步地向上升,这样经过遍历一次后最小的气泡就会被上升到顶(下标为0) 14 | * 然后再从底至上地这样升,循环直至十个气泡大小有序。 15 | * 在冒泡排序中,最重要的思想是两两比较,将两者较少的升上去 16 | * 17 | */ 18 | 19 | // +-------------------------------------------------------------------------- 20 | // | 解题方式 | 这儿,可能有用的解决方案 21 | // +-------------------------------------------------------------------------- 22 | 23 | /** 24 | * BubbleSort 25 | * 26 | * @param array $container 27 | * @return array 28 | */ 29 | function BubbleSort(array $container) 30 | { 31 | $count = count($container); 32 | for ($j = 1; $j < $count; $j++) { 33 | for ($i = 0; $i < $count - $j; $i++) { 34 | if ($container[$i] > $container[$i + 1]) { 35 | $temp = $container[$i]; 36 | $container[$i] = $container[$i + 1]; 37 | $container[$i + 1] = $temp; 38 | } 39 | } 40 | } 41 | return $container; 42 | } 43 | 44 | // +-------------------------------------------------------------------------- 45 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 46 | // +-------------------------------------------------------------------------- 47 | 48 | var_dump(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); 49 | 50 | /* 51 | array(10) { 52 | [0] => 53 | int(1) 54 | [1] => 55 | int(2) 56 | [2] => 57 | int(4) 58 | [3] => 59 | int(21) 60 | [4] => 61 | int(21) 62 | [5] => 63 | int(41) 64 | [6] => 65 | int(41) 66 | [7] => 67 | int(53) 68 | [8] => 69 | int(213) 70 | [9] => 71 | int(423) 72 | } 73 | */ -------------------------------------------------------------------------------- /src/Sort/ChineseTextNumberSort.php: -------------------------------------------------------------------------------- 1 | $matchNum) { 48 | if ($matchNum === '十') { 49 | if ($plane === 0) { 50 | $currentNum += 10; 51 | continue; 52 | } 53 | if ($plane === 1) { 54 | $index = array_search($structure[0][0], $mapping); 55 | $currentNum -= $index; 56 | $currentNum += $index * 10; 57 | continue; 58 | } 59 | } 60 | $index = array_search($matchNum, $mapping); 61 | $currentNum += $index; 62 | } 63 | return $currentNum; 64 | } 65 | 66 | /** 67 | * isChinese 68 | * 69 | * @param $text 70 | * @return bool 71 | */ 72 | public function isCompletelyChinese($text) 73 | { 74 | return boolval(preg_match('/^[\x7f-\xff]+$/', $text)); 75 | } 76 | 77 | /** 78 | * regularModel 79 | * 80 | * @param $regularModel 81 | * @param $text 82 | * @return bool 83 | */ 84 | public function regularModel($regularModel, $text) 85 | { 86 | return boolval(preg_match($regularModel, $text)); 87 | } 88 | 89 | /** 90 | * extractModel 91 | * 92 | * @param $regularModel 93 | * @param $text 94 | * @return string 95 | * @throws \Exception 96 | */ 97 | public function extractModel($regularModel, $text) 98 | { 99 | $result = ''; 100 | if (preg_match($regularModel, $text, $result)) { 101 | return trim($result[$this->modelMappingIndex($regularModel)]); 102 | } 103 | throw new Exception('The matching error'); 104 | } 105 | 106 | /** 107 | * modelMappingIndex 108 | * 109 | * @param $regularModel 110 | * @return int|mixed 111 | */ 112 | protected function modelMappingIndex($regularModel) 113 | { 114 | return array ( 115 | static::MODEL_REGULAR_A => 1, 116 | static::MODEL_REGULAR_B => 0, 117 | static::MODEL_REGULAR_C => 0, 118 | static::MODEL_REGULAR_D => 1, 119 | static::MODEL_REGULAR_E => 1, 120 | static::MODEL_REGULAR_F => 1, 121 | static::MODEL_REGULAR_G => 1, 122 | static::MODEL_REGULAR_H => 1, 123 | static::MODEL_REGULAR_I => 2 124 | )[$regularModel] ?? 1; 125 | } 126 | 127 | /** 128 | * chineseConversionNum 129 | * 130 | * @param $text 131 | * @return mixed 132 | */ 133 | public function chineseConversionNum($text) 134 | { 135 | if ($this->regularModel(static::CHINESE_DIGITAL_MATCHING, $text)) { 136 | $mapping = array ('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'); 137 | return array_search($text, $mapping); 138 | } 139 | return ltrim($text, 0); 140 | } 141 | 142 | /** 143 | * getAllModelRegular 144 | * 145 | * @return array 146 | * @throws \ReflectionException 147 | */ 148 | public function getAllModelRegular() 149 | { 150 | $constants = (new \ReflectionClass(__CLASS__))->getConstants(); 151 | $collection = array (); 152 | foreach ($constants as $key => $value) { 153 | if (strpos($key, 'MODEL_REGULAR_') !== false) { 154 | $collection[$key] = $value; 155 | } 156 | } 157 | return $collection; 158 | } 159 | 160 | /** 161 | * modelAnalysis 162 | * 163 | * @param $text 164 | * @return int|string 165 | * @throws \ReflectionException 166 | */ 167 | public function modelAnalysis($text) 168 | { 169 | foreach ($this->getAllModelRegular() as $item) { 170 | if ($this->regularModel($item, $text)) { 171 | return $item; 172 | } 173 | } 174 | throw new Exception('Model Analysis of the failure !'); 175 | } 176 | 177 | /** 178 | * textAnalysis 179 | * 180 | * @param $text 181 | * @return int 182 | */ 183 | public function textAnalysis($text) 184 | { 185 | try { 186 | return (int)$this->chineseConversionNum($this->extractModel( 187 | $this->modelAnalysis($text), 188 | $text 189 | ) 190 | ); 191 | } catch (Exception $e) { 192 | return 0; 193 | } 194 | } 195 | 196 | /** 197 | * chineseTextList 198 | * 199 | * @param array $list 200 | * @return array 201 | */ 202 | public function chineseTextListSorter(array $list) 203 | { 204 | $container = $generate = array (); 205 | foreach ($list as $item) { 206 | $container[] = $this->textAnalysis($item); 207 | } 208 | if (count($container) !== count($list)) { 209 | return $list; 210 | } 211 | uksort($list, function ($left, $right) use ($container) { 212 | if ($left == $right) { 213 | return 0; 214 | } 215 | return $container[$left] < $container[$right] ? -1 : 1; 216 | }); 217 | return array_values($list); 218 | } 219 | } -------------------------------------------------------------------------------- /src/Sort/HeapSort.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/10/9 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:堆排序利用了大根堆堆顶记录的关键字最大(或最小)这一特征 11 | * ------------------------------------------------------------- 12 | * 堆排序(HeapSort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,它是选择排序的一种。 13 | * 可以利用数组的特点快速定位指定索引的元素。堆分为大根堆和小根堆,是完全二叉树。 14 | * 大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆, 15 | * 因为根据大根堆的要求可知,最大的值一定在堆顶。 16 | */ 17 | 18 | 19 | // +-------------------------------------------------------------------------- 20 | // | 解题方式 | 这儿,可能有用的解决方案 21 | // +-------------------------------------------------------------------------- 22 | 23 | 24 | class HeapSort 25 | { 26 | /** 27 | * @var int 28 | */ 29 | protected $count; 30 | 31 | /** 32 | * @var array 33 | */ 34 | protected $data; 35 | 36 | /** 37 | * HeapSort constructor. 38 | * 39 | * @param array $data 40 | */ 41 | public function __construct(array $data) 42 | { 43 | $this->count = count($data); 44 | $this->data = $data; 45 | } 46 | 47 | /** 48 | * Action 49 | * 50 | * @return array 51 | */ 52 | public function run() 53 | { 54 | $this->createHeap(); 55 | while ($this->count > 0) { 56 | /* 这是一个大顶堆 , 所以堆顶的节点必须是最大的 57 | 根据此特点 , 每次都将堆顶数据移到最后一位 58 | 然后对剩余数据节点再次建造堆就可以 */ 59 | $this->swap($this->data[0], $this->data[--$this->count]); 60 | $this->buildHeap($this->data, 0, $this->count); 61 | } 62 | return $this->data; 63 | } 64 | 65 | /** 66 | * 创建一个堆 67 | */ 68 | public function createHeap() 69 | { 70 | $i = floor($this->count / 2) + 1; 71 | while ($i--) { 72 | $this->buildHeap($this->data, $i, $this->count); 73 | } 74 | } 75 | 76 | /** 77 | * 从 数组 的第 $i 个节点开始至 数组长度为0 结束 , 递归的将其 ( 包括其子节点 ) 转化为一个小顶堆 78 | * 79 | * @param $data 80 | * @param $i 81 | * @param $count 82 | */ 83 | public function buildHeap(array &$data, $i, $count) 84 | { 85 | if (false === $i < $count) { 86 | return; 87 | } 88 | // 获取左 / 右节点 89 | $right = ($left = 2 * $i + 1) + 1; 90 | $max = $i; 91 | // 如果左子节点大于当前节点 , 那么记录左节点键名 92 | if ($left < $count && $data[$i] < $data[$left]) { 93 | $max = $left; 94 | } 95 | // 如果右节点大于刚刚记录的 $max , 那么再次交换 96 | if ($right < $count && $data[$max] < $data[$right]) { 97 | $max = $right; 98 | } 99 | if ($max !== $i && $max < $count) { 100 | $this->swap($data[$i], $data[$max]); 101 | $this->buildHeap($data, $max, $count); 102 | } 103 | } 104 | 105 | /** 106 | * 交换空间 107 | * 108 | * @param $left 109 | * @param $right 110 | */ 111 | public function swap(&$left, &$right) 112 | { 113 | list($left, $right) = array ($right, $left); 114 | } 115 | } 116 | 117 | // +-------------------------------------------------------------------------- 118 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 119 | // +-------------------------------------------------------------------------- 120 | 121 | $array = array (4, 21, 41, 2, 53, 1, 213, 31, 21, 423, 56); 122 | $result = (new HeapSort($array))->run(); 123 | var_dump($result); 124 | -------------------------------------------------------------------------------- /src/Sort/InsertSort.php: -------------------------------------------------------------------------------- 1 | 6 | * @date 2017/6/17 7 | * @license MIT 8 | * ------------------------------------------------------------- 9 | * 思路分析:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。 10 | * ------------------------------------------------------------- 11 | * 12 | * 算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。 13 | * 插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素, 14 | * 但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。 15 | * 在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。 16 | * 17 | */ 18 | 19 | 20 | // +-------------------------------------------------------------------------- 21 | // | 解题方式 | 这儿,可能有用的解决方案 22 | // +-------------------------------------------------------------------------- 23 | 24 | /** 25 | * InsertSort 26 | * 27 | * @param array $container 28 | * @return array 29 | */ 30 | function InsertSort(array $container) 31 | { 32 | $count = count($container); 33 | for ($i = 1; $i < $count; $i++){ 34 | $temp = $container[$i]; 35 | $j = $i - 1; 36 | // Init 37 | while($j >= 0 && $container[$j] > $temp){ 38 | $container[$j+1] = $container[$j]; 39 | $j--; 40 | } 41 | if($i != $j+1) 42 | $container[$j+1] = $temp; 43 | } 44 | return $container; 45 | } 46 | 47 | 48 | // +-------------------------------------------------------------------------- 49 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 50 | // +-------------------------------------------------------------------------- 51 | var_dump(InsertSort([3, 12, 42, 1, 24, 5, 346, 7])); 52 | 53 | /* 54 | array (size=8) 55 | 0 => int 1 56 | 1 => int 3 57 | 2 => int 5 58 | 3 => int 7 59 | 4 => int 12 60 | 5 => int 24 61 | 6 => int 42 62 | 7 => int 346 63 | */ 64 | -------------------------------------------------------------------------------- /src/Sort/MergeSort.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/7/22 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析: 11 | * 大O表示: O(n log n) 12 | * ------------------------------------------------------------- 13 | * 比较a[i]和b[j]的大小,若a[i]≤b[j],则将第一个有序表中的元素a[i]复制到r[k]中, 14 | * 并令i和k分别加上1;否则将第二个有序表中的元素b[j]复制到r[k]中,并令j和k分别加上1, 15 | * 如此循环下去,直到其中一个有序表取完,然后再将另一个有序表中剩余的元素复制到r中从下标k到下标t的单元。 16 | * 归并排序的算法我们通常用递归实现,先把待排序区间[s,t]以中点二分,接着把左边子区间排序,再把右边子区间排序, 17 | * 最后把左区间和右区间用一次归并操作合并成有序的区间[s,t] 18 | */ 19 | 20 | 21 | // +-------------------------------------------------------------------------- 22 | // | 解题方式 23 | // +-------------------------------------------------------------------------- 24 | 25 | class MergeSort 26 | { 27 | /** 28 | * MergeSort constructor. 29 | * 是开始递归函数的一个驱动函数 30 | * 31 | * @param array $arr 待排序的数组 32 | */ 33 | public function __construct(array $arr) 34 | { 35 | $this->mSort($arr, 0, count($arr) - 1); 36 | var_dump($arr); 37 | } 38 | 39 | /** 40 | * 实际实现归并排序的程序 41 | * 42 | * @param $arr array 需要排序的数组 43 | * @param $left int 子序列的左下标值 44 | * @param $right int 子序列的右下标值 45 | */ 46 | public function mSort(&$arr, $left, $right) 47 | { 48 | if ($left < $right) { 49 | //说明子序列内存在多余1个的元素,那么需要拆分,分别排序,合并 50 | //计算拆分的位置,长度/2 去整 51 | $center = floor(($left + $right) / 2); 52 | //递归调用对左边进行再次排序: 53 | $this->mSort($arr, $left, $center); 54 | //递归调用对右边进行再次排序 55 | $this->mSort($arr, $center + 1, $right); 56 | //合并排序结果 57 | $this->mergeArray($arr, $left, $center, $right); 58 | } 59 | } 60 | 61 | /** 62 | * 将两个有序数组合并成一个有序数组 63 | * 64 | * @param &$arr , 待排序的所有元素 65 | * @param $left , 排序子数组A的开始下标 66 | * @param $center , 排序子数组A与排序子数组B的中间下标,也就是数组A的结束下标 67 | * @param $right , 排序子数组B的结束下标(开始为$center+1) 68 | */ 69 | public function mergeArray(&$arr, $left, $center, $right) 70 | { 71 | echo '| ' . $left . ' - ' . $center . ' - ' . $right . ' - ' . implode(',', $arr) . PHP_EOL; 72 | //设置两个起始位置标记 73 | $a_i = $left; 74 | $b_i = $center + 1; 75 | $temp = []; 76 | 77 | while ($a_i <= $center && $b_i <= $right) { 78 | //当数组A和数组B都没有越界时 79 | if ($arr[ $a_i ] < $arr[ $b_i ]) { 80 | $temp[] = $arr[ $a_i++ ]; 81 | } else { 82 | $temp[] = $arr[ $b_i++ ]; 83 | } 84 | } 85 | //判断 数组A内的元素是否都用完了,没有的话将其全部插入到C数组内: 86 | while ($a_i <= $center) { 87 | $temp[] = $arr[ $a_i++ ]; 88 | } 89 | //判断 数组B内的元素是否都用完了,没有的话将其全部插入到C数组内: 90 | while ($b_i <= $right) { 91 | $temp[] = $arr[ $b_i++ ]; 92 | } 93 | 94 | //将$arrC内排序好的部分,写入到$arr内: 95 | for ($i = 0, $len = count($temp); $i < $len; $i++) { 96 | $arr[ $left + $i ] = $temp[ $i ]; 97 | } 98 | } 99 | } 100 | 101 | 102 | 103 | // +-------------------------------------------------------------------------- 104 | // | 方案测试 105 | // +-------------------------------------------------------------------------- 106 | 107 | //do some test: 108 | new mergeSort([4, 7, 6, 3, 9, 5, 8]); 109 | 110 | /* 111 | 112 | | 0 - 0 - 1 - 4,7,6,3,9,5,8 113 | | 2 - 2 - 3 - 4,7,6,3,9,5,8 114 | | 0 - 1 - 3 - 4,7,3,6,9,5,8 115 | | 4 - 4 - 5 - 3,4,6,7,9,5,8 116 | | 4 - 5 - 6 - 3,4,6,7,5,9,8 117 | | 0 - 3 - 6 - 3,4,6,7,5,8,9 118 | 119 | array(7) { 120 | [0] => 121 | int(3) 122 | [1] => 123 | int(4) 124 | [2] => 125 | int(5) 126 | [3] => 127 | int(6) 128 | [4] => 129 | int(7) 130 | [5] => 131 | int(8) 132 | [6] => 133 | int(9) 134 | } 135 | */ -------------------------------------------------------------------------------- /src/Sort/QuickSort.php: -------------------------------------------------------------------------------- 1 | 6 | * @date 2017/6/17 7 | * @license MIT 8 | * ------------------------------------------------------------- 9 | * 思路分析:从数列中挑出一个元素,称为 “基准”(pivot)  10 | * 大O表示: O(n log n) 最糟 O(n 2) 11 | * ------------------------------------------------------------- 12 | * 重新排序数列,所有元素比基准值小的摆放在基准前面,C 语言中的 qsort就是快速排序 13 | * 所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。 14 | * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 15 | */ 16 | 17 | // +-------------------------------------------------------------------------- 18 | // | 解题方式 19 | // +-------------------------------------------------------------------------- 20 | 21 | /** 22 | * QuickSort 23 | * 24 | * @param array $container 25 | * @return array 26 | */ 27 | function QuickSort(array $container) 28 | { 29 | $count = count($container); 30 | if ($count <= 1) { // 基线条件为空或者只包含一个元素,只需要原样返回数组 31 | return $container; 32 | } 33 | $pivot = $container[0]; // 基准值 pivot 34 | $left = $right = []; 35 | 36 | for ($i = 1; $i < $count; $i++) { 37 | if ($container[$i] < $pivot) { 38 | $left[] = $container[$i]; 39 | } else { 40 | $right[] = $container[$i]; 41 | } 42 | } 43 | $left = QuickSort($left); 44 | $right = QuickSort($right); 45 | return array_merge($left, [$container[0]], $right); 46 | } 47 | 48 | // +-------------------------------------------------------------------------- 49 | // | 方案测试 50 | // +-------------------------------------------------------------------------- 51 | 52 | 53 | var_dump(QuickSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); 54 | /** 55 | * array(10) { 56 | * [0] => 57 | * int(1) 58 | * [1] => 59 | * int(2) 60 | * [2] => 61 | * int(4) 62 | * [3] => 63 | * int(21) 64 | * [4] => 65 | * int(21) 66 | * [5] => 67 | * int(31) 68 | * [6] => 69 | * int(41) 70 | * [7] => 71 | * int(53) 72 | * [8] => 73 | * int(213) 74 | * [9] => 75 | * int(423) 76 | * } 77 | */ 78 | /** 79 | * PS & EX: 80 | * 快速排序使用分而治之【 divide and conquer,D&C 】的策略,D&C 解决问题的过程包括两个步骤 81 | * 1. 找出基线条件,这种条件必须尽可能简单 82 | * 2. 不断将问题分解(或者说缩小规模),直到符合基线条件 83 | * (D&C 并非解决问题的算法,而是一种解决问题的思路) 84 | */ -------------------------------------------------------------------------------- /src/Sort/SelectSort.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/6/17 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * 思路分析:选择排序是不稳定的排序方法 11 | * 大O表示: O(n 2) 12 | * ------------------------------------------------------------- 13 | * 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 14 | * 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。 15 | */ 16 | 17 | 18 | // +-------------------------------------------------------------------------- 19 | // | 解题方式 20 | // +-------------------------------------------------------------------------- 21 | /** 22 | * SelectSort 23 | * 24 | * @param array $container 25 | * @return array 26 | */ 27 | function SelectSort(array $container) 28 | { 29 | $count = count($container); 30 | for ($i = 0; $i < $count; $i++){ 31 | $k = $i; 32 | for ($j = $i + 1; $j < $count; $j++){ 33 | if($container[$j] < $container[$k]){ 34 | $k = $j; 35 | } 36 | } 37 | if($k != $i){ 38 | $temp = $container[$i]; 39 | $container[$i] = $container[$k]; 40 | $container[$k] = $temp; 41 | } 42 | } 43 | return $container; 44 | } 45 | 46 | // +-------------------------------------------------------------------------- 47 | // | 方案测试 48 | // +-------------------------------------------------------------------------- 49 | 50 | 51 | var_dump(SelectSort([3, 12, 42, 1, 24, 5, 346, 7])); 52 | 53 | /* 54 | array(8) { 55 | [0] => 56 | int(1) 57 | [1] => 58 | int(3) 59 | [2] => 60 | int(5) 61 | [3] => 62 | int(7) 63 | [4] => 64 | int(12) 65 | [5] => 66 | int(24) 67 | [6] => 68 | int(42) 69 | [7] => 70 | int(346) 71 | } 72 | */ -------------------------------------------------------------------------------- /src/Sort/ShellSort.php: -------------------------------------------------------------------------------- 1 | 6 | * @date 2017/7/22 7 | * @license Mozilla 8 | * ------------------------------------------------------------- 9 | * 思路分析:希尔排序是基于插入排序的,区别在于插入排序是相邻的一个个比较(类似于希尔中h=1的情形),而希尔排序是距离h的比较和替换。 10 | * ------------------------------------------------------------- 11 | * 希尔排序中一个常数因子n,原数组被分成各个小组,每个小组由h个元素组成,很可能会有多余的元素。 12 | * 当然每次循环的时候,h也是递减的(h=h/n)。第一次循环就是从下标为h开始。希尔排序的一个思想就是,分成小组去排序。 13 | */ 14 | 15 | 16 | // +-------------------------------------------------------------------------- 17 | // | 解题方式 | 这儿,可能有用的解决方案 18 | // +-------------------------------------------------------------------------- 19 | 20 | 21 | /** 22 | * ShellSort 23 | * 24 | * @param array $container 25 | * @return array 26 | */ 27 | function ShellSort(array $container) 28 | { 29 | $count = count($container); 30 | for ($increment = intval($count / 2); $increment > 0; $increment = intval($increment / 2)) { 31 | for ($i = $increment; $i < $count; $i++) { 32 | $temp = $container[$i]; 33 | for ($j = $i; $j >= $increment; $j -= $increment) { 34 | if ($temp < $container[$j - $increment]) { 35 | $container[$j] = $container[$j - $increment]; 36 | } else { 37 | break; 38 | } 39 | } 40 | $container[$j] = $temp; 41 | } 42 | } 43 | return $container; 44 | } 45 | 46 | 47 | // +-------------------------------------------------------------------------- 48 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 49 | // +-------------------------------------------------------------------------- 50 | 51 | 52 | var_dump(ShellSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/Sort/ShuttleSort.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/12/19 8 | * @version 1.0 9 | * ------------------------------------------------------------- 10 | * 思路分析:飞梭排序是冒泡排序的轻微变形。不同的地方在于,飞梭排序是从低到高然后从高到低来回排序,而冒泡排序则仅从低到高去比较序列里的每个元素。 11 | * ------------------------------------------------------------- 12 | * 先对数组从左到右进行冒泡排序(升序),则最大的元素去到最右端 13 | * 再对数组从右到左进行冒泡排序(降序),则最小的元素去到最左端 14 | * 以此类推,依次改变冒泡的方向,并不断缩小未排序元素的范围,直到最后一个元素结束 15 | */ 16 | 17 | 18 | // +-------------------------------------------------------------------------- 19 | // | 解题方式 | 这儿,可能有用的解决方案 20 | // +-------------------------------------------------------------------------- 21 | 22 | 23 | /** 24 | * ShuttleSort 25 | * 26 | * @param array $data 27 | * @return array 28 | */ 29 | function ShuttleSort(array $data) 30 | { 31 | /** 32 | * 替换方法 33 | * 34 | * @param array $data 35 | * @param $i 36 | * @param $j 37 | * @return array 38 | */ 39 | $swap = function (array &$data, $i, $j) { 40 | $temp = $data[$i]; 41 | $data[$i] = $data[$j]; 42 | $data[$j] = $temp; 43 | return $data; 44 | }; 45 | 46 | $count = count($data); 47 | $left = 0; 48 | $right = $count - 1; 49 | 50 | while ($left < $right) { 51 | // 从左到右 52 | $lastRight = 0; 53 | for ($i = $left; $i < $right; $i++) { 54 | if ($data[$i] > $data[$i + 1]) { 55 | $swap($data, $i, 1 + $i); 56 | $lastRight = $i; 57 | } 58 | } 59 | $right = $lastRight; 60 | // 从右到左 61 | $lastLeft = 0; 62 | for ($j = $right; $left < $j; $j--) { 63 | if ($data[$j - 1] > $data[$j]) { 64 | $swap($data, $j - 1, $j); 65 | $lastLeft = $j; 66 | } 67 | } 68 | $left = $lastLeft; 69 | } 70 | return $data; 71 | } 72 | 73 | // +-------------------------------------------------------------------------- 74 | // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` 75 | // +-------------------------------------------------------------------------- 76 | 77 | 78 | var_dump(ShuttleSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); 79 | -------------------------------------------------------------------------------- /src/Structure/BinarySearchTree.php: -------------------------------------------------------------------------------- 1 | value = $data; 32 | $node->left = null; 33 | $node->right = null; 34 | return $node; 35 | } 36 | 37 | 38 | /** 39 | * 插入节点 40 | * @param $node 根节点 41 | * @param $value 关键值 42 | */ 43 | public function insert(&$node, $value) 44 | { 45 | if(empty($value) && $value !== 0) { 46 | return ; 47 | } 48 | 49 | if ($node == null) { 50 | $node = $this->createNode($value); 51 | } else if ($value < $node->value) { 52 | $this->insert($node->left, $value); 53 | } else { 54 | $this->insert($node->right, $value); 55 | } 56 | } 57 | 58 | /** 59 | * 先序遍历 60 | * @param $node 根节点 61 | */ 62 | public function preOrder(&$node) 63 | { 64 | if ($node != null) { 65 | echo $node->value . PHP_EOL ; 66 | $this->preOrder($node->left); 67 | $this->preOrder($node->right); 68 | } 69 | 70 | } 71 | /** 72 | * 中序遍历 73 | * @param $node 根节点 74 | */ 75 | public function middleOrder(&$node) 76 | { 77 | if ($node != null) { 78 | $this->middleOrder($node->left); 79 | echo $node->value . PHP_EOL ; 80 | $this->middleOrder($node->right); 81 | } 82 | 83 | } 84 | 85 | /** 86 | * 后序遍历 87 | * @param $node 根节点 88 | */ 89 | public function afterOrder(&$node) 90 | { 91 | if ($node != null) { 92 | $this->afterOrder($node->left); 93 | $this->afterOrder($node->right); 94 | echo $node->value . PHP_EOL; 95 | } 96 | } 97 | 98 | /** 99 | * 获取最大值 100 | * @param $node 根节点 101 | */ 102 | public function findMax(&$node) 103 | { 104 | while($node->right != null) { 105 | $node = $node->right; 106 | } 107 | return $node->value; 108 | } 109 | 110 | } 111 | 112 | $tree = new BinarySearchTree(); 113 | $tree->insert($tree->root, 3); 114 | $tree->insert($tree->root, 9); 115 | $tree->insert($tree->root, 2); 116 | $tree->insert($tree->root, 20); 117 | 118 | echo "先序遍历".PHP_EOL; 119 | $tree->preOrder($tree->root); //324 120 | echo "中序遍历" . PHP_EOL; 121 | 122 | $tree->middleOrder($tree->root); //324 123 | echo "后序遍历" . PHP_EOL; 124 | 125 | $tree->afterOrder($tree->root); //234 126 | 127 | $max = $tree->findMax($tree->root); 128 | 129 | var_dump($max); -------------------------------------------------------------------------------- /src/Structure/KitchenQueue.php: -------------------------------------------------------------------------------- 1 | 12 | * @date 2017/12/3 13 | * @version 1.0 14 | * @license MIT 15 | */ 16 | 17 | class KitchenQueue 18 | { 19 | /** 20 | * @var \stdClass $cooking 21 | */ 22 | protected $cooking; 23 | 24 | /** 25 | * 服务员 26 | * 27 | * @param $dishes 28 | */ 29 | public function waiter($dishes) 30 | { 31 | $node = new \stdClass(); 32 | $node->element = $dishes; 33 | $node->next = $this->cooking; 34 | $this->cooking = $node; 35 | } 36 | 37 | /** 38 | * 厨师 39 | * 40 | * @return \stdClass 41 | */ 42 | public function kitchen() 43 | { 44 | return $this->cooking; 45 | } 46 | } 47 | 48 | $kitchen = new KitchenQueue(); 49 | $kitchen->waiter("Qin Jiao Rou Si"); 50 | $kitchen->waiter("Ma Po Dou Fu"); 51 | $kitchen->waiter("Fu Qi Fei Pian"); 52 | $kitchen->waiter("Kou Shui Ji"); 53 | var_dump($kitchen->kichen()); 54 | -------------------------------------------------------------------------------- /src/Structure/LinearChain.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/9/29 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * [基本说明] 11 | * ======= 12 | * 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的 13 | * 注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储) 14 | * 但是把最后一个数据元素的尾指针指向了首位结点)。 15 | * [基本特点] 16 | * ======= 17 | * - 存在一个唯一的被称为`第一个`的数据元素 18 | * - 存在一个唯一的被称为`最后一个`的数据元素 19 | * - 除第一个元素外,每个元素均有唯一一个直接前驱 20 | * - 除最后一个元素外,每个元素均有唯一一个直接后继 21 | * ------------------------------------------------------------- 22 | * [定义] 23 | * ======= 24 | * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 25 | * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 26 | * 当n=0时,称为空表。 27 | * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 28 | * ------------------------------------------------------------- 29 | * [线性表单链存储] 30 | * ======= 31 | * 用一组任意的存储单元存储线性表中的数据元素,用这种方法存储的线性表简称线性链表。 32 | * ------------------------------------------------------------- 33 | * [单链存储的线性表的特点] 34 | * ======= 35 | * - 存储链表中结点的一组任意的存储单元可以是连续的,也可以是不连续的,甚至是零散分布在内存中的任意位置上 36 | * - 链表中结点的逻辑顺序和物理顺序不一定相同 37 | * ------------------------------------------------------------- 38 | */ 39 | class LinearChain 40 | { 41 | /** 42 | * @var string 下一结点指针 43 | */ 44 | public $next; 45 | 46 | /** 47 | * @var string 头结点数据 48 | */ 49 | public $elem; 50 | 51 | /** 52 | * @var int 链表长度 53 | */ 54 | public $length; 55 | 56 | /** 57 | * LinearChain constructor. 线性表初始化 58 | */ 59 | public function __construct() 60 | { 61 | $this->next = $this->elem = $this->length = null; 62 | } 63 | 64 | /** 65 | * 清空单链表 66 | * 67 | * @return mixed 68 | */ 69 | public function clearChain() 70 | { 71 | if ($this->length <= 0) { 72 | return false; 73 | } 74 | while ($this->next != null) { 75 | $q = $this->next->next; 76 | $this->next = null; 77 | unset($this->next); 78 | $this->next = $q; 79 | } 80 | $this->length = 0; 81 | } 82 | 83 | /** 84 | * 返回单链表长度 85 | * 86 | * @return mixed 87 | */ 88 | public function getLength() 89 | { 90 | return $this->length; 91 | } 92 | 93 | /** 94 | * 判断单链表是否为空 95 | * 96 | * @return bool 为空返回true,不为空返回false 97 | */ 98 | public function getIsEmpty() 99 | { 100 | return $this->length == 0 && $this->next == null; 101 | } 102 | 103 | /** 104 | * 头插入法建表 105 | * 106 | * @param array $arr 建立单链表的数据 107 | * @return mixed 108 | */ 109 | protected function getHeadCreateChain(array $arr) 110 | { 111 | $this->clearChain(); 112 | $iterator = $this->generator($arr); 113 | $iterator->rewind(); 114 | while ($iterator->valid()) { 115 | $node = new stdClass(); 116 | $node->elem = $iterator->current(); 117 | $node->next = $this->next; 118 | $this->next = $node; 119 | $this->length++; 120 | $iterator->next(); 121 | } 122 | return $this->next; 123 | } 124 | 125 | /** 126 | * 尾插入法建表 127 | * 128 | * @param array $arr 建立单链表的数据 129 | * @return mixed 130 | */ 131 | protected function getTailCreateChain(array $arr) 132 | { 133 | $this->clearChain(); 134 | $self = $this; 135 | $iterator = $this->generator($arr); 136 | $iterator->rewind(); 137 | while ($iterator->valid()) { 138 | $node = new stdClass(); 139 | $node->elem = $iterator->current(); 140 | $node->next = $self->next; 141 | $self->next = $node; 142 | $self = $node; 143 | $iterator->next(); 144 | $this->length++; 145 | } 146 | return $this->next; 147 | } 148 | 149 | /** 150 | * 返回第$i个元素 151 | * 152 | * @param int $i 元素位序,从1开始 153 | * @return mixed 154 | */ 155 | protected function getElemForPos($i) 156 | { 157 | $i = (int)$i; 158 | if ($i > $this->length || $i < 1) { 159 | return null; 160 | } 161 | $mark = 1; 162 | $self = $this->next; 163 | while ($mark < $i) { 164 | $box = $self->next; 165 | $self = $box; 166 | $mark++; 167 | } 168 | return $self; 169 | } 170 | 171 | /** 172 | * 查找单链表中是否存在某个值的元素 173 | * 如果有返回该元素结点,否则返回null 174 | * 175 | * @param mixed $value 查找的值 176 | * @return mixed 177 | */ 178 | protected function getElemIsExist($value) 179 | { 180 | $self = $this; 181 | while ($self->next != null && strcmp($self->elem, $value) !== 0) { 182 | $self = $self->next; 183 | } 184 | if (strcmp($self->elem, $value) === 0) { 185 | return $self; 186 | } 187 | return null; 188 | } 189 | 190 | /** 191 | * 查找单链表中是否存在某个值的元素 192 | * 如果有返回该元素位序,否则返回-1 193 | * 194 | * @param mixed $value 查找的值 195 | * @return mixed 196 | */ 197 | protected function getElemPosition($value) 198 | { 199 | $self = $this; 200 | $mark = 0; 201 | while ($self->next != null && strcmp($self->elem, $value) !== 0) { 202 | $self = $self->next; 203 | $mark++; 204 | } 205 | if (strcmp($self->elem, $value) === 0) { 206 | return $mark; 207 | } 208 | return -1; 209 | } 210 | 211 | /** 212 | * 单链表的插入操作 213 | * 214 | * @param int $key 插入元素的位序,即在什么位置插入新的元素,从1开始 215 | * @param mixed $value 插入的新的元素值 216 | * @return boolean 插入成功返回true,失败返回false 217 | */ 218 | protected function getInsertElem($key, $value) 219 | { 220 | if ($key > $this->length || $key < 1) { 221 | return false; 222 | } 223 | $mark = 1; 224 | $self = $this; 225 | while ($self->next != null && $mark < $key) { 226 | $self = $self->next; 227 | $mark++; 228 | } 229 | $node = new stdClass(); 230 | $node->elem = $value; 231 | $node->next = $self->next; 232 | $self->next = $node; 233 | $this->length++; 234 | return true; 235 | } 236 | 237 | /** 238 | * 遍历单链表中的所有元素 239 | * 240 | * @return array 包括单链中的所有元素 241 | */ 242 | protected function getAllElem() 243 | { 244 | $result = array (); 245 | if ($this->getIsEmpty()) { 246 | return $result; 247 | } 248 | $self = $this->next; 249 | while ($self->next != null) { 250 | array_push($result, $self->elem); 251 | $self = $self->next; 252 | } 253 | array_push($result, $self->elem); 254 | return $result; 255 | } 256 | 257 | /** 258 | * 根据Key 删除单链中的元素 259 | * 260 | * @param int $key 元素位序 261 | * @return boolean 删除成功返回true,失败返回false 262 | */ 263 | protected function getDeleteElem($key) 264 | { 265 | $key = (int)$key; 266 | if ($key > $this->length || $key < 1) { 267 | return false; 268 | } 269 | $self = $this; 270 | $mark = 1; 271 | while ($mark < $key) { 272 | $self = $self->next; 273 | $mark++; 274 | } 275 | $node = $self->next; 276 | $self->next = $node->next; 277 | $this->length--; 278 | return true; 279 | } 280 | 281 | /** 282 | * 删除单链表中值为$value的前 $i($i>=1) 个结点 283 | * 284 | * @param mixed mixed 待查找的值 285 | * @param $i mixed 删除的次数,即删除查找到的前$i个 286 | * @return mixed 287 | */ 288 | protected function getDeleteElemForValue($value, $i = 1) 289 | { 290 | if ($i > 1) { 291 | $this->getDeleteElemForValue($value, $i - 1); 292 | } 293 | $vp = $this->getElemPosition($value); 294 | $this->getDeleteElem($vp); 295 | return $this->getAllElem(); 296 | } 297 | 298 | /** 299 | * 删除单链表所有重复的值 300 | * 301 | * @return mixed 302 | */ 303 | protected function getElemUnique() 304 | { 305 | if ($this->getIsEmpty()) { 306 | return $this->getAllElem(); 307 | } 308 | $self = $this; 309 | while ($self->next != null) { 310 | $node = $self->next; 311 | $ptr = $self; 312 | while ($node->next != null) { 313 | if (strcmp($self->elem, $node->elem) === 0) { 314 | $ptr->next = $node->next; 315 | unset($node->next); 316 | $node = $ptr->next; 317 | $this->length--; 318 | } else { 319 | $ptr = $node; 320 | $node = $node->next; 321 | } 322 | } 323 | $self = $self->next; 324 | } 325 | return $this->getAllElem(); 326 | } 327 | 328 | /** 329 | * 迭代器生产 330 | * 331 | * @param array $info 332 | * @return \ArrayIterator 333 | */ 334 | protected function generator(array $info) 335 | { 336 | return (new ArrayObject($info))->getIterator(); 337 | } 338 | 339 | /** 340 | * 调试用请无视 341 | * 342 | * @param $name 343 | * @param $arguments 344 | * @return mixed 345 | */ 346 | public function __call($name, $arguments) 347 | { 348 | $this->preDispatch(); // 调试用,请无视 349 | return call_user_func_array(array ($this, $name), $arguments); 350 | } 351 | 352 | /** 353 | * 调试用请无视! 354 | * 355 | * @param bool $isDebug 356 | * @return bool 357 | */ 358 | protected function preDispatch($isDebug = true) 359 | { 360 | if (!$isDebug) { 361 | return false; 362 | } 363 | $debug = debug_backtrace()[1]; 364 | $reflection = new ReflectionMethod($this, $debug['args'][0]); 365 | $args = ''; 366 | if (isset($debug['args'][1])) { 367 | foreach ($debug['args'][1] as &$value) { 368 | if (is_array($value)) { 369 | $args .= json_encode($debug['args'][1]) . ', '; 370 | } else { 371 | $args .= $value . ', '; 372 | } 373 | } 374 | } 375 | $args = trim($args, ', '); 376 | echo "\t" . $reflection->getDocComment() . PHP_EOL; 377 | echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; 378 | } 379 | } 380 | 381 | $echo = function ($str, $action) { 382 | echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; 383 | echo "--------------------------- " . PHP_EOL; 384 | }; 385 | $personal = array ( 386 | "One", 387 | "Two", 388 | "Three", 389 | "Four", 390 | "Five", 391 | ); 392 | 393 | $oll = new LinearChain(); 394 | $echo('头插入链表数据', $oll->getHeadCreateChain($personal)); 395 | $echo('尾插入链表数据', $oll->getTailCreateChain($personal)); 396 | $echo('返回第二个数据', $oll->getElemForPos(2)); 397 | $echo('是否存在Tow呢?', $oll->getElemIsExist("Two")); 398 | $echo('One 的下标示是', $oll->getElemPosition("One")); 399 | $echo('从2号位插入一个Four', $oll->getInsertElem(2, "Four")); 400 | $echo('遍历整个单链表', $oll->getAllElem()); 401 | $echo('删除第一个元素', $oll->getDeleteElem(1)); 402 | $echo('删除Three 前一个', $oll->getDeleteElemForValue("Three", 1)); 403 | $echo('去重链表中重复值', $oll->getElemUnique()); -------------------------------------------------------------------------------- /src/Structure/LinearOrder.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/9/29 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * [基本说明] 11 | * ======= 12 | * 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的 13 | * 注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储) 14 | * 但是把最后一个数据元素的尾指针指向了首位结点)。 15 | * [基本特点] 16 | * ======= 17 | * - 存在一个唯一的被称为`第一个`的数据元素 18 | * - 存在一个唯一的被称为`最后一个`的数据元素 19 | * - 除第一个元素外,每个元素均有唯一一个直接前驱 20 | * - 除最后一个元素外,每个元素均有唯一一个直接后继 21 | * ------------------------------------------------------------- 22 | * [定义] 23 | * ======= 24 | * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 25 | * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 26 | * 当n=0时,称为空表。 27 | * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 28 | * ------------------------------------------------------------- 29 | * [线性表顺序存储] 30 | * ======= 31 | * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称线性表。 32 | * ------------------------------------------------------------- 33 | * [顺序存储的线性表的特点] 34 | * ======= 35 | * - 线性表的逻辑顺序与物理顺序一致; 36 | * - 数据元素之间的关系是以元素在计算机内“物理位置相邻”来体现。 37 | * ------------------------------------------------------------- 38 | * @param array 39 | */ 40 | class LinearOrder extends ArrayObject 41 | { 42 | const PRECURSOR_KEY = 0; 43 | const PRECURSOR_VALUE = 1; 44 | 45 | const SUBSEQUENT_KEY = 0; 46 | const SUBSEQUENT_VALUE = 1; 47 | 48 | const ASSIGN_KEY = 0; 49 | const DEFAULT_KEY = 1; 50 | 51 | const DELETE_KEY = 0; 52 | const DELETE_VALUE = 1; 53 | 54 | /** 55 | * @var array|mixed 线性表 56 | */ 57 | public $oll; 58 | 59 | /** 60 | * LinearList constructor. 线性表初始化 61 | * 62 | * @param array $oll 63 | */ 64 | public function __construct($oll = array ()) 65 | { 66 | echo '---------------------------'.PHP_EOL; 67 | echo var_export($oll).PHP_EOL; 68 | echo '---------------------------'.PHP_EOL; 69 | parent::__construct($oll); 70 | $this->oll = $this->getIterator(); 71 | } 72 | 73 | /** 74 | * @return void 清空线性表 75 | */ 76 | public function __destruct() 77 | { 78 | unset($this->oll); 79 | } 80 | 81 | /** 82 | * 调试用请无视 83 | * 84 | * @param $name 85 | * @param $arguments 86 | * @return mixed 87 | */ 88 | public function __call($name, $arguments) 89 | { 90 | $this->preDispatch(); // 调试用,请无视 91 | return call_user_func_array(array($this, $name), $arguments); 92 | } 93 | 94 | /** 95 | * 判断线性表是否为空 96 | * 97 | * @return boolean 为空返回true,否则返回false 98 | */ 99 | protected function isEmpty() 100 | { 101 | return $this->getLength() > 0 ? false : true; 102 | } 103 | 104 | /** 105 | * 返回线性表的长度 106 | * 107 | * @return int 108 | */ 109 | protected function getLength() 110 | { 111 | return $this->oll->count(); 112 | } 113 | 114 | /** 115 | * 返回线性表中下标为$key的元素 116 | * 117 | * @param mixed $key 线性表元素的下标 118 | * @return mixed 119 | */ 120 | protected function getElement($key) 121 | { 122 | return $this->oll->offsetGet($key); 123 | } 124 | 125 | /** 126 | * 返回线性表中某个元素的位置 127 | * 128 | * @param mixed $value 线性表中某个元素的值 129 | * @return int 从1开始,如果返回-1表示不存在该元素 130 | */ 131 | protected function getElementPosition($value) 132 | { 133 | $i = 0; 134 | $this->oll->rewind(); 135 | while ($this->oll->valid()) { 136 | $i++; 137 | if (strcmp($value, $this->oll->current()) === 0) { 138 | return $i; 139 | } 140 | $this->oll-> next(); 141 | } 142 | return -1; 143 | } 144 | 145 | /** 146 | * 返回线性表中某个元素的直接前驱元素 147 | * 148 | * @param string $value 线性表中某个元素的值 149 | * @param int $tag 如果$value为下标则为1, 如果$value为元素值则为0 150 | * @return array|bool array('value'=>...)直接前驱元素值,array('key'=>...)直接前驱元素下标 151 | */ 152 | protected function getElementPrecursor($value, $tag = self::PRECURSOR_VALUE) 153 | { 154 | $i = 0; 155 | $prev = null; 156 | $this->oll->rewind(); 157 | while ($this->oll->valid()) { 158 | $key = $this->oll->key(); 159 | $current = $this->oll->current(); 160 | if (strcmp($key, $value) === 0) { 161 | if ($i == 1) { 162 | return false; 163 | } 164 | return array ('value' => $this->getElement($prev), 'key' => $prev); 165 | } 166 | if ($tag == self::PRECURSOR_VALUE) { 167 | if (strcmp($current, $value) === 0) { 168 | if ($i == 1) { 169 | return false; 170 | } 171 | return array ('value' => $this->getElement($prev), 'key' => $prev); 172 | } 173 | } 174 | $i++; 175 | $prev = $this->oll->key(); 176 | $this->oll->next(); 177 | } 178 | } 179 | 180 | /** 181 | * 返回某个元素的直接后继元素 182 | * 183 | * @param string $value $value线性表中某个元素的值 184 | * @param int $tag 如果$value为下标则为1,如果$value为元素值则为0 185 | * @return array|bool array('value'=>...)直接后继元素值,array('key'=>...)直接后继元素下标 186 | */ 187 | protected function getElementSubsequent($value, $tag = self::SUBSEQUENT_KEY) 188 | { 189 | $i = 0; 190 | $len = $this->getLength(); 191 | $this->oll->rewind(); 192 | while ($this->oll->valid()) { 193 | $key = $this->oll->key(); 194 | $current = $this->oll->current(); 195 | if ($tag == self::SUBSEQUENT_KEY) { 196 | if (strcmp($key, $value) == 0) { 197 | if ($i == $len) { 198 | return false; 199 | } 200 | $this->oll->next(); 201 | return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); 202 | } 203 | } 204 | if ($tag == self::SUBSEQUENT_VALUE) { 205 | if (strcmp($current, $value) == 0) { 206 | if ($i == $len) { 207 | return false; 208 | } 209 | $this->oll->next(); 210 | return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); 211 | } 212 | } 213 | $i++; 214 | $this->oll->next(); 215 | } 216 | return false; 217 | } 218 | 219 | /** 220 | * 在指定位置插入一个新的结点 221 | * 222 | * @param string $p 新结点插入位置,从0开始 223 | * @param string $value 线性表新结点的值 224 | * @param null $key 线性表新结点的下标 225 | * @param int $tag 是否指定新结点的下标,1表示默认下标,0表示指定下标 226 | * @return bool 插入成功返回true,失败返回false 227 | */ 228 | protected function getInsertElement($p, $value, $key = null, $tag = self::DEFAULT_KEY) 229 | { 230 | $p = (int)$p; 231 | $i = 0; 232 | if ($p > $this->getLength() || $p < 1) { 233 | return false; 234 | } 235 | $this->oll->rewind(); 236 | while ($this->oll->valid()) { 237 | if ($i != $p) { 238 | $i++; 239 | $this->oll->next(); 240 | } 241 | switch ($tag){ 242 | case self::DEFAULT_KEY: 243 | $this->oll->append($value); 244 | break 2; 245 | case self::ASSIGN_KEY: 246 | $this->oll->offsetSet($key, $value); 247 | break 2; 248 | } 249 | } 250 | return true; 251 | } 252 | 253 | /** 254 | * 根据元素位置返回线性表中的某个元素 255 | * 256 | * @param mixed $position 元素位置从1开始 257 | * @return array|bool array('value'=>...)元素值,array('key'=>...)元素下标 258 | */ 259 | protected function getElemForPos($position) 260 | { 261 | $i = 0; 262 | $len = $this->getLength(); 263 | $position = (int)$position; 264 | if ($position > $len || $position < 1) { 265 | return false; 266 | } 267 | $this->oll->rewind(); 268 | while ($this->oll->valid()) { 269 | if ($i == $position) { 270 | return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); 271 | } 272 | $i++; 273 | $this->oll->next(); 274 | } 275 | } 276 | 277 | /** 278 | * 根据下标或者元素值删除线性表中的某个元素 279 | * 280 | * @param mixed $value 元素下标或者值 281 | * @param int $tag 0表示$value为下标,1表示$value为元素值 282 | * @return bool 成功返回true,失败返回false 283 | */ 284 | protected function getDeleteElement($value, $tag = self::DELETE_KEY) 285 | { 286 | $this->oll->rewind(); 287 | while ($this->oll->valid()) 288 | { 289 | $key = $this->oll->key(); 290 | $current = $this->oll->current(); 291 | if ($tag == self::DELETE_KEY) { 292 | if (strcmp($key, $value) === 0) { 293 | $this->oll->offsetUnset($key); 294 | } 295 | } 296 | if ($tag == self::DELETE_VALUE) { 297 | if (strcmp($current, $value) === 0) { 298 | $this->oll->offsetUnset($key); 299 | } 300 | } 301 | $this->oll->next(); 302 | } 303 | return true; 304 | } 305 | 306 | /** 307 | * 根据元素位置删除线性表中的某个元素 308 | * 309 | * @param int $position 元素位置从1开始 310 | * @return bool 成功返回true,失败返回false 311 | */ 312 | protected function getDeleteEleForPos($position) 313 | { 314 | $len = $this->getLength(); 315 | $i = 0; 316 | $position = (int)$position; 317 | if ($position > $len || $position < 1) { 318 | return false; 319 | } 320 | $this->oll->rewind(); 321 | while ($this->oll->valid()) { 322 | $key = $this->oll->key(); 323 | if ($i == $position) { 324 | $this->oll->offsetUnset($key); 325 | } 326 | $i++; 327 | $this->oll->next(); 328 | } 329 | return true; 330 | } 331 | 332 | /** 333 | * 调试用 334 | * 335 | * @param bool $isDebug 336 | * @return bool 337 | */ 338 | protected function preDispatch($isDebug = true) 339 | { 340 | if (!$isDebug) { 341 | return false; 342 | } 343 | $debug = debug_backtrace()[1]; 344 | $reflection = new ReflectionMethod($this, $debug['args'][0]); 345 | $args = ''; 346 | if(isset($debug['args'][1])){ 347 | foreach ($debug['args'][1] as &$value){ 348 | if( is_array($value )){ 349 | $args .= json_encode($debug['args'][1]).', '; 350 | }else{ 351 | $args .= $value.', '; 352 | } 353 | } 354 | } 355 | $args = trim($args,', '); 356 | echo "\t".$reflection->getDocComment() . PHP_EOL; 357 | echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; 358 | } 359 | } 360 | 361 | $echo = function ($str, $action) { 362 | echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; 363 | echo "--------------------------- " . PHP_EOL; 364 | }; 365 | 366 | $oll = new LinearOrder(array ('name' => 'Jack', 10, "age", 'msg' => 10, 666)); 367 | $echo('判断线性表是否为空', $oll->isEmpty()); 368 | $echo('返回线性表的长度', $oll->getLength()); 369 | $echo('根据下标返回线性表中的某个元素', $oll->getElement(1)); 370 | $echo('返回线性表中某个元素的位置', $oll->getElementPosition(666)); 371 | $echo('返回线性表中某个元素的直接前驱元素', $oll->getElementPrecursor(666, LinearOrder::PRECURSOR_VALUE)); 372 | $echo('返回线性表中某个元素的直接后继元素', $oll->getElementSubsequent(0, LinearOrder::SUBSEQUENT_KEY)); 373 | $echo('根据元素位置返回线性表中的某个元素', $oll->getElemForPos(2)); 374 | $echo('根据下标或者元素值删除线性表中的某个元素', $oll->getDeleteElement('name', LinearOrder::DELETE_KEY)); 375 | $echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", "qzone", LinearOrder::ASSIGN_KEY)); 376 | $echo('$oll->oll的内容 ', $oll->oll); -------------------------------------------------------------------------------- /src/Structure/StackExample.php: -------------------------------------------------------------------------------- 1 | 7 | * @date 2017/10/16 8 | * @license MIT 9 | * ------------------------------------------------------------- 10 | * [栈的定义] 11 | * ======= 12 | * 栈(Stack):是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。 13 | * 栈顶(Top):允许进行插入、删除操作的一端,又称为表尾。用栈顶指针(top)来指示栈顶元素。 14 | * 栈底(Bottom):是固定端,又称为表头。 15 | * 空栈:当表中没有元素时称为空栈。 16 | * [栈的实现方式] 17 | * ======= 18 | * - 硬堆栈:利用CPU中的某些寄存器组或类似的硬件或使用内存的特殊区域来实现。这类堆栈容量有限,但速度很快; 19 | * - 软堆栈:这类堆栈主要在内存中实现。堆栈容量可以达到很大。在实现方式上,又有动态方式和静态方式两种 20 | * ------------------------------------------------------------- 21 | * [定义] 22 | * ======= 23 | * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 24 | * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 25 | * 当n=0时,称为空表。 26 | * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 27 | * ------------------------------------------------------------- 28 | * [线性表顺序存储] 29 | * ======= 30 | * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称线性表。 31 | * ------------------------------------------------------------- 32 | * [顺序存储的线性表的特点] 33 | * ======= 34 | * - 线性表的逻辑顺序与物理顺序一致; 35 | * - 数据元素之间的关系是以元素在计算机内“物理位置相邻”来体现。 36 | * ------------------------------------------------------------- 37 | * @param array 38 | */ 39 | class StackExample 40 | { 41 | /** 42 | * @var null 栈元素 43 | */ 44 | protected $elem; 45 | /** 46 | * @var null 下一个节点 47 | */ 48 | protected $next; 49 | /** 50 | * @var int 栈长度 51 | */ 52 | protected $length; 53 | 54 | /** 55 | * 初始化栈 56 | * StackExample constructor. 57 | */ 58 | public function __construct() 59 | { 60 | $this->elem = $this->next = null; 61 | $this->length = 0; 62 | } 63 | 64 | /** 65 | * 判断栈是否空栈 66 | * 67 | * @return boolean 如果为空栈返回true,否则返回false 68 | */ 69 | protected function getIsEmpty() 70 | { 71 | return $this->elem ? false : true; 72 | } 73 | 74 | /** 75 | * 将所有元素出栈 76 | * 77 | * @return array 返回所有栈内元素 78 | */ 79 | protected function getAllPopStack() 80 | { 81 | $result = array (); 82 | if ($this->getIsEmpty()) { 83 | return $result; 84 | } 85 | while ($this->elem != null) { 86 | $result[] = $this->elem->elem; 87 | $this->elem = $this->elem->next; 88 | } 89 | $this->length = 0; 90 | return $result; 91 | } 92 | 93 | /** 94 | * 返回栈内元素个数 95 | * 96 | * @return int 97 | */ 98 | protected function getLength() 99 | { 100 | return $this->length; 101 | } 102 | 103 | /** 104 | * 元素进栈 105 | * 106 | * @param mixed $element 进栈元素值 107 | * @return void 108 | **/ 109 | protected function setPushStack($element) 110 | { 111 | $stack = new stdClass(); 112 | $stack->elem = $element; 113 | $stack->next = $this->elem; 114 | $this->elem = &$stack; 115 | $this->length++; 116 | } 117 | 118 | /** 119 | * 元素出栈 120 | * 121 | * @return boolean 出栈成功返回true,否则返回false 122 | **/ 123 | protected function getPopStack() 124 | { 125 | if ($this->getIsEmpty()) { 126 | return false; 127 | } 128 | $node = $this->elem; 129 | $this->elem = $node->next; 130 | $this->length--; 131 | } 132 | 133 | /** 134 | * 仅返回栈内所有元素 135 | * 136 | * @return array 栈内所有元素组成的一个数组 137 | */ 138 | protected function getAllElem() 139 | { 140 | $result = array (); 141 | if ($this->getIsEmpty()) { 142 | return $result; 143 | } 144 | $node = $this->elem; 145 | while ($node != null) { 146 | $result[] = $node->elem; 147 | $node = $node->next; 148 | } 149 | return $result; 150 | } 151 | 152 | /** 153 | * 返回栈内某个元素的个数 154 | * 155 | * @param mixed $elem 待查找的元素的值 156 | * @return int 157 | **/ 158 | protected function getCountForElem($elem) 159 | { 160 | $result = $this->getAllElem(); 161 | $count = 0; 162 | foreach ($result as $value) { 163 | if ($elem === $value) { 164 | $count++; 165 | } 166 | } 167 | return $count; 168 | } 169 | 170 | /** 171 | * 调试用请无视 172 | * 173 | * @param $name 174 | * @param $arguments 175 | * @return mixed 176 | */ 177 | public function __call($name, $arguments) 178 | { 179 | $this->preDispatch(); // 调试用,请无视 180 | return call_user_func_array(array ($this, $name), $arguments); 181 | } 182 | 183 | /** 184 | * 调试用 185 | * 186 | * @param bool $isDebug 187 | * @return bool 188 | */ 189 | protected function preDispatch($isDebug = true) 190 | { 191 | if (!$isDebug) { 192 | return false; 193 | } 194 | $debug = debug_backtrace()[1]; 195 | $reflection = new ReflectionMethod($this, $debug['args'][0]); 196 | $args = ''; 197 | if (isset($debug['args'][1])) { 198 | foreach ($debug['args'][1] as &$value) { 199 | if (is_array($value)) { 200 | $args .= json_encode($debug['args'][1]) . ', '; 201 | } else { 202 | $args .= $value . ', '; 203 | } 204 | } 205 | } 206 | $args = trim($args, ', '); 207 | echo "\t" . $reflection->getDocComment() . PHP_EOL; 208 | echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; 209 | } 210 | } 211 | 212 | $echo = function ($str, $action) { 213 | echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; 214 | echo "--------------------------- " . PHP_EOL; 215 | }; 216 | 217 | //$stack = new StackExample(); 218 | //$stack->setPushStack('First'); 219 | //$stack->setPushStack('Second'); 220 | //$echo('返回栈内所有元素', $stack->getAllElem()); 221 | //$stack->setPushStack('Third'); 222 | //$echo('返回栈内所有元素', $stack->getAllElem()); 223 | //$stack->getPopStack(); 224 | //$echo('返回栈内所有元素', $stack->getAllElem()); 225 | -------------------------------------------------------------------------------- /tests/BootStrapTest.php: -------------------------------------------------------------------------------- 1 | chineseObj = new ChineseTextNumberSort(); 31 | } 32 | 33 | /** 34 | * testValidationModelA 35 | * 36 | * @test 37 | * @throws \Exception 38 | */ 39 | public function testValidationModelA() 40 | { 41 | $this->assertEquals( 42 | $this->chineseObj->extractModel( 43 | ChineseTextNumberSort::MODEL_REGULAR_A, 44 | '第二章 我是Marco小哥哥' 45 | ), 46 | '二' 47 | ); 48 | 49 | $this->assertEquals( 50 | $this->chineseObj->extractModel( 51 | ChineseTextNumberSort::MODEL_REGULAR_A, 52 | '第一节 我是Marco小哥哥' 53 | ), 54 | '一' 55 | ); 56 | 57 | $this->assertEquals( 58 | $this->chineseObj->extractModel( 59 | ChineseTextNumberSort::MODEL_REGULAR_A, 60 | '第二单元 我是Marco小哥哥' 61 | ), 62 | '二' 63 | ); 64 | 65 | $this->assertNotEquals( 66 | $this->chineseObj->extractModel( 67 | ChineseTextNumberSort::MODEL_REGULAR_A, 68 | '第一章 我是Marco小哥哥' 69 | ), 70 | '1' 71 | ); 72 | } 73 | 74 | /** 75 | * testValidationModelB 76 | * 77 | * @throws \Exception 78 | * @test 79 | */ 80 | public function testValidationModelB() 81 | { 82 | $this->assertEquals( 83 | $this->chineseObj->extractModel( 84 | ChineseTextNumberSort::MODEL_REGULAR_B, 85 | '01我是Marco小哥哥' 86 | ), 87 | '01' 88 | ); 89 | 90 | $this->assertEquals( 91 | $this->chineseObj->extractModel( 92 | ChineseTextNumberSort::MODEL_REGULAR_B, 93 | '12我是Marco小哥哥' 94 | ), 95 | '12' 96 | ); 97 | 98 | $this->assertNotEquals( 99 | $this->chineseObj->extractModel( 100 | ChineseTextNumberSort::MODEL_REGULAR_B, 101 | '10章我是Marco小哥哥' 102 | ), 103 | '1' 104 | ); 105 | } 106 | 107 | /** 108 | * testValidationModelC 109 | * 110 | * @throws \Exception 111 | * @test 112 | */ 113 | public function testValidationModelC() 114 | { 115 | $this->assertEquals( 116 | $this->chineseObj->extractModel( 117 | ChineseTextNumberSort::MODEL_REGULAR_C, 118 | '1 我是Marco小哥哥' 119 | ), 120 | 1 121 | ); 122 | 123 | $this->assertEquals( 124 | $this->chineseObj->extractModel( 125 | ChineseTextNumberSort::MODEL_REGULAR_C, 126 | '22 我是Marco小哥哥' 127 | ), 128 | 22 129 | ); 130 | 131 | $this->assertNotEquals( 132 | $this->chineseObj->extractModel( 133 | ChineseTextNumberSort::MODEL_REGULAR_C, 134 | '22 我是Marco小哥哥' 135 | ), 136 | 21 137 | ); 138 | } 139 | 140 | /** 141 | * testValidationModelD 142 | * 143 | * @throws \Exception 144 | * @test 145 | */ 146 | public function testValidationModelD() 147 | { 148 | $this->assertEquals( 149 | $this->chineseObj->extractModel( 150 | ChineseTextNumberSort::MODEL_REGULAR_D, 151 | '1页-我是Marco小哥哥' 152 | ), 153 | 1 154 | ); 155 | 156 | $this->assertEquals( 157 | $this->chineseObj->extractModel( 158 | ChineseTextNumberSort::MODEL_REGULAR_D, 159 | '22页-+我是Marco小哥哥' 160 | ), 161 | 22 162 | ); 163 | 164 | $this->assertNotEquals( 165 | $this->chineseObj->extractModel( 166 | ChineseTextNumberSort::MODEL_REGULAR_D, 167 | '2页-+我是Marco小哥哥' 168 | ), 169 | 22 170 | ); 171 | } 172 | 173 | /** 174 | * testValidationModelE 175 | * 176 | * @throws \Exception 177 | * @test 178 | */ 179 | public function testValidationModelE() 180 | { 181 | $this->assertEquals( 182 | $this->chineseObj->extractModel( 183 | ChineseTextNumberSort::MODEL_REGULAR_E, 184 | '1-' 185 | ), 186 | 1 187 | ); 188 | 189 | $this->assertEquals( 190 | $this->chineseObj->extractModel( 191 | ChineseTextNumberSort::MODEL_REGULAR_E, 192 | '2-+我是Marco小哥哥' 193 | ), 194 | 2 195 | ); 196 | 197 | $this->assertNotEquals( 198 | $this->chineseObj->extractModel( 199 | ChineseTextNumberSort::MODEL_REGULAR_E, 200 | '23-我是Marco小哥哥' 201 | ), 202 | 24 203 | ); 204 | } 205 | 206 | /** 207 | * testValidationModelF 208 | * 209 | * @throws \Exception 210 | * @test 211 | */ 212 | public function testValidationModelF() 213 | { 214 | $this->assertEquals( 215 | $this->chineseObj->extractModel( 216 | ChineseTextNumberSort::MODEL_REGULAR_F, 217 | '1 但是' 218 | ), 219 | 1 220 | ); 221 | 222 | $this->assertEquals( 223 | $this->chineseObj->extractModel( 224 | ChineseTextNumberSort::MODEL_REGULAR_F, 225 | '1 2对对对' 226 | ), 227 | 1 228 | ); 229 | 230 | $this->assertNotEquals( 231 | $this->chineseObj->extractModel( 232 | ChineseTextNumberSort::MODEL_REGULAR_F, 233 | '22 我是Marco小哥哥' 234 | ), 235 | 2 236 | ); 237 | } 238 | 239 | /** 240 | * testValidationModelG 241 | * 242 | * @throws \Exception 243 | * @test 244 | */ 245 | public function testValidationModelG() 246 | { 247 | $this->assertEquals( 248 | $this->chineseObj->extractModel( 249 | ChineseTextNumberSort::MODEL_REGULAR_G, 250 | '1、、' 251 | ), 252 | 1 253 | ); 254 | 255 | $this->assertEquals( 256 | $this->chineseObj->extractModel( 257 | ChineseTextNumberSort::MODEL_REGULAR_G, 258 | '01、2对对对' 259 | ), 260 | 01 261 | ); 262 | 263 | $this->assertNotEquals( 264 | $this->chineseObj->extractModel( 265 | ChineseTextNumberSort::MODEL_REGULAR_G, 266 | '23、我是Marco小哥哥' 267 | ), 268 | 24 269 | ); 270 | } 271 | 272 | /** 273 | * testValidationModelH 274 | * 275 | * @throws \Exception 276 | * @test 277 | */ 278 | public function testValidationModelH() 279 | { 280 | $this->assertEquals( 281 | $this->chineseObj->extractModel( 282 | ChineseTextNumberSort::MODEL_REGULAR_H, 283 | '我爱Marco老师小册10 :' 284 | ), 285 | 10 286 | ); 287 | 288 | $this->assertEquals( 289 | $this->chineseObj->extractModel( 290 | ChineseTextNumberSort::MODEL_REGULAR_H, 291 | '我爱Marco老师小册1 : 阳光鱼' 292 | ), 293 | 1 294 | ); 295 | 296 | $this->assertNotEquals( 297 | $this->chineseObj->extractModel( 298 | ChineseTextNumberSort::MODEL_REGULAR_H, 299 | '我爱Marco老师小册1 : 阳光鱼' 300 | ), 301 | 122 302 | ); 303 | } 304 | 305 | /** 306 | * testValidationModelI 307 | * 308 | * @throws \Exception 309 | */ 310 | public function testValidationModelI() 311 | { 312 | $this->assertEquals( 313 | $this->chineseObj->extractModel( 314 | ChineseTextNumberSort::MODEL_REGULAR_I, 315 | '识字一 01 十' 316 | ), 317 | '01' 318 | ); 319 | 320 | $this->assertEquals( 321 | $this->chineseObj->extractModel( 322 | ChineseTextNumberSort::MODEL_REGULAR_I, 323 | '狮子 03卧槽' 324 | ), 325 | '03' 326 | ); 327 | 328 | $this->assertNotEquals( 329 | $this->chineseObj->extractModel( 330 | ChineseTextNumberSort::MODEL_REGULAR_I, 331 | '狮子 03卧槽' 332 | ), 333 | '04' 334 | ); 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /tests/Sort/ChineseTextNumberSortModelTest.php: -------------------------------------------------------------------------------- 1 | chineseObj = new ChineseTextNumberSort(); 31 | } 32 | 33 | /** 34 | * testValidationModelA 35 | * 36 | * @test 37 | */ 38 | public function testValidationModelA() 39 | { 40 | $this->assertTrue( 41 | $this->chineseObj->regularModel( 42 | ChineseTextNumberSort::MODEL_REGULAR_A, 43 | '第二章 我是Marco小哥哥' 44 | ) 45 | ); 46 | 47 | $this->assertTrue( 48 | $this->chineseObj->regularModel( 49 | ChineseTextNumberSort::MODEL_REGULAR_A, 50 | '第一节 我是Marco小哥哥' 51 | ) 52 | ); 53 | 54 | $this->assertTrue( 55 | $this->chineseObj->regularModel( 56 | ChineseTextNumberSort::MODEL_REGULAR_A, 57 | '第二单元 我是Marco小哥哥' 58 | ) 59 | ); 60 | 61 | $this->assertNotTrue( 62 | $this->chineseObj->regularModel( 63 | ChineseTextNumberSort::MODEL_REGULAR_A, 64 | '第一章我是Marco小哥哥' 65 | ) 66 | ); 67 | } 68 | 69 | /** 70 | * testValidationModelB 71 | * 72 | * @test 73 | */ 74 | public function testValidationModelB() 75 | { 76 | $this->assertTrue( 77 | $this->chineseObj->regularModel( 78 | ChineseTextNumberSort::MODEL_REGULAR_B, 79 | '01我是Marco小哥哥' 80 | ) 81 | ); 82 | 83 | $this->assertTrue( 84 | $this->chineseObj->regularModel( 85 | ChineseTextNumberSort::MODEL_REGULAR_B, 86 | '12我是Marco小哥哥' 87 | ) 88 | ); 89 | 90 | $this->assertNotTrue( 91 | $this->chineseObj->regularModel( 92 | ChineseTextNumberSort::MODEL_REGULAR_B, 93 | '第一章我是Marco小哥哥' 94 | ) 95 | ); 96 | } 97 | 98 | /** 99 | * testValidationModelC 100 | * 101 | * @test 102 | */ 103 | public function testValidationModelC() 104 | { 105 | $this->assertTrue( 106 | $this->chineseObj->regularModel( 107 | ChineseTextNumberSort::MODEL_REGULAR_C, 108 | '1 我是Marco小哥哥' 109 | ) 110 | ); 111 | 112 | $this->assertTrue( 113 | $this->chineseObj->regularModel( 114 | ChineseTextNumberSort::MODEL_REGULAR_C, 115 | '22 我是Marco小哥哥' 116 | ) 117 | ); 118 | 119 | $this->assertNotTrue( 120 | $this->chineseObj->regularModel( 121 | ChineseTextNumberSort::MODEL_REGULAR_C, 122 | '22我是Marco小哥哥' 123 | ) 124 | ); 125 | } 126 | 127 | /** 128 | * testValidationModelD 129 | * 130 | * @test 131 | */ 132 | public function testValidationModelD() 133 | { 134 | $this->assertTrue( 135 | $this->chineseObj->regularModel( 136 | ChineseTextNumberSort::MODEL_REGULAR_D, 137 | '1页-我是Marco小哥哥' 138 | ) 139 | ); 140 | 141 | $this->assertTrue( 142 | $this->chineseObj->regularModel( 143 | ChineseTextNumberSort::MODEL_REGULAR_D, 144 | '1页-+我是Marco小哥哥' 145 | ) 146 | ); 147 | 148 | $this->assertNotTrue( 149 | $this->chineseObj->regularModel( 150 | ChineseTextNumberSort::MODEL_REGULAR_D, 151 | '22我是Marco小哥哥' 152 | ) 153 | ); 154 | } 155 | 156 | /** 157 | * testValidationModelD 158 | * 159 | * @test 160 | */ 161 | public function testValidationModelE() 162 | { 163 | $this->assertTrue( 164 | $this->chineseObj->regularModel( 165 | ChineseTextNumberSort::MODEL_REGULAR_E, 166 | '1-' 167 | ) 168 | ); 169 | 170 | $this->assertTrue( 171 | $this->chineseObj->regularModel( 172 | ChineseTextNumberSort::MODEL_REGULAR_E, 173 | '1-+我是Marco小哥哥' 174 | ) 175 | ); 176 | 177 | $this->assertNotTrue( 178 | $this->chineseObj->regularModel( 179 | ChineseTextNumberSort::MODEL_REGULAR_E, 180 | '22我是Marco小哥哥' 181 | ) 182 | ); 183 | } 184 | 185 | 186 | /** 187 | * MODEL_REGULAR_F 188 | * 189 | * @test 190 | */ 191 | public function testValidationModelF() 192 | { 193 | $this->assertTrue( 194 | $this->chineseObj->regularModel( 195 | ChineseTextNumberSort::MODEL_REGULAR_F, 196 | '1 但是' 197 | ) 198 | ); 199 | 200 | $this->assertTrue( 201 | $this->chineseObj->regularModel( 202 | ChineseTextNumberSort::MODEL_REGULAR_F, 203 | '1 2对对对' 204 | ) 205 | ); 206 | 207 | $this->assertNotTrue( 208 | $this->chineseObj->regularModel( 209 | ChineseTextNumberSort::MODEL_REGULAR_F, 210 | '22我是Marco小哥哥' 211 | ) 212 | ); 213 | } 214 | 215 | /** 216 | * testValidationModelG 217 | * 218 | * @test 219 | */ 220 | public function testValidationModelG() 221 | { 222 | $this->assertTrue( 223 | $this->chineseObj->regularModel( 224 | ChineseTextNumberSort::MODEL_REGULAR_G, 225 | '1、、' 226 | ) 227 | ); 228 | 229 | $this->assertTrue( 230 | $this->chineseObj->regularModel( 231 | ChineseTextNumberSort::MODEL_REGULAR_G, 232 | '01、2对对对' 233 | ) 234 | ); 235 | 236 | $this->assertNotTrue( 237 | $this->chineseObj->regularModel( 238 | ChineseTextNumberSort::MODEL_REGULAR_G, 239 | '22我是Marco小哥哥' 240 | ) 241 | ); 242 | } 243 | 244 | /** 245 | * testValidationModelG 246 | * 247 | * @test 248 | */ 249 | public function testValidationModelH() 250 | { 251 | $this->assertTrue( 252 | $this->chineseObj->regularModel( 253 | ChineseTextNumberSort::MODEL_REGULAR_H, 254 | '我爱Marco老师小册10 :' 255 | ) 256 | ); 257 | 258 | $this->assertTrue( 259 | $this->chineseObj->regularModel( 260 | ChineseTextNumberSort::MODEL_REGULAR_H, 261 | '我爱Marco老师小册1 : 阳光鱼' 262 | ) 263 | ); 264 | 265 | $this->assertNotTrue( 266 | $this->chineseObj->regularModel( 267 | ChineseTextNumberSort::MODEL_REGULAR_H, 268 | '22我是Marco小哥哥' 269 | ) 270 | ); 271 | } 272 | 273 | /** 274 | * testValidationModelG 275 | * 276 | * @test 277 | */ 278 | public function testValidationModelI() 279 | { 280 | $this->assertTrue( 281 | $this->chineseObj->regularModel( 282 | ChineseTextNumberSort::MODEL_REGULAR_I, 283 | '识字一 01 十' 284 | ) 285 | ); 286 | 287 | $this->assertTrue( 288 | $this->chineseObj->regularModel( 289 | ChineseTextNumberSort::MODEL_REGULAR_I, 290 | '狮子 03卧槽' 291 | ) 292 | ); 293 | 294 | $this->assertNotTrue( 295 | $this->chineseObj->regularModel( 296 | ChineseTextNumberSort::MODEL_REGULAR_I, 297 | '22我是Marco小哥哥' 298 | ) 299 | ); 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /tests/Sort/ChineseTextNumberSortTest.php: -------------------------------------------------------------------------------- 1 | chineseObj = new ChineseTextNumberSort(); 31 | } 32 | 33 | /** 34 | * testChineseTextListSorter 35 | */ 36 | public function testChineseTextListSorter() 37 | { 38 | $this->assertArraySubset( 39 | $this->chineseObj->chineseTextListSorter( 40 | array ( 41 | '第五章 我是Marco小哥哥', 42 | '第一章 我是Marco小哥哥', 43 | '第三章 我是Marco小哥哥', 44 | '第三章 我是Marco小哥哥', 45 | '第二章 我是Marco小哥哥', 46 | )), 47 | array ( 48 | '第一章 我是Marco小哥哥', 49 | '第二章 我是Marco小哥哥', 50 | '第三章 我是Marco小哥哥', 51 | '第三章 我是Marco小哥哥', 52 | '第五章 我是Marco小哥哥', 53 | ) 54 | ); 55 | 56 | $this->assertArraySubset( 57 | $this->chineseObj->chineseTextListSorter( 58 | array ( 59 | '05我是Marco小哥哥', 60 | '03我是Marco小哥哥', 61 | '02我是Marco小哥哥', 62 | '04我是Marco小哥哥', 63 | '01我是Marco小哥哥', 64 | )), 65 | array ( 66 | '01我是Marco小哥哥', 67 | '02我是Marco小哥哥', 68 | '03我是Marco小哥哥', 69 | '04我是Marco小哥哥', 70 | '05我是Marco小哥哥', 71 | ) 72 | ); 73 | 74 | $this->assertArraySubset( 75 | $this->chineseObj->chineseTextListSorter( 76 | array ( 77 | '6页-我是Marco小哥哥', 78 | '2页-我是Marco小哥哥', 79 | '3页-我是Marco小哥哥', 80 | '4页-我是Marco小哥哥', 81 | '5页-我是Marco小哥哥', 82 | '1页-我是Marco小哥哥', 83 | )), 84 | array ( 85 | '1页-我是Marco小哥哥', 86 | '2页-我是Marco小哥哥', 87 | '3页-我是Marco小哥哥', 88 | '4页-我是Marco小哥哥', 89 | '5页-我是Marco小哥哥', 90 | '6页-我是Marco小哥哥', 91 | ) 92 | ); 93 | 94 | $this->assertArraySubset( 95 | $this->chineseObj->chineseTextListSorter( 96 | array ( 97 | '我爱Marco老师小册6 :', 98 | '我爱Marco老师小册2 :', 99 | '我爱Marco老师小册3 :', 100 | '我爱Marco老师小册4 :', 101 | '我爱Marco老师小册5 :', 102 | '我爱Marco老师小册1 :', 103 | '我爱Marco老师小册7 :', 104 | )), 105 | array ( 106 | '我爱Marco老师小册1 :', 107 | '我爱Marco老师小册2 :', 108 | '我爱Marco老师小册3 :', 109 | '我爱Marco老师小册4 :', 110 | '我爱Marco老师小册5 :', 111 | '我爱Marco老师小册6 :', 112 | '我爱Marco老师小册7 :', 113 | ) 114 | ); 115 | 116 | $this->assertArraySubset( 117 | $this->chineseObj->chineseTextListSorter( 118 | array ( 119 | '6、2对对对', 120 | '2、2对对对', 121 | '4、2对对对', 122 | '3、2对对对', 123 | '5、2对对对', 124 | '1、2对对对', 125 | )), 126 | array ( 127 | '1、2对对对', 128 | '2、2对对对', 129 | '3、2对对对', 130 | '4、2对对对', 131 | '5、2对对对', 132 | '6、2对对对', 133 | ) 134 | ); 135 | } 136 | 137 | 138 | /** 139 | * testTextAnalysis 140 | */ 141 | public function testTextAnalysis() 142 | { 143 | $this->assertEquals( 144 | $this->chineseObj->textAnalysis('第二章 我是Marco小哥哥'), 145 | 2 146 | ); 147 | $this->assertEquals( 148 | $this->chineseObj->textAnalysis('01我是Marco小哥哥'), 149 | 1 150 | ); 151 | $this->assertEquals( 152 | $this->chineseObj->textAnalysis('1 我是Marco小哥哥'), 153 | 1 154 | ); 155 | $this->assertEquals( 156 | $this->chineseObj->textAnalysis('1页-我是Marco小哥哥'), 157 | 1 158 | ); 159 | $this->assertEquals( 160 | $this->chineseObj->textAnalysis('2-+我是Marco小哥哥'), 161 | 2 162 | ); 163 | $this->assertEquals( 164 | $this->chineseObj->textAnalysis('1 2对对对'), 165 | 1 166 | ); 167 | $this->assertEquals( 168 | $this->chineseObj->textAnalysis('1、2对对对'), 169 | 1 170 | ); 171 | $this->assertEquals( 172 | $this->chineseObj->textAnalysis('我爱Marco老师小册10 :'), 173 | 10 174 | ); 175 | $this->assertNotEquals( 176 | $this->chineseObj->textAnalysis('我爱Marco老师小册10 :'), 177 | 12 178 | ); 179 | } 180 | 181 | 182 | /** 183 | * testModelAnalysis 184 | * 185 | * @throws \ReflectionException 186 | */ 187 | public function testModelAnalysis() 188 | { 189 | $this->assertEquals( 190 | $this->chineseObj->modelAnalysis('第二章 我是Marco小哥哥'), 191 | ChineseTextNumberSort::MODEL_REGULAR_A 192 | ); 193 | $this->assertEquals( 194 | $this->chineseObj->modelAnalysis('01我是Marco小哥哥'), 195 | ChineseTextNumberSort::MODEL_REGULAR_B 196 | ); 197 | 198 | $this->assertEquals( 199 | $this->chineseObj->modelAnalysis('1 我是Marco小哥哥'), 200 | ChineseTextNumberSort::MODEL_REGULAR_F 201 | ); 202 | 203 | $this->assertEquals( 204 | $this->chineseObj->modelAnalysis('1页-我是Marco小哥哥'), 205 | ChineseTextNumberSort::MODEL_REGULAR_D 206 | ); 207 | $this->assertEquals( 208 | $this->chineseObj->modelAnalysis('2-+我是Marco小哥哥'), 209 | ChineseTextNumberSort::MODEL_REGULAR_E 210 | ); 211 | $this->assertEquals( 212 | $this->chineseObj->modelAnalysis('1 2对对对'), 213 | ChineseTextNumberSort::MODEL_REGULAR_F 214 | ); 215 | $this->assertEquals( 216 | $this->chineseObj->modelAnalysis('1、2对对对'), 217 | ChineseTextNumberSort::MODEL_REGULAR_G 218 | ); 219 | $this->assertEquals( 220 | $this->chineseObj->modelAnalysis('我爱Marco老师小册10 :'), 221 | ChineseTextNumberSort::MODEL_REGULAR_H 222 | ); 223 | $this->assertNotEquals( 224 | $this->chineseObj->modelAnalysis('我爱Marco老师小册10 :'), 225 | ChineseTextNumberSort::MODEL_REGULAR_G 226 | ); 227 | } 228 | 229 | /** 230 | * description 231 | * 232 | * @test 233 | */ 234 | /** 235 | * description 236 | * 237 | * @throws \ReflectionException 238 | * @test 239 | */ 240 | public function testAnalysisText() 241 | { 242 | var_dump($this->chineseObj->getAllModelRegular()); 243 | die; 244 | } 245 | 246 | } 247 | --------------------------------------------------------------------------------