├── .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 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
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 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
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 计算-';
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 ';
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 .='
';
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 ';
65 | for ($j = 0; $j < $this->col; $j++) {
66 | $str .=' ";
69 | }
70 | $str .=''.$this->res[$i][$j] . " ";
67 | }
68 | $str .="