From c0492002bb149eed06da1fd58800e4d445e10bbf Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 18:25:39 +0800 Subject: [PATCH 001/127] fix: test emoj :ok_hand: --- package/Sort/MergeSort.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 0297736..30bf71c 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -24,8 +24,7 @@ class MergeSort */ public function __construct(array $arr) { - $len = count($arr);//求得数组长度 - $this->mSort($arr, 0, $len - 1); + $this->mSort($arr, 0, count($arr) - 1); var_dump($arr); } From a8eed19be78ca16f46c515df3278d85a5a2ad925 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 18:39:41 +0800 Subject: [PATCH 002/127] fix: modify LICENSE :memo: --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 748bc09..00f89f5 100644 --- a/LICENSE +++ b/LICENSE @@ -373,4 +373,4 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice defined by the Mozilla Public License, v. 2.0. Contact GitHub API Training Shop Blog About -© 2017 GitHub, Inc. Terms Privacy Security Status Help \ No newline at end of file +© 2017 GitHub, Inc. Terms Privacy Security Status Help .Shao Wei \ No newline at end of file From 070559a13259871c034fee8554329eb8ac6b27e2 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 18:43:53 +0800 Subject: [PATCH 003/127] fix: add examples :arrow_down: --- package/Query/BinaryQuery.php | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/package/Query/BinaryQuery.php b/package/Query/BinaryQuery.php index aedc8c2..28dfd83 100644 --- a/package/Query/BinaryQuery.php +++ b/package/Query/BinaryQuery.php @@ -57,4 +57,22 @@ function BinaryQueryRecursive(array $container,$search,$low = 0,$top = 'default' } } -// var_dump( BinaryQueryRecursive([0,1,2,3,4,5,6,7,8,9],9) ); + var_dump( BinaryQueryRecursive([0,1,2,3,4,5,6,7,8,9],9) ); +/* +array(7) { + [0] => + int(3) + [1] => + int(4) + [2] => + int(5) + [3] => + int(6) + [4] => + int(7) + [5] => + int(8) + [6] => + int(9) +} +*/ \ No newline at end of file From efaab21e997543ecf1e166600f783635c2f2f095 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 19:21:31 +0800 Subject: [PATCH 004/127] fix: Increase the process; :rocket: --- package/Sort/MergeSort.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 30bf71c..1fc7a43 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -60,6 +60,7 @@ public function mSort(&$arr, $left, $right) */ public function mergeArray(&$arr, $left, $center, $right) { + echo '| '.$left.' - '.$center.' - '.$right.' - '.implode(',',$arr).PHP_EOL; //设置两个起始位置标记 $a_i = $left; $b_i = $center + 1; @@ -92,4 +93,29 @@ public function mergeArray(&$arr, $left, $center, $right) //do some test: new mergeSort([4, 7, 6, 3, 9, 5, 8]); +/* +| 0 - 0 - 1 - 4,7,6,3,9,5,8 +| 2 - 2 - 3 - 4,7,6,3,9,5,8 +| 0 - 1 - 3 - 4,7,3,6,9,5,8 +| 4 - 4 - 5 - 3,4,6,7,9,5,8 +| 4 - 5 - 6 - 3,4,6,7,5,9,8 +| 0 - 3 - 6 - 3,4,6,7,5,8,9 + +array(7) { + [0] => + int(3) + [1] => + int(4) + [2] => + int(5) + [3] => + int(6) + [4] => + int(7) + [5] => + int(8) + [6] => + int(9) +} + */ \ No newline at end of file From b44db07775585e7d1bd9d4faede4baac84a2a934 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 19:22:41 +0800 Subject: [PATCH 005/127] fix: Increase the process :package: --- package/Sort/MergeSort.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 35c5403..1fc7a43 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -49,8 +49,6 @@ public function mSort(&$arr, $left, $right) $this->mergeArray($arr, $left, $center, $right); } } - // 4, 7, 6, 3, 9, 5, 8 - // /** * 将两个有序数组合并成一个有序数组 From aee75348f3dfb29e1f5c732b61ce844b32dd81b3 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 20:10:24 +0800 Subject: [PATCH 006/127] feat: new stydy :page_facing_up: --- package/Other/MonkeyKing.php | 66 +++++++++++++++++++++++++++++++++++ package/Query/QulickQuery.php | 44 +++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 package/Other/MonkeyKing.php create mode 100644 package/Query/QulickQuery.php diff --git a/package/Other/MonkeyKing.php b/package/Other/MonkeyKing.php new file mode 100644 index 0000000..4a17a42 --- /dev/null +++ b/package/Other/MonkeyKing.php @@ -0,0 +1,66 @@ + + * @date 2017/8/23 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:单项循环数据链表  + * ------------------------------------------------------------- + *有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 + */ +class MonkeyKing +{ + protected $next; + protected $name; + + /** + * MonkeyKing constructor. + * + * @param $name + */ + public function __construct($name) + { + $this->name = $name; + } + + /** + * whoIsKing + * + * @static + * @param $count + * @param $num + * @return mixed + */ + public static function whoIsKing($count, $num) + { + // 构造单向循环链表 + $current = $first = new MonkeyKing(1); + for ($i = 2; $i <= $count; $i++){ + $current->next = new MonkeyKing($i); + $current = $current->next; + } + // 最后一个指向第一个 + $current->next = $first; + // 指向第一个 + $current = $first; + // 定义一个数字 + $cn = 1; + while ($current !== $current->next){ + $cn++; + if ($cn == $num) { + $current->next = $current->next->next; + $cn = 1; + } + $current = $current->next; + } + // 返回猴子姓名 + return $current->name; + } +} + +// 共10个猴子每3个出圈 +var_dump(MonkeyKing::whoIsKing(10, 3)); + diff --git a/package/Query/QulickQuery.php b/package/Query/QulickQuery.php new file mode 100644 index 0000000..f39d079 --- /dev/null +++ b/package/Query/QulickQuery.php @@ -0,0 +1,44 @@ + + * @date 2017/8/23 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:数组中间的值floor((low+top)/2)  + * ------------------------------------------------------------- + * 重复第二步操作直至找出目标数字 + */ + +/** + * @param $array + * @param $k + * @param int $low + * @param int $high + * @return int + */ +function QulickQuery($array, $k, $low = 0, $high = 0) +{ + //判断是否为第一次调用 + if (count($array) != 0 and $high == 0) { + $high = count($array); + } + //如果还存在剩余的数组元素 + if ($low <= $high) { + //取$low和$high的中间值 + $mid = intval(($low + $high) / 2); + //如果找到则返回 + if ($array[ $mid ] == $k) { + return $mid; + }else if ($k < $array[ $mid ]) {//如果没有找到,则继续查找 + return QulickQuery($array, $k, $low, $mid - 1); + } else { + return QulickQuery($array, $k, $mid + 1, $high); + } + } + return -1; +} + +echo QulickQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file From 6745a11535644e483f6f1c3b97d7ddeb684614a8 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 20:10:57 +0800 Subject: [PATCH 007/127] fix: add new study :sparkles: --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9229c40..20e05bc 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,10 @@ │ │ │ ├── Query 查询篇 │ │ ├── BinaryQuery.php 二分查找 - │ │ └── 快速查找 + │ │ └── QulickQuery.php 快速查找 │ │ │ └── Other 其他 + │ ├── MonkeyKing.php 猴子选大王 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE From d6c94a0913d89d8de1237b3f6ec68151c9df6556 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 23 Aug 2017 20:52:16 +0800 Subject: [PATCH 008/127] feat: new arithmetic :hammer: --- README.md | 4 ++- package/Other/BigSmallReplace.php | 4 +-- package/Query/BinaryQuery.php | 4 +-- package/Query/QulickQuery.php | 4 +-- package/Sort/BubbleSort.php | 4 +-- package/Sort/InsertSort.php | 49 ++++++++++++++++++++++++++ package/Sort/MergeSort.php | 14 ++++---- package/Sort/QuickSort.php | 4 +-- package/Sort/SelectSort.php | 57 +++++++++++++++++++++++++++++++ package/Sort/ShellSort.php | 4 +-- 10 files changed, 122 insertions(+), 26 deletions(-) create mode 100644 package/Sort/InsertSort.php create mode 100644 package/Sort/SelectSort.php diff --git a/README.md b/README.md index 20e05bc..4f0d002 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,9 @@ │ │ ├── BubbleSort.php 冒泡排序 │ │ ├── QuickSort.php 快速排序 │ │ ├── ShellSort.php 希尔排序 - │ │ └── MergeSort.php 归并排序 + │ │ ├── MergeSort.php 归并排序 + │ │ ├── InsertSort.php 插入排序 + │ │ └── SelectSort.php 选择排序 │ │ │ ├── Query 查询篇 │ │ ├── BinaryQuery.php 二分查找 diff --git a/package/Other/BigSmallReplace.php b/package/Other/BigSmallReplace.php index cdd178f..656c947 100644 --- a/package/Other/BigSmallReplace.php +++ b/package/Other/BigSmallReplace.php @@ -6,9 +6,7 @@ * @author Pu ShaoWei * @date 2017/8/12 * @license Mozilla - */ - -/** + * * segmentFault: https://segmentfault.com/q/1010000010627229 * * @language php diff --git a/package/Query/BinaryQuery.php b/package/Query/BinaryQuery.php index 28dfd83..4994862 100644 --- a/package/Query/BinaryQuery.php +++ b/package/Query/BinaryQuery.php @@ -11,9 +11,7 @@ * 若比中间值大则将首值替换为中间位置下一个位置,继续第一步的操作; * 若比中间值小,则将尾值替换为中间位置上一个位置,继续第一步操作 * 重复第二步操作直至找出目标数字 - */ - -/** + * * 非递归版 二分查找 * @param array $container * @param $search diff --git a/package/Query/QulickQuery.php b/package/Query/QulickQuery.php index f39d079..6c8fb4c 100644 --- a/package/Query/QulickQuery.php +++ b/package/Query/QulickQuery.php @@ -10,9 +10,7 @@ * 思路分析:数组中间的值floor((low+top)/2)  * ------------------------------------------------------------- * 重复第二步操作直至找出目标数字 - */ - -/** + * * @param $array * @param $k * @param int $low diff --git a/package/Sort/BubbleSort.php b/package/Sort/BubbleSort.php index 004503f..e05b775 100644 --- a/package/Sort/BubbleSort.php +++ b/package/Sort/BubbleSort.php @@ -11,9 +11,7 @@ * 由底至上的把较少的气泡逐步地向上升,这样经过遍历一次后最小的气泡就会被上升到顶(下标为0) * 然后再从底至上地这样升,循环直至十个气泡大小有序。 * 在冒泡排序中,最重要的思想是两两比较,将两者较少的升上去 - */ - -/** + * * @param array $container * @return array */ diff --git a/package/Sort/InsertSort.php b/package/Sort/InsertSort.php new file mode 100644 index 0000000..58b8ff1 --- /dev/null +++ b/package/Sort/InsertSort.php @@ -0,0 +1,49 @@ + + * @date 2017/6/17 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。 + * ------------------------------------------------------------- + * + * 算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。 + * 插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素, + * 但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。 + * 在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。 + * + * @param $container + * @return mixed + */ + +function InsertSort(array $container) +{ + $count = count($container); + for ($i = 1; $i < $count; $i++){ + $temp = $container[$i]; + $j = $i - 1; + // Init + while ($container[$j] > $temp){ + $container[$j+1] = $container[$j]; + $container[$j] = $temp; + $j--; + if ($j < 0) break; + } + } + return $container; +} +var_dump(InsertSort([3, 12, 42, 1, 24, 5, 346, 7])); + +/* +array (size=8) + 0 => int 1 + 1 => int 3 + 2 => int 5 + 3 => int 7 + 4 => int 12 + 5 => int 24 + 6 => int 42 + 7 => int 346 + */ \ No newline at end of file diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 1fc7a43..88beb0c 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -60,13 +60,13 @@ public function mSort(&$arr, $left, $right) */ public function mergeArray(&$arr, $left, $center, $right) { - echo '| '.$left.' - '.$center.' - '.$right.' - '.implode(',',$arr).PHP_EOL; + echo '| ' . $left . ' - ' . $center . ' - ' . $right . ' - ' . implode(',', $arr) . PHP_EOL; //设置两个起始位置标记 - $a_i = $left; - $b_i = $center + 1; + $a_i = $left; + $b_i = $center + 1; $temp = []; - while ($a_i <= $center && $b_i <= $right){ + while ($a_i <= $center && $b_i <= $right) { //当数组A和数组B都没有越界时 if ($arr[ $a_i ] < $arr[ $b_i ]) { $temp[] = $arr[ $a_i++ ]; @@ -75,16 +75,16 @@ public function mergeArray(&$arr, $left, $center, $right) } } //判断 数组A内的元素是否都用完了,没有的话将其全部插入到C数组内: - while ($a_i <= $center){ + while ($a_i <= $center) { $temp[] = $arr[ $a_i++ ]; } //判断 数组B内的元素是否都用完了,没有的话将其全部插入到C数组内: - while ($b_i <= $right){ + while ($b_i <= $right) { $temp[] = $arr[ $b_i++ ]; } //将$arrC内排序好的部分,写入到$arr内: - for ($i = 0, $len = count($temp); $i < $len; $i++){ + for ($i = 0, $len = count($temp); $i < $len; $i++) { $arr[ $left + $i ] = $temp[ $i ]; } } diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index 3902d5f..845a296 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -10,9 +10,7 @@ * 重新排序数列,所有元素比基准值小的摆放在基准前面 * 所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。 * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 - */ - -/** + * * @param array $container * @return array|void */ diff --git a/package/Sort/SelectSort.php b/package/Sort/SelectSort.php new file mode 100644 index 0000000..0c8fedf --- /dev/null +++ b/package/Sort/SelectSort.php @@ -0,0 +1,57 @@ + + * @date 2017/6/17 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:选择排序是不稳定的排序方法 + * ------------------------------------------------------------- + * 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 + * 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。 + * + * @param $container + * @return mixed + */ +function SelectSort(array $container) +{ + $count = count($container); + for ($i = 0; $i < $count; $i++){ + $k = $i; + for ($j = $i + 1; $j < $count; $j++){ + if($container[$j] < $container[$k]){ + $k = $j; + } + } + if($k != $i){ + $temp = $container[$i]; + $container[$i] = $container[$k]; + $container[$k] = $temp; + } + } + return $container; +} + +var_dump(SelectSort([3, 12, 42, 1, 24, 5, 346, 7])); + +/* + array(8) { + [0] => + int(1) + [1] => + int(3) + [2] => + int(5) + [3] => + int(7) + [4] => + int(12) + [5] => + int(24) + [6] => + int(42) + [7] => + int(346) +} + */ \ No newline at end of file diff --git a/package/Sort/ShellSort.php b/package/Sort/ShellSort.php index eb5b86d..809c8cd 100644 --- a/package/Sort/ShellSort.php +++ b/package/Sort/ShellSort.php @@ -9,9 +9,7 @@ * ------------------------------------------------------------- * 希尔排序中一个常数因子n,原数组被分成各个小组,每个小组由h个元素组成,很可能会有多余的元素。 * 当然每次循环的时候,h也是递减的(h=h/n)。第一次循环就是从下标为h开始。希尔排序的一个思想就是,分成小组去排序。 - */ - -/** + * * @param array $container * @return array */ From 2ed8fa8ce4ca61ad5c64d136d88d266242c90006 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 18:33:24 +0800 Subject: [PATCH 009/127] feat: The new algorithm :hammer: --- README.md | 5 ++++- package/Other/GetCattle.php | 13 +++++++++++++ package/Query/BinaryTree.php | 8 ++++++++ package/Query/FibonacciQuery.php | 8 ++++++++ 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 package/Other/GetCattle.php create mode 100644 package/Query/BinaryTree.php create mode 100644 package/Query/FibonacciQuery.php diff --git a/README.md b/README.md index 4f0d002..df903f4 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,15 @@ │ │ ├── InsertSort.php 插入排序 │ │ └── SelectSort.php 选择排序 │ │ - │ ├── Query 查询篇 + │ ├── Query 查找篇 │ │ ├── BinaryQuery.php 二分查找 + │ │ ├── FibonacciQuery.php 斐波那契查找 │ │ └── QulickQuery.php 快速查找 │ │ │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 + │ ├── GetCattle.php 牛年求牛 + │ ├── Fibonacci.php 斐波那契数列 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/GetCattle.php b/package/Other/GetCattle.php new file mode 100644 index 0000000..ce0a6ee --- /dev/null +++ b/package/Other/GetCattle.php @@ -0,0 +1,13 @@ + + * @date 2017/8/24 + * @license Mozilla + */ +class GetCattle +{ + +} \ No newline at end of file diff --git a/package/Query/BinaryTree.php b/package/Query/BinaryTree.php new file mode 100644 index 0000000..140ad8d --- /dev/null +++ b/package/Query/BinaryTree.php @@ -0,0 +1,8 @@ + + * @date 2017/8/25 + * @license Mozilla + */ diff --git a/package/Query/FibonacciQuery.php b/package/Query/FibonacciQuery.php new file mode 100644 index 0000000..140ad8d --- /dev/null +++ b/package/Query/FibonacciQuery.php @@ -0,0 +1,8 @@ + + * @date 2017/8/25 + * @license Mozilla + */ From 2f271ff199e245098fae66ef2feeff2b861f2743 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 18:33:56 +0800 Subject: [PATCH 010/127] feat: the new algorithm :chart_with_upwards_trend: --- package/Other/BigSmallReplace.php | 2 - package/Other/Fibonacci.php | 44 ++++++++++++++++++ package/Other/GetCattle.php | 40 +++++++++++++++-- package/Other/MonkeyKing.php | 11 ++++- package/Query/BinaryTree.php | 9 +++- package/Query/FibonacciQuery.php | 75 +++++++++++++++++++++++++++++-- 6 files changed, 170 insertions(+), 11 deletions(-) create mode 100644 package/Other/Fibonacci.php diff --git a/package/Other/BigSmallReplace.php b/package/Other/BigSmallReplace.php index 656c947..c5277ff 100644 --- a/package/Other/BigSmallReplace.php +++ b/package/Other/BigSmallReplace.php @@ -9,8 +9,6 @@ * * segmentFault: https://segmentfault.com/q/1010000010627229 * - * @language php - * @author Pu Shaowei * @param $str * @return string */ diff --git a/package/Other/Fibonacci.php b/package/Other/Fibonacci.php new file mode 100644 index 0000000..be4c603 --- /dev/null +++ b/package/Other/Fibonacci.php @@ -0,0 +1,44 @@ + + * @date 2017/8/25 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:这他妈有个毛的思路,随便学习一下 + * ------------------------------------------------------------- + * 斐波那契数列(Fibonacci Sequence)又称黄金分割数列 + * 指的是这样一个数列:1、1、2、3、5、8、13、21 + * 在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。 + * + * @param $n + * @return int + */ + +// recursion +/* +function Fibonacci($n) +{ + if ($n <= 1 ) { + return $n; + } + return Fibonacci($n - 1) + Fibonacci($n - 2); +} +*/ +// 55 + +// not recursion +function Fibonacci($n) +{ + if ($n <= 1) { + return $n; + } + for ($fib = [0, 1], $i = 2; $i <= $n; $i++) { + $fib[$i] = $fib[$i - 1] + $fib[$i - 2]; + } + return $fib[$n]; +} + +echo Fibonacci(10); +// 55 diff --git a/package/Other/GetCattle.php b/package/Other/GetCattle.php index ce0a6ee..9cc19dc 100644 --- a/package/Other/GetCattle.php +++ b/package/Other/GetCattle.php @@ -3,11 +3,45 @@ /** * GetCattle * - * @author Pu ShaoWei + * @author Pu ShaoWei * @date 2017/8/24 * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:见下方注释  + * ------------------------------------------------------------- + * + * 牛年求牛: + * 有一母牛,到4岁可生育,每年一头,所生均是一样的母牛 + * 15岁绝育,不再能生, + * 20岁死亡,问n年后有多少头牛。 + * + * @param $n + * @return int */ -class GetCattle +function getCattle($n) { + static $num = 1; + for ($i =1; $i<=$n;$i++){ + if( $i == 20) break; + if($i >= 4 && $i <15){ + if($i % 4 == 0 ){ + getCattle($n - $i); + $num++; + } + $num++; + } + } + return $num; +} +echo '牛年共有:'.getCattle(10); + +/* +123456789 + 123456 + 123 + 12 +9 - 11 + +--- -} \ No newline at end of file + */ \ No newline at end of file diff --git a/package/Other/MonkeyKing.php b/package/Other/MonkeyKing.php index 4a17a42..d07a2e9 100644 --- a/package/Other/MonkeyKing.php +++ b/package/Other/MonkeyKing.php @@ -7,7 +7,7 @@ * @date 2017/8/23 * @license Mozilla * ------------------------------------------------------------- - * 思路分析:单项循环数据链表  + * 思路分析:约瑟夫环问题 * ------------------------------------------------------------- *有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 */ @@ -64,3 +64,12 @@ public static function whoIsKing($count, $num) // 共10个猴子每3个出圈 var_dump(MonkeyKing::whoIsKing(10, 3)); +function whoIsKing($n,$m){ + $r = 0; + for ($i=2; $i <= $n ; $i++) { + $r = ($r + $m) % $i; + } + return $r+1; +} + +var_dump(whoIsKing(10,3)); \ No newline at end of file diff --git a/package/Query/BinaryTree.php b/package/Query/BinaryTree.php index 140ad8d..05ac1ba 100644 --- a/package/Query/BinaryTree.php +++ b/package/Query/BinaryTree.php @@ -1,8 +1,13 @@ + * @author Pu ShaoWei * @date 2017/8/25 * @license Mozilla + * ------------------------------------------------------------- + * 思路分析: + * ------------------------------------------------------------- + * */ diff --git a/package/Query/FibonacciQuery.php b/package/Query/FibonacciQuery.php index 140ad8d..eca8939 100644 --- a/package/Query/FibonacciQuery.php +++ b/package/Query/FibonacciQuery.php @@ -1,8 +1,77 @@ - * @date 2017/8/25 + * @author Pu ShaoWei + * @date 2017/8/23 * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:斐波那契查找 利用黄金分割原理 + * ------------------------------------------------------------- + * + * $num == $container[$mid],直接返回 + * $num < $container[$mid],新范围是第 $low 个到 $mid-1 个,此时范围个数为 produced($key-1)-1 个 + * $num > $container[$mid],新范围是第 $mid+1 个到 $high 个,此时范围个数为 produced($key-2)-1 个 */ +class FibonacciQuery{ + + /** + * FibonacciQuery constructor. + * + * @param array $container + * @param $num + */ + public function __construct(array $container,$num) + { + $count = count($container); + $lower = $key = $result = 0; + $high = $count - 1; + + //计算$count位于斐波那契数列的位置 + while ($count > ($this->produced($key) - 1)) { + $key++; + } + + //将不满的数值补全,补的数值为数组的最后一位 + for ($j = $count; $j < $this->produced($key) - 1; $j++) { + $container[ $j ] = $container[ $count - 1 ]; + } + + //查找开始 + while ($lower <= $high) { + + //计算当前分隔的下标 + $mid = $lower + $this->produced($key - 1) - 1; + + if ($num < $container[ $mid ]) { + $high = $mid - 1; + $key -= 1; //斐波那契数列数列下标减一位 + }else if ($num > $container[ $mid ]) { + $lower = $mid + 1; + $key -= 2; //斐波那契数列数列下标减两位 + } + + if ($mid <= $count - 1) { + $result = $mid; break; + } else { //这里$mid大于$count-1说明是补全数值,返回$count-1 + $result = $count - 1; break; + } + } + var_dump( $result ); + } + + /** + * 创建一个生产斐波那契数列 + * + * @param $length + * @return int + */ + public function produced($length){ + if($length < 2){ + return ($length == 0 ? 0 : 1); + } + return $this->produced($length - 1) + $this->produced($length - 2); + } +} + +var_dump(new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8)); \ No newline at end of file From 0eddd4f1d4577e167c2885b9b22700bcf6367cea Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 19:22:16 +0800 Subject: [PATCH 011/127] feat: add compare :page_facing_up: --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index df903f4..7ce396e 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,13 @@ return i; > #### 可变空间,这部分空间的主要包括动态分配的空间,以及递归栈所需的空间等。这部分的空间大小与算法有关。 一个算法所需的存储空间用f(n)表示。S(n)=O(f(n))  其中n为问题的规模,S(n)表示空间复杂度。 +## 递归和循环的简单比较: + 1、从程序上看,递归表现为自己调用自己,循环则没有这样的形式。 + 2、递归是从问题的最终目标出发,逐渐将复杂问题化为简单问题,并且简单的问题的解决思路和复杂问题一样,同时存在基准情况,就能最终求得问题,是逆向的。而循环是从简单问题出发,一步步的向前发展,最终求得问题,是正向的。 + 3、任意循环都是可以用递归来表示的,但是想用循环来实现递归(除了单向递归和尾递归),都必须引入栈结构进行压栈出栈。 + 4、一般来说,非递归的效率高于递归。而且递归函数调用是有开销的,递归的次数受堆栈大小的限制。 + + ## 一起进步学习 1. Fork 我的项目 2. Pull Request From 1cbd8faf06922e5a78decef2896e4277a2b3e005 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 19:22:36 +0800 Subject: [PATCH 012/127] fix: modify bug :arrow_up: --- package/Other/Fibonacci.php | 4 ++-- package/Query/FibonacciQuery.php | 17 ++++++----------- 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/package/Other/Fibonacci.php b/package/Other/Fibonacci.php index be4c603..6cec949 100644 --- a/package/Other/Fibonacci.php +++ b/package/Other/Fibonacci.php @@ -6,9 +6,9 @@ * @date 2017/8/25 * @license Mozilla * ------------------------------------------------------------- - * 思路分析:这他妈有个毛的思路,随便学习一下 + * 思路分析: * ------------------------------------------------------------- - * 斐波那契数列(Fibonacci Sequence)又称黄金分割数列 + * 斐波那契数列(Fibonacci Sequence)又称黄金分割数列 兔子数列 * 指的是这样一个数列:1、1、2、3、5、8、13、21 * 在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。 * diff --git a/package/Query/FibonacciQuery.php b/package/Query/FibonacciQuery.php index eca8939..4e1b3d0 100644 --- a/package/Query/FibonacciQuery.php +++ b/package/Query/FibonacciQuery.php @@ -26,31 +26,25 @@ public function __construct(array $container,$num) $count = count($container); $lower = $key = $result = 0; $high = $count - 1; - //计算$count位于斐波那契数列的位置 while ($count > ($this->produced($key) - 1)) { $key++; } - //将不满的数值补全,补的数值为数组的最后一位 for ($j = $count; $j < $this->produced($key) - 1; $j++) { $container[ $j ] = $container[ $count - 1 ]; } - //查找开始 while ($lower <= $high) { - //计算当前分隔的下标 $mid = $lower + $this->produced($key - 1) - 1; - if ($num < $container[ $mid ]) { - $high = $mid - 1; - $key -= 1; //斐波那契数列数列下标减一位 + $high = $mid - 1; + $key -= 1; //斐波那契数列数列下标减一位 }else if ($num > $container[ $mid ]) { $lower = $mid + 1; - $key -= 2; //斐波那契数列数列下标减两位 + $key -= 2; //斐波那契数列数列下标减两位 } - if ($mid <= $count - 1) { $result = $mid; break; } else { //这里$mid大于$count-1说明是补全数值,返回$count-1 @@ -66,7 +60,8 @@ public function __construct(array $container,$num) * @param $length * @return int */ - public function produced($length){ + public function produced($length) + { if($length < 2){ return ($length == 0 ? 0 : 1); } @@ -74,4 +69,4 @@ public function produced($length){ } } -var_dump(new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8)); \ No newline at end of file +new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file From ee25d4337e78c064aea9fd4e578fc8db09f2cf97 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 19:43:14 +0800 Subject: [PATCH 013/127] feat: new arithmetic :art: --- README.md | 27 ++++++++++++++------------- package/Query/InseertQuery.php | 8 ++++++++ 2 files changed, 22 insertions(+), 13 deletions(-) create mode 100644 package/Query/InseertQuery.php diff --git a/README.md b/README.md index 7ce396e..38bb8ab 100644 --- a/README.md +++ b/README.md @@ -17,23 +17,24 @@ ├──Package │ ├── Sort 排序篇 - │ │ ├── BubbleSort.php 冒泡排序 - │ │ ├── QuickSort.php 快速排序 - │ │ ├── ShellSort.php 希尔排序 - │ │ ├── MergeSort.php 归并排序 - │ │ ├── InsertSort.php 插入排序 - │ │ └── SelectSort.php 选择排序 + │ │ ├── BubbleSort.php 冒泡排序 + │ │ ├── QuickSort.php 快速排序 + │ │ ├── ShellSort.php 希尔排序 + │ │ ├── MergeSort.php 归并排序 + │ │ ├── InsertSort.php 插入排序 + │ │ └── SelectSort.php 选择排序 │ │ │ ├── Query 查找篇 - │ │ ├── BinaryQuery.php 二分查找 - │ │ ├── FibonacciQuery.php 斐波那契查找 - │ │ └── QulickQuery.php 快速查找 + │ │ ├── BinaryQuery.php 二分查找 + │ │ ├── InseertQuery.php 插入查找 + │ │ ├── FibonacciQuery.php 斐波那契查找 + │ │ └── QulickQuery.php 快速查找 │ │ │ └── Other 其他 - │ ├── MonkeyKing.php 猴子选大王 - │ ├── GetCattle.php 牛年求牛 - │ ├── Fibonacci.php 斐波那契数列 - │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow + │ ├── MonkeyKing.php 猴子选大王 + │ ├── GetCattle.php 牛年求牛 + │ ├── Fibonacci.php 斐波那契数列 + │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE └──README.md diff --git a/package/Query/InseertQuery.php b/package/Query/InseertQuery.php new file mode 100644 index 0000000..140ad8d --- /dev/null +++ b/package/Query/InseertQuery.php @@ -0,0 +1,8 @@ + + * @date 2017/8/25 + * @license Mozilla + */ From 507f1af4ebe9724d19113d0195e18dd4726250a6 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 25 Aug 2017 19:44:22 +0800 Subject: [PATCH 014/127] feat: new arithmetic :art: --- package/Query/InseertQuery.php | 8 ------ package/Query/InsertQuery.php | 49 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) delete mode 100644 package/Query/InseertQuery.php create mode 100644 package/Query/InsertQuery.php diff --git a/package/Query/InseertQuery.php b/package/Query/InseertQuery.php deleted file mode 100644 index 140ad8d..0000000 --- a/package/Query/InseertQuery.php +++ /dev/null @@ -1,8 +0,0 @@ - - * @date 2017/8/25 - * @license Mozilla - */ diff --git a/package/Query/InsertQuery.php b/package/Query/InsertQuery.php new file mode 100644 index 0000000..f331409 --- /dev/null +++ b/package/Query/InsertQuery.php @@ -0,0 +1,49 @@ + + * @date 2017/8/25 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:对于数组长度比较大,关键字分布又是比较均匀的来说,插值查找的效率比折半查找的效率高 + * ------------------------------------------------------------- + * 它是二分查找的改进。 + * 在英文词典里查找“apple”,你下意识里翻开词典是翻前面的书页还是后面的书页呢?如果再查“zoo”,你又会怎么查? + * 显然你不会从词典中间开始查起,而是有一定目的地往前或往后翻。 + * + * @param $container + * @param $num + * @return int + */ +function insertQuery(array $container, $num) +{ + $count = count($container); + $lower = 0; + $high = $count - 1; + + while ($lower <= $high) { + if ($container[ $lower ] == $num) { + return $lower; + } + if ($container[ $high ] == $num) { + return $high; + } + + $left = intval($lower + $num - $container[ $lower ]); + $right = ($container[ $high ] - $container[ $lower ]) * ($high - $lower); + + $middle = $left /$right; + + if ($num < $container[ $middle ]) { + $high = $middle - 1; + } else if ($num > $container[ $middle ]) { + $lower = $middle + 1; + } else { + return $middle; + } + } + return false; +} + +echo insertQuery([4, 5, 7, 8, 9, 10, 8], 8); From cd15797c817247f0840502bdc924d6dbf265ea1e Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 26 Aug 2017 23:43:34 +0800 Subject: [PATCH 015/127] feat: apples & HanoiGames :construction_worker: --- README.md | 4 +++- package/Other/StealingApples.php | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 package/Other/StealingApples.php diff --git a/README.md b/README.md index 38bb8ab..bbe3b45 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,10 @@ │ │ │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 - │ ├── GetCattle.php 牛年求牛 │ ├── Fibonacci.php 斐波那契数列 + │ ├── StealingApples.php 偷苹果求余 + │ ├── HanoiGames.php 汉诺塔游戏 + │ ├── GetCattle.php 牛年求牛 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php new file mode 100644 index 0000000..4b981ff --- /dev/null +++ b/package/Other/StealingApples.php @@ -0,0 +1,8 @@ + + * @date 2017/8/26 + * @license Mozilla + */ From cc655ebbcca843b1fbdb7ad0694650fa10b419ec Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 26 Aug 2017 23:43:50 +0800 Subject: [PATCH 016/127] feat: new arithmetic :twisted_rightwards_arrows: --- package/Other/HanoiGames.php | 52 ++++++++++++++++++++++++++++++++ package/Other/MonkeyKing.php | 20 +++++++++++- package/Other/StealingApples.php | 42 ++++++++++++++++++++++++-- 3 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 package/Other/HanoiGames.php diff --git a/package/Other/HanoiGames.php b/package/Other/HanoiGames.php new file mode 100644 index 0000000..10e54e1 --- /dev/null +++ b/package/Other/HanoiGames.php @@ -0,0 +1,52 @@ + + * @date 2017/8/26 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析: + * ------------------------------------------------------------- + * 汉诺塔(又称河内塔)问题是印度的一个古老的传说。 + * 开天辟地的神勃拉玛在一个庙里留下了三根金刚石的棒, + * 第一根上面套着64个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去, + * 庙里的众僧不倦地把它们一个个地从这根棒搬到另一根棒上,规定可利用中间的一根棒作为帮助, + * 但每次只能搬一个,而且大的不能放在小的上面。 + * + * 面对庞大的数字(移动圆片的次数)18446744073709551615,看来,众僧们耗尽毕生精力也不可能完成金片的移动。 + * + * 后来,这个传说就演变为汉诺塔游戏: + * 1.有三根杆子A,B,C。A杆上有若干碟子 + * 2.每次移动一块碟子,小的只能叠在大的上面 + * 3.把所有碟子从A杆全部移到C杆上 + * 经过研究发现,汉诺塔的破解很简单,就是按照移动规则向一个方向移动金片: + * 如3阶汉诺塔的移动:A→C,A→B,C→B,A→C,B→A,B→C,A→C + * 此外,汉诺塔问题也是程序设计中的经典递归问题。 + * + * @param $n + * @param $x + * @param $y + * @param $z + */ +function HanoiGames($n, $x, $y, $z) +{ + if ($n == 1) { + echo 'move disk 1 from ' . $x . ' to ' . $z . "\n"; + } else { + HanoiGames($n - 1, $x, $z, $y); + echo 'move disk ' . $n . ' from ' . $x . ' to ' . $z . "\n"; + HanoiGames($n - 1, $y, $x, $z); + } +} + +HanoiGames(3, 'A', 'B', 'C'); + +// move disk 1 from A to C +// move disk 2 from A to B +// move disk 1 from C to B +// move disk 3 from A to C +// move disk 1 from B to A +// move disk 2 from B to C +// move disk 1 from A to C diff --git a/package/Other/MonkeyKing.php b/package/Other/MonkeyKing.php index d07a2e9..45e645e 100644 --- a/package/Other/MonkeyKing.php +++ b/package/Other/MonkeyKing.php @@ -72,4 +72,22 @@ function whoIsKing($n,$m){ return $r+1; } -var_dump(whoIsKing(10,3)); \ No newline at end of file +var_dump(whoIsKing(10,3)); + +function king($n, $m){ + $monkeys = range(1, $n); + $i=0; + $k=$n; + while (count($monkeys)>1) { + if(($i+1)%$m==0) { + unset($monkeys[$i]); + } else { + array_push($monkeys,$monkeys[$i]); + unset($monkeys[$i]); + } + $i++; + } + return current($monkeys); +} +$a = king(10, 3); +var_dump($a); \ No newline at end of file diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php index 4b981ff..d1a04f5 100644 --- a/package/Other/StealingApples.php +++ b/package/Other/StealingApples.php @@ -1,8 +1,46 @@ + * @author Pu ShaoWei * @date 2017/8/26 * @license Mozilla + * ------------------------------------------------------------- + * 思路分析: + * ------------------------------------------------------------- + * 有5个人偷了一堆苹果,准备在第二天分赃。 + * 晚上,有一人遛出来,把所有苹果分成5份,但是多了一个,顺手把这个扔给树上的猴了,自己先拿1/5藏了。 + * 没想到其他四人也都是这么想的,都如第一个人一样分成5份把多的那一个扔给了猴,偷走了1/5。 + * 第二天,大家分赃,也是分成5份多一个扔给猴了。最后一人分了一份。 + * 问:共有多少苹果?N 个人呢? */ + +$i = 1; +while (true) { + if ($i % 5 == 1) { + //第一个人取五分之一,还剩$t + $t = $i - round($i / 5) - 1; + if ($t % 5 == 1) { + //第二个人取五分之一,还剩$r + $r = $t - round($t / 5) - 1; + if ($r % 5 == 1) { + //第三个人取五分之一,还剩$s + $s = $r - round($r / 5) - 1; + if ($s % 5 == 1) { + //第四个人取五分之一,还剩$x + $x = $s - round($s / 5) - 1; + if ($x % 5 == 1) { + //第五个人取五分之一,还剩$y + $y = $x - round($x / 5) - 1; + if ($y % 5 == 1) { + echo $i; + break; + } + } + } + } + } + } + $i++; +} \ No newline at end of file From d46a9604c44c0facf019983d3cb06cf51ffbdc68 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 28 Aug 2017 09:47:33 +0800 Subject: [PATCH 017/127] fix: modify LICENSE :robot: --- LICENSE | 397 +++----------------------------------------------------- 1 file changed, 21 insertions(+), 376 deletions(-) diff --git a/LICENSE b/LICENSE index 00f89f5..8d0adb8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,376 +1,21 @@ -Mozilla Public License Version 2.0 -================================== - -1. Definitions --------------- - -1.1. "Contributor" - means each individual or legal entity that creates, contributes to - the creation of, or owns Covered Software. - -1.2. "Contributor Version" - means the combination of the Contributions of others (if any) used - by a Contributor and that particular Contributor's Contribution. - -1.3. "Contribution" - means Covered Software of a particular Contributor. - -1.4. "Covered Software" - means Source Code Form to which the initial Contributor has attached - the notice in Exhibit A, the Executable Form of such Source Code - Form, and Modifications of such Source Code Form, in each case - including portions thereof. - -1.5. "Incompatible With Secondary Licenses" - means - - (a) that the initial Contributor has attached the notice described - in Exhibit B to the Covered Software; or - - (b) that the Covered Software was made available under the terms of - version 1.1 or earlier of the License, but not also under the - terms of a Secondary License. - -1.6. "Executable Form" - means any form of the work other than Source Code Form. - -1.7. "Larger Work" - means a work that combines Covered Software with other material, in - a separate file or files, that is not Covered Software. - -1.8. "License" - means this document. - -1.9. "Licensable" - means having the right to grant, to the maximum extent possible, - whether at the time of the initial grant or subsequently, any and - all of the rights conveyed by this License. - -1.10. "Modifications" - means any of the following: - - (a) any file in Source Code Form that results from an addition to, - deletion from, or modification of the contents of Covered - Software; or - - (b) any new file in Source Code Form that contains any Covered - Software. - -1.11. "Patent Claims" of a Contributor - means any patent claim(s), including without limitation, method, - process, and apparatus claims, in any patent Licensable by such - Contributor that would be infringed, but for the grant of the - License, by the making, using, selling, offering for sale, having - made, import, or transfer of either its Contributions or its - Contributor Version. - -1.12. "Secondary License" - means either the GNU General Public License, Version 2.0, the GNU - Lesser General Public License, Version 2.1, the GNU Affero General - Public License, Version 3.0, or any later versions of those - licenses. - -1.13. "Source Code Form" - means the form of the work preferred for making modifications. - -1.14. "You" (or "Your") - means an individual or a legal entity exercising rights under this - License. For legal entities, "You" includes any entity that - controls, is controlled by, or is under common control with You. For - purposes of this definition, "control" means (a) the power, direct - or indirect, to cause the direction or management of such entity, - whether by contract or otherwise, or (b) ownership of more than - fifty percent (50%) of the outstanding shares or beneficial - ownership of such entity. - -2. License Grants and Conditions --------------------------------- - -2.1. Grants - -Each Contributor hereby grants You a world-wide, royalty-free, -non-exclusive license: - -(a) under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or - as part of a Larger Work; and - -(b) under Patent Claims of such Contributor to make, use, sell, offer - for sale, have made, import, and otherwise transfer either its - Contributions or its Contributor Version. - -2.2. Effective Date - -The licenses granted in Section 2.1 with respect to any Contribution -become effective for each Contribution on the date the Contributor first -distributes such Contribution. - -2.3. Limitations on Grant Scope - -The licenses granted in this Section 2 are the only rights granted under -this License. No additional rights or licenses will be implied from the -distribution or licensing of Covered Software under this License. -Notwithstanding Section 2.1(b) above, no patent license is granted by a -Contributor: - -(a) for any code that a Contributor has removed from Covered Software; - or - -(b) for infringements caused by: (i) Your and any other third party's - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - -(c) under Patent Claims infringed by Covered Software in the absence of - its Contributions. - -This License does not grant any rights in the trademarks, service marks, -or logos of any Contributor (except as may be necessary to comply with -the notice requirements in Section 3.4). - -2.4. Subsequent Licenses - -No Contributor makes additional grants as a result of Your choice to -distribute the Covered Software under a subsequent version of this -License (see Section 10.2) or under the terms of a Secondary License (if -permitted under the terms of Section 3.3). - -2.5. Representation - -Each Contributor represents that the Contributor believes its -Contributions are its original creation(s) or it has sufficient rights -to grant the rights to its Contributions conveyed by this License. - -2.6. Fair Use - -This License is not intended to limit any rights You have under -applicable copyright doctrines of fair use, fair dealing, or other -equivalents. - -2.7. Conditions - -Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted -in Section 2.1. - -3. Responsibilities -------------------- - -3.1. Distribution of Source Form - -All distribution of Covered Software in Source Code Form, including any -Modifications that You create or to which You contribute, must be under -the terms of this License. You must inform recipients that the Source -Code Form of the Covered Software is governed by the terms of this -License, and how they can obtain a copy of this License. You may not -attempt to alter or restrict the recipients' rights in the Source Code -Form. - -3.2. Distribution of Executable Form - -If You distribute Covered Software in Executable Form then: - -(a) such Covered Software must also be made available in Source Code - Form, as described in Section 3.1, and You must inform recipients of - the Executable Form how they can obtain a copy of such Source Code - Form by reasonable means in a timely manner, at a charge no more - than the cost of distribution to the recipient; and - -(b) You may distribute such Executable Form under the terms of this - License, or sublicense it under different terms, provided that the - license for the Executable Form does not attempt to limit or alter - the recipients' rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - -You may create and distribute a Larger Work under terms of Your choice, -provided that You also comply with the requirements of this License for -the Covered Software. If the Larger Work is a combination of Covered -Software with a work governed by one or more Secondary Licenses, and the -Covered Software is not Incompatible With Secondary Licenses, this -License permits You to additionally distribute such Covered Software -under the terms of such Secondary License(s), so that the recipient of -the Larger Work may, at their option, further distribute the Covered -Software under the terms of either this License or such Secondary -License(s). - -3.4. Notices - -You may not remove or alter the substance of any license notices -(including copyright notices, patent notices, disclaimers of warranty, -or limitations of liability) contained within the Source Code Form of -the Covered Software, except that You may alter any license notices to -the extent required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - -You may choose to offer, and to charge a fee for, warranty, support, -indemnity or liability obligations to one or more recipients of Covered -Software. However, You may do so only on Your own behalf, and not on -behalf of any Contributor. You must make it absolutely clear that any -such warranty, support, indemnity, or liability obligation is offered by -You alone, and You hereby agree to indemnify every Contributor for any -liability incurred by such Contributor as a result of warranty, support, -indemnity or liability terms You offer. You may include additional -disclaimers of warranty and limitations of liability specific to any -jurisdiction. - -4. Inability to Comply Due to Statute or Regulation ---------------------------------------------------- - -If it is impossible for You to comply with any of the terms of this -License with respect to some or all of the Covered Software due to -statute, judicial order, or regulation then You must: (a) comply with -the terms of this License to the maximum extent possible; and (b) -describe the limitations and the code they affect. Such description must -be placed in a text file included with all distributions of the Covered -Software under this License. Except to the extent prohibited by statute -or regulation, such description must be sufficiently detailed for a -recipient of ordinary skill to be able to understand it. - -5. Termination --------------- - -5.1. The rights granted under this License will terminate automatically -if You fail to comply with any of its terms. However, if You become -compliant, then the rights granted under this License from a particular -Contributor are reinstated (a) provisionally, unless and until such -Contributor explicitly and finally terminates Your grants, and (b) on an -ongoing basis, if such Contributor fails to notify You of the -non-compliance by some reasonable means prior to 60 days after You have -come back into compliance. Moreover, Your grants from a particular -Contributor are reinstated on an ongoing basis if such Contributor -notifies You of the non-compliance by some reasonable means, this is the -first time You have received notice of non-compliance with this License -from such Contributor, and You become compliant prior to 30 days after -Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent -infringement claim (excluding declaratory judgment actions, -counter-claims, and cross-claims) alleging that a Contributor Version -directly or indirectly infringes any patent, then the rights granted to -You by any and all Contributors for the Covered Software under Section -2.1 of this License shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all -end user license agreements (excluding distributors and resellers) which -have been validly granted by You or Your distributors under this License -prior to termination shall survive termination. - -************************************************************************ -* * -* 6. Disclaimer of Warranty * -* ------------------------- * -* * -* Covered Software is provided under this License on an "as is" * -* basis, without warranty of any kind, either expressed, implied, or * -* statutory, including, without limitation, warranties that the * -* Covered Software is free of defects, merchantable, fit for a * -* particular purpose or non-infringing. The entire risk as to the * -* quality and performance of the Covered Software is with You. * -* Should any Covered Software prove defective in any respect, You * -* (not any Contributor) assume the cost of any necessary servicing, * -* repair, or correction. This disclaimer of warranty constitutes an * -* essential part of this License. No use of any Covered Software is * -* authorized under this License except under this disclaimer. * -* * -************************************************************************ - -************************************************************************ -* * -* 7. Limitation of Liability * -* -------------------------- * -* * -* Under no circumstances and under no legal theory, whether tort * -* (including negligence), contract, or otherwise, shall any * -* Contributor, or anyone who distributes Covered Software as * -* permitted above, be liable to You for any direct, indirect, * -* special, incidental, or consequential damages of any character * -* including, without limitation, damages for lost profits, loss of * -* goodwill, work stoppage, computer failure or malfunction, or any * -* and all other commercial damages or losses, even if such party * -* shall have been informed of the possibility of such damages. This * -* limitation of liability shall not apply to liability for death or * -* personal injury resulting from such party's negligence to the * -* extent applicable law prohibits such limitation. Some * -* jurisdictions do not allow the exclusion or limitation of * -* incidental or consequential damages, so this exclusion and * -* limitation may not apply to You. * -* * -************************************************************************ - -8. Litigation -------------- - -Any litigation relating to this License may be brought only in the -courts of a jurisdiction where the defendant maintains its principal -place of business and such litigation shall be governed by laws of that -jurisdiction, without reference to its conflict-of-law provisions. -Nothing in this Section shall prevent a party's ability to bring -cross-claims or counter-claims. - -9. Miscellaneous ----------------- - -This License represents the complete agreement concerning the subject -matter hereof. If any provision of this License is held to be -unenforceable, such provision shall be reformed only to the extent -necessary to make it enforceable. Any law or regulation which provides -that the language of a contract shall be construed against the drafter -shall not be used to construe this License against a Contributor. - -10. Versions of the License ---------------------------- - -10.1. New Versions - -Mozilla Foundation is the license steward. Except as provided in Section -10.3, no one other than the license steward has the right to modify or -publish new versions of this License. Each version will be given a -distinguishing version number. - -10.2. Effect of New Versions - -You may distribute the Covered Software under the terms of the version -of the License under which You originally received the Covered Software, -or under the terms of any subsequent version published by the license -steward. - -10.3. Modified Versions - -If you create software not governed by this License, and you want to -create a new license for such software, you may create and use a -modified version of this License if you rename the license and remove -any references to the name of the license steward (except to note that -such modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary -Licenses - -If You choose to distribute Source Code Form that is Incompatible With -Secondary Licenses under the terms of this version of the License, the -notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice -------------------------------------------- - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular -file, then You may include the notice in a location (such as a LICENSE -file in a relevant directory) where a recipient would be likely to look -for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - "Incompatible With Secondary Licenses" Notice ---------------------------------------------------------- - - This Source Code Form is "Incompatible With Secondary Licenses", as - defined by the Mozilla Public License, v. 2.0. - -Contact GitHub API Training Shop Blog About -© 2017 GitHub, Inc. Terms Privacy Security Status Help .Shao Wei \ No newline at end of file +MIT License + +Copyright (c) 2017 Shaowei pu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 144107918f590c2691e91f496b513b11b457b411 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 28 Aug 2017 09:47:53 +0800 Subject: [PATCH 018/127] feat: add DynamicProgramming :construction_worker: --- package/Other/DynamicProgramming.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 package/Other/DynamicProgramming.php diff --git a/package/Other/DynamicProgramming.php b/package/Other/DynamicProgramming.php new file mode 100644 index 0000000..b1a4a1f --- /dev/null +++ b/package/Other/DynamicProgramming.php @@ -0,0 +1,22 @@ + + * @date 2017/8/28 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析: + * ------------------------------------------------------------- + * 题目放在这里,9点来完成实例 + * + * @param $n + * @return int + */ +function DynamicProgramming( $str ) +{ + +} + + From 0b92574e5aafb33f890a6ad9acaa13ba4eedc1c9 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 28 Aug 2017 09:48:09 +0800 Subject: [PATCH 019/127] feat: new arithmetic :white_check_mark: --- README.md | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index bbe3b45..d458f1b 100644 --- a/README.md +++ b/README.md @@ -17,26 +17,27 @@ ├──Package │ ├── Sort 排序篇 - │ │ ├── BubbleSort.php 冒泡排序 - │ │ ├── QuickSort.php 快速排序 - │ │ ├── ShellSort.php 希尔排序 - │ │ ├── MergeSort.php 归并排序 - │ │ ├── InsertSort.php 插入排序 - │ │ └── SelectSort.php 选择排序 + │ │ ├── BubbleSort.php 冒泡排序 + │ │ ├── QuickSort.php 快速排序 + │ │ ├── ShellSort.php 希尔排序 + │ │ ├── MergeSort.php 归并排序 + │ │ ├── InsertSort.php 插入排序 + │ │ └── SelectSort.php 选择排序 │ │ │ ├── Query 查找篇 - │ │ ├── BinaryQuery.php 二分查找 - │ │ ├── InseertQuery.php 插入查找 - │ │ ├── FibonacciQuery.php 斐波那契查找 - │ │ └── QulickQuery.php 快速查找 + │ │ ├── BinaryQuery.php 二分查找 + │ │ ├── InseertQuery.php 插入查找 + │ │ ├── FibonacciQuery.php 斐波那契查找 + │ │ └── QulickQuery.php 快速查找 │ │ │ └── Other 其他 - │ ├── MonkeyKing.php 猴子选大王 - │ ├── Fibonacci.php 斐波那契数列 - │ ├── StealingApples.php 偷苹果求余 - │ ├── HanoiGames.php 汉诺塔游戏 - │ ├── GetCattle.php 牛年求牛 - │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow + │ ├── MonkeyKing.php 猴子选大王 + │ ├── DynamicProgramming.php 动态规划 + │ ├── Fibonacci.php 斐波那契数列 + │ ├── StealingApples.php 偷苹果求余 + │ ├── HanoiGames.php 汉诺塔游戏 + │ ├── GetCattle.php 牛年求牛 + │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE └──README.md From e8f96d93bedf29dbaae1e30e0fcd0f42ea2a3113 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 28 Aug 2017 21:35:46 +0800 Subject: [PATCH 020/127] feat: dynamic programming :speech_balloon: --- package/Other/DynamicProgramming.php | 39 +++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/package/Other/DynamicProgramming.php b/package/Other/DynamicProgramming.php index b1a4a1f..8d04f26 100644 --- a/package/Other/DynamicProgramming.php +++ b/package/Other/DynamicProgramming.php @@ -7,16 +7,43 @@ * @date 2017/8/28 * @license Mozilla * ------------------------------------------------------------- - * 思路分析: + * 思路分析:动态规划原理思想,max(opt(i-1,w),wi+opt(i-1,w-wi)) 当中最大值,opt(i-1,w-wi)指上一个最优解 * ------------------------------------------------------------- - * 题目放在这里,9点来完成实例 - * - * @param $n + * 一个承受最大重量为W的背包,现在有n个物品,每个物品重量为t, 每个物品的价值为v。 + * 要使得这个背包重量最大(但不能超过W),同时又需要背包的价值最大 + * * @return int */ -function DynamicProgramming( $str ) +function DynamicProgramming( $maxSize ,$goods, $cost) { + $container = []; + $goodsCount = count($goods); + //初始化 + for ($i = 0; $i <= $maxSize; $i++) { + $container[0][$i] = 0; + } + for ($j = 0; $j <= $goodsCount; $j++) { + $container[$j][0] = 0; + } + for ($j = 1; $j <= $goodsCount; $j++) { + for ($i = 1; $i <= $maxSize; $i++) { + $container[$j][$i] = $container[$j - 1][$i]; + //不大于最大的w=15 + if ($goods[$j - 1] <= $maxSize) { + if (!isset($container[ $j - 1 ][ $i - $goods[ $j - 1 ] ])) { + continue; + } + //wi+opt(i-1,wi) + $tmp = $container[ $j - 1 ][ $i - $goods[ $j - 1 ] ] + $cost[ $j - 1 ]; + //opt(i-1,w),wi+opt(i-1,w-wi) => 进行比较 + if ($tmp > $container[$j][$i]) { + $container[$j][$i] = $tmp; + } + } + } + } + var_dump($container[$j-1][$i - 1]); } - +echo DynamicProgramming(15, [3, 4, 5, 6], [8, 7, 4, 9]); From 7db8f55db7799b97f5eeefa3b7159fa91a91c0d6 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 29 Aug 2017 13:46:49 +0800 Subject: [PATCH 021/127] fix: modify fail :twisted_rightwards_arrows: --- package/Sort/QuickSort.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index 845a296..684ef0c 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -12,11 +12,13 @@ * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 * * @param array $container - * @return array|void + * @return mixed */ function QulickSort( array $container ){ $count = count( $container ); - if( $count <= 1 ) return; + if( $count <= 1 ) { + return $container; + } $left = $right = []; for ( $i =0; $i<$count-1;$i++ ){ if( $container[$i] < $container[0] ){ @@ -26,7 +28,7 @@ function QulickSort( array $container ){ } } $left = QulickSort($left); $right = QulickSort($right); - return array_merge($left,[$container[0],$right]); + return array_merge($left,[$container[0]],$right); } var_dump( QulickSort([4,21,41,2,53,1,213,31,21,423]) ); \ No newline at end of file From 3b7d305caa63903f20089817fa04bb3487c0869c Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 29 Aug 2017 13:57:53 +0800 Subject: [PATCH 022/127] fix: modify Styles and errors :lipstick: --- package/Other/MonkeyKing.php | 2 +- package/Sort/QuickSort.php | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/package/Other/MonkeyKing.php b/package/Other/MonkeyKing.php index 45e645e..c1fca9f 100644 --- a/package/Other/MonkeyKing.php +++ b/package/Other/MonkeyKing.php @@ -9,7 +9,7 @@ * ------------------------------------------------------------- * 思路分析:约瑟夫环问题 * ------------------------------------------------------------- - *有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 + * 有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 */ class MonkeyKing { diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index 684ef0c..057effc 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -20,14 +20,15 @@ function QulickSort( array $container ){ return $container; } $left = $right = []; - for ( $i =0; $i<$count-1;$i++ ){ - if( $container[$i] < $container[0] ){ - $left[] = $container[$i]; - }else{ - $right[]= $container[$i]; + for ($i = 1; $i < $count; $i++) { + if ($container[$i] < $container[0]) { + $left[] = $container[$i]; + } else { + $right[] = $container[$i]; } } - $left = QulickSort($left); $right = QulickSort($right); + $left = QulickSort($left); + $right = QulickSort($right); return array_merge($left,[$container[0]],$right); } From 0e7b11f9fb6651b1493f993736c32c234894a6a4 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 30 Aug 2017 21:02:15 +0800 Subject: [PATCH 023/127] feat: Update on Wednesday :alien: --- package/Other/OnlyNumbers.php | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 package/Other/OnlyNumbers.php diff --git a/package/Other/OnlyNumbers.php b/package/Other/OnlyNumbers.php new file mode 100644 index 0000000..9a08ba1 --- /dev/null +++ b/package/Other/OnlyNumbers.php @@ -0,0 +1,32 @@ + + * @date 2017/8/30 + * @license Mozilla + * ------------------------------------------------------------- + * 思路分析:快排同时做唯一标示 + * ------------------------------------------------------------- + * 一个数组里只有唯一一个元素是不同于别的元素,其余元素是两两相等如何得到这个元素 + * + * @param array $container + * @return mixed + */ +function OnlyNumbers(array $container){ + $count = count($container); + if( $count <= 1 ) { + return $container; + } + $exist = []; + for ($i = 0; $i < $count; $i++) { + if(isset($exist[$container[$i]])){ + unset($exist[$container[$i]]); + continue; + } + $exist[$container[$i]] = true; + } + return !empty($exist) ? array_keys($exist)[0] : false; +} +var_dump(OnlyNumbers([11,22,22,11,5,63,13,5,63,18,89,13,89])); \ No newline at end of file From 46b9f602f8df5d8819cd0ac3c1e45c00f73a8ace Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 30 Aug 2017 21:02:57 +0800 Subject: [PATCH 024/127] feat: add only number :robot: --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d458f1b..31c8176 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ │ ├── StealingApples.php 偷苹果求余 │ ├── HanoiGames.php 汉诺塔游戏 │ ├── GetCattle.php 牛年求牛 + │ ├── OnlyNumbers.php 求唯一数 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE From f81f5a2c45509e5a13c43a8956a814a2b9127e8e Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 2 Sep 2017 15:53:15 +0800 Subject: [PATCH 025/127] feat: ColorBricks :green_heart: --- package/Other/ColorBricks.php | 71 ++++++++++++++++++++++++++++ package/Other/DynamicProgramming.php | 15 +++--- 2 files changed, 78 insertions(+), 8 deletions(-) create mode 100644 package/Other/ColorBricks.php diff --git a/package/Other/ColorBricks.php b/package/Other/ColorBricks.php new file mode 100644 index 0000000..e962b60 --- /dev/null +++ b/package/Other/ColorBricks.php @@ -0,0 +1,71 @@ + + * @date 2017/9/1 + * @license MIT + * ------------------------------------------------------------- + * 思路分析:额。。。 没做出来求大佬带 + * ------------------------------------------------------------- + * 小易有一些彩色的砖块。每种颜色由一个大写字母表示。各个颜色砖块看起来都完全一样。 + * 现在有一个给定的字符串s,s中每个字符代表小易的某个砖块的颜色。小易想把他所有的砖块排成一行。 + * 如果最多存在一对不同颜色的相邻砖块,那么这行砖块就很漂亮的。 + * ------------------------------------------------------------- + * 请你帮助小易计算有多少种方式将他所有砖块排成漂亮的一行。(如果两种方式所对应的砖块颜色序列是相同的,那么认为这两种方式是一样的。) + * ------------------------------------------------------------- + * 例如: s = "ABAB",那么小易有六种排列的结果: + * "AABB","ABAB","ABBA","BAAB","BABA","BBAA" + * 其中只有"AABB"和"BBAA"满足最多只有一对不同颜色的相邻砖块。 + * ------- + * 输入描述: + * 输入包括一个字符串s,字符串s的长度length(1 ≤ length ≤ 50), [s中的每一个字符都为一个大写字母(A到Z)]。 + * 输出描述: + * 输出一个整数,表示小易可以有多少种方式。 + * ------- + * 输入例子1: + * ABAB + * 输出例子1: + * 2 + * @param $inputting + * @return mixed + */ +function ColorBricks($inputting) +{ + $str = ord($inputting); + $strLen = strlen($inputting); +// if (!($str > 64 && $str < 91) || +// !(1 <= $strLen && $strLen <= 50) +// ) { +// return false; +// } + $group = []; + $temp = ''; + + // 表示标排列 有24 种排列方式 + // 0123 0132 0213 0231 0312 0321 + // 1023 1032 1203 1230 1320 1302 + // 2013 2031 2130 2103 2301 2310 + // 3012 3021 3120 3102 3201 3210 + + // 0123 0132 + // 0213 0231 + // 0312 0321 + + // 额。。。 没做出来求大佬带 + + for ($i = 1; $i < $strLen; $i++) { +// $group[$inputting] = true; + for ($j = 1; $j < $strLen ; $j++) { + echo $i, $j, PHP_EOL; + if (isset($inputting[$i + 1])) { + $temp = $inputting[$i]; + $inputting[$i] = $inputting[$i + 1]; + $inputting[$i + 1] = $temp; + } + } + } + var_dump($group); +} + +echo ColorBricks("AABB"); \ No newline at end of file diff --git a/package/Other/DynamicProgramming.php b/package/Other/DynamicProgramming.php index 8d04f26..2e71008 100644 --- a/package/Other/DynamicProgramming.php +++ b/package/Other/DynamicProgramming.php @@ -11,12 +11,11 @@ * ------------------------------------------------------------- * 一个承受最大重量为W的背包,现在有n个物品,每个物品重量为t, 每个物品的价值为v。 * 要使得这个背包重量最大(但不能超过W),同时又需要背包的价值最大 - * * @return int */ -function DynamicProgramming( $maxSize ,$goods, $cost) +function DynamicProgramming($maxSize, $goods, $cost) { - $container = []; + $container = []; $goodsCount = count($goods); //初始化 @@ -31,19 +30,19 @@ function DynamicProgramming( $maxSize ,$goods, $cost) $container[$j][$i] = $container[$j - 1][$i]; //不大于最大的w=15 if ($goods[$j - 1] <= $maxSize) { - if (!isset($container[ $j - 1 ][ $i - $goods[ $j - 1 ] ])) { + if (!isset($container[$j - 1][$i - $goods[$j - 1]])) { continue; } - //wi+opt(i-1,wi) - $tmp = $container[ $j - 1 ][ $i - $goods[ $j - 1 ] ] + $cost[ $j - 1 ]; - //opt(i-1,w),wi+opt(i-1,w-wi) => 进行比较 + //wi+opt(i-1,wi) + $tmp = $container[$j - 1][$i - $goods[$j - 1]] + $cost[$j - 1]; + //opt(i-1,w),wi+opt(i-1,w-wi) => 进行比较 if ($tmp > $container[$j][$i]) { $container[$j][$i] = $tmp; } } } } - var_dump($container[$j-1][$i - 1]); + var_dump($container[$j - 1][$i - 1]); } echo DynamicProgramming(15, [3, 4, 5, 6], [8, 7, 4, 9]); From 7fc608a064ecfa24959e778c27363bd194d746f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E9=80=89=E5=85=A5?= <1107099011@qq.com> Date: Mon, 4 Sep 2017 18:15:34 +0800 Subject: [PATCH 026/127] add ColorBricks how to write add ColorBricks how to write --- package/Other/ColorBricks.php | 69 ++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/package/Other/ColorBricks.php b/package/Other/ColorBricks.php index e962b60..238145c 100644 --- a/package/Other/ColorBricks.php +++ b/package/Other/ColorBricks.php @@ -68,4 +68,71 @@ function ColorBricks($inputting) var_dump($group); } -echo ColorBricks("AABB"); \ No newline at end of file +echo ColorBricks("AABB"); + + +#########################3 + + + + function ColorBricks2($str) + { + $count = strlen($str); + $data = array(); + for($i = 0; $i < $count; $i++){ + $data[] = $str[$i]; + } + $a = pre2($data); + } + + /* + 思路分析: + + * 例如: s = "ABAB",那么小易有六种排列的结果: + * "AABB","ABAB","ABBA","BAAB", "BBAA" "BABA", + 1-2 0 2-3 0-1 0-3 1-2 + "ABAB", 0 + "BAAB", 0-1 + "AABB", 0-2 + "BABA" 0-3 + "ABBA", 1-2 + "BBAA" 1-3 + + */ + + function pre2($data) + { + $c = count($data); + $new = array(); + $max = floor($c/2); + for($i = 0; $i < $max;$i++){ + for($j = 1; $j < $c;$j++){ + $temp = $data[$j]; + $data[$j] = $data[0]; + $data[0] = $temp; + $new[] = implode("",$data); + echo '0##'.$j.'
'; + } + } + $nMax = count($new); + $successNumber = 0; + for($i = 0 ; $i < $max;$i++){ + $success = false; + for($j = 0; $j < $nMax;$j++){ + $str = $new[$j]; + if($str[$i] == $str[0]){ + $success = true; + } + } + if($success)$successNumber++; + } + echo '
'; 
+	   echo "小易可以有{$successNumber}种方式";
+	   echo "



"; + print_r($new); + exit; + } + $str = "ABAB"; + ColorBricks2($str); + + From 8df4b8c6d82ee7c16b8b2e2ef0d6aa0de1dd2b94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E9=80=89=E5=85=A5?= <1107099011@qq.com> Date: Mon, 4 Sep 2017 18:16:14 +0800 Subject: [PATCH 027/127] Update ColorBricks.php --- package/Other/ColorBricks.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package/Other/ColorBricks.php b/package/Other/ColorBricks.php index 238145c..f222686 100644 --- a/package/Other/ColorBricks.php +++ b/package/Other/ColorBricks.php @@ -71,7 +71,7 @@ function ColorBricks($inputting) echo ColorBricks("AABB"); -#########################3 +######################################### From b3f5ef8a4f11216c1e7c514d86def18d2d95dc1c Mon Sep 17 00:00:00 2001 From: Openset Date: Tue, 5 Sep 2017 12:21:04 +0800 Subject: [PATCH 028/127] Add BubbleSortV2 --- package/Sort/BubbleSort.php | 52 +++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/package/Sort/BubbleSort.php b/package/Sort/BubbleSort.php index e05b775..66c0133 100644 --- a/package/Sort/BubbleSort.php +++ b/package/Sort/BubbleSort.php @@ -15,21 +15,22 @@ * @param array $container * @return array */ -function BubbleSort( array $container ) { +function BubbleSort(array $container) +{ $count = count($container); - for ( $j = 1; $j < $count; $j++ ) { - for ( $i = 0; $i < $count - $j; $i++ ) { - if ( $container[$i] > $container[$i + 1] ) { + for ($j = 1; $j < $count; $j++) { + for ($i = 0; $i < $count - $j; $i++) { + if ($container[$i] > $container[$i + 1]) { $temp = $container[$i]; - $container[$i] = $container[$i+1]; - $container[$i+1] = $temp; + $container[$i] = $container[$i + 1]; + $container[$i + 1] = $temp; } } } return $container; } -var_dump( BubbleSort([4,21,41,2,53,1,213,31,21,423]) ); +var_dump(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); /* array(10) { @@ -54,4 +55,39 @@ function BubbleSort( array $container ) { [9] => int(423) } - */ \ No newline at end of file + */ + +// +---------------------------------------------------------------------- +// | 方法二 +// +---------------------------------------------------------------------- +function BubbleSortV2(array $container) +{ + $len = count($container); + // 也可以用foreach + for ($i = 0; $i < $len; $i++) { + for ($j = $i + 1; $j < $len; $j++) { + if ($container[$i] > $container[$j]) { + list($container[$i], $container[$j]) = array($container[$j], $container[$i]); + } + } + } + + return $container; +} + +print_r(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); +/* +Array +( + [0] => 1 + [1] => 2 + [2] => 4 + [3] => 21 + [4] => 21 + [5] => 31 + [6] => 41 + [7] => 53 + [8] => 213 + [9] => 423 +) + */ From 8cbcc37f8b2abcfd6840c62f46bc2e34aa6db02e Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 5 Sep 2017 13:14:27 +0800 Subject: [PATCH 029/127] fix: update style :checkered_flag: --- package/Other/ColorBricks.php | 137 ++++++++++------------------------ 1 file changed, 41 insertions(+), 96 deletions(-) diff --git a/package/Other/ColorBricks.php b/package/Other/ColorBricks.php index f222686..79fd236 100644 --- a/package/Other/ColorBricks.php +++ b/package/Other/ColorBricks.php @@ -6,7 +6,16 @@ * @date 2017/9/1 * @license MIT * ------------------------------------------------------------- - * 思路分析:额。。。 没做出来求大佬带 + * 思路分析: + * 例如: s = "ABAB",那么小易有六种排列的结果: + * "AABB","ABAB","ABBA","BAAB", "BBAA" "BABA", + * 1-2 0 2-3 0-1 0-3 1-2 + * "ABAB", 0 + * "BAAB", 0-1 + * "AABB", 0-2 + * "BABA" 0-3 + * "ABBA", 1-2 + * "BBAA" 1-3 * ------------------------------------------------------------- * 小易有一些彩色的砖块。每种颜色由一个大写字母表示。各个颜色砖块看起来都完全一样。 * 现在有一个给定的字符串s,s中每个字符代表小易的某个砖块的颜色。小易想把他所有的砖块排成一行。 @@ -32,107 +41,43 @@ */ function ColorBricks($inputting) { - $str = ord($inputting); - $strLen = strlen($inputting); -// if (!($str > 64 && $str < 91) || -// !(1 <= $strLen && $strLen <= 50) -// ) { -// return false; -// } - $group = []; - $temp = ''; + $count = strlen($inputting); + $ascii = ord($inputting); - // 表示标排列 有24 种排列方式 - // 0123 0132 0213 0231 0312 0321 - // 1023 1032 1203 1230 1320 1302 - // 2013 2031 2130 2103 2301 2310 - // 3012 3021 3120 3102 3201 3210 + if (!($ascii > 64 && $ascii < 91)) { + return false; + } + if (!(1 <= $count && $count <= 50)) { + return false; + } - // 0123 0132 - // 0213 0231 - // 0312 0321 + $container = array (); + $max = floor($count / 2); - // 额。。。 没做出来求大佬带 + for ($i = 0; $i < $max; $i++) { + for ($j = 1; $j < $count; $j++) { + $temp = $inputting[$j]; + $inputting[$j] = $inputting[0]; + $inputting[0] = $temp; + array_push($container, $inputting); + } + } + $containerCount = count($container); + $counter = 0; - for ($i = 1; $i < $strLen; $i++) { -// $group[$inputting] = true; - for ($j = 1; $j < $strLen ; $j++) { - echo $i, $j, PHP_EOL; - if (isset($inputting[$i + 1])) { - $temp = $inputting[$i]; - $inputting[$i] = $inputting[$i + 1]; - $inputting[$i + 1] = $temp; + for ($i = 0; $i < $max; $i++) { + $success = false; + for ($j = 0; $j < $containerCount; $j++) { + $str = $container[$j]; + if ($str[$i] == $str[0]) { + $success = true; } } + if ($success) { + $counter++; + } } - var_dump($group); + return $counter; } -echo ColorBricks("AABB"); - - -######################################### - - - - function ColorBricks2($str) - { - $count = strlen($str); - $data = array(); - for($i = 0; $i < $count; $i++){ - $data[] = $str[$i]; - } - $a = pre2($data); - } - - /* - 思路分析: - - * 例如: s = "ABAB",那么小易有六种排列的结果: - * "AABB","ABAB","ABBA","BAAB", "BBAA" "BABA", - 1-2 0 2-3 0-1 0-3 1-2 - "ABAB", 0 - "BAAB", 0-1 - "AABB", 0-2 - "BABA" 0-3 - "ABBA", 1-2 - "BBAA" 1-3 - - */ - - function pre2($data) - { - $c = count($data); - $new = array(); - $max = floor($c/2); - for($i = 0; $i < $max;$i++){ - for($j = 1; $j < $c;$j++){ - $temp = $data[$j]; - $data[$j] = $data[0]; - $data[0] = $temp; - $new[] = implode("",$data); - echo '0##'.$j.'
'; - } - } - $nMax = count($new); - $successNumber = 0; - for($i = 0 ; $i < $max;$i++){ - $success = false; - for($j = 0; $j < $nMax;$j++){ - $str = $new[$j]; - if($str[$i] == $str[0]){ - $success = true; - } - } - if($success)$successNumber++; - } - echo '
'; 
-	   echo "小易可以有{$successNumber}种方式";
-	   echo "



"; - print_r($new); - exit; - } - $str = "ABAB"; - ColorBricks2($str); - - +echo ColorBricks("AABB"); \ No newline at end of file From 91bd9b6ee4faba626a77250d27d04ac6c0fde215 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 5 Sep 2017 13:24:14 +0800 Subject: [PATCH 030/127] fix: update readme :lipstick: --- README.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 31c8176..0695904 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -用 PHP 的方式实现的各类算法合集 +

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

=============== [![Github file size](https://img.shields.io/github/size/webcaetano/craft/build/craft.min.js.svg)](https://github.com/PuShaoWei/arithmetic-php) @@ -8,6 +8,7 @@ [![Codacy grade](https://img.shields.io/codacy/grade/e27821fb6289410b8f58338c7e0bc686.svg)](https://github.com/PuShaoWei/arithmetic-php) [![AUR](https://img.shields.io/aur/license/yaourt.svg)]() + ## About > 如果说各种编程语言是程序员的招式,那么数据结构和算法就相当于程序员的内功。 @@ -36,6 +37,7 @@ │ ├── Fibonacci.php 斐波那契数列 │ ├── StealingApples.php 偷苹果求余 │ ├── HanoiGames.php 汉诺塔游戏 + │ ├── ColorBricks.php 彩色砖块 │ ├── GetCattle.php 牛年求牛 │ ├── OnlyNumbers.php 求唯一数 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow @@ -124,11 +126,19 @@ return i; ## 一起进步学习 - 1. Fork 我的项目 - 2. Pull Request + 1. Fork 我的项目并提交你的 `idea` + 2. Pull Request 3. Merge -## 纠错 +## 纠错 如果大家发现有什么不对的地方,可以发起一个[issue](https://github.com/PuShaoWei/arithmetic-php/issues)或者[pull request](https://github.com/PuShaoWei/arithmetic-php/pulls),我会及时纠正 > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) + +## 致谢 +感谢以下朋友的issue或pull request: + +- [hailwood ](https://github.com/hailwood) +- [zhangxuanru](https://github.com/zhangxuanru) +- [ifreesec](https://github.com/ifreesec) +- [openset](https://github.com/openset) \ No newline at end of file From 04cb13875edaac4b137b232a07c322e27fc49647 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 5 Sep 2017 13:34:34 +0800 Subject: [PATCH 031/127] fix: update readme :bookmark: --- README.md | 35 +++++++++++++++++++++++++---------- 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0695904..a169c15 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,34 @@ -

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

-=============== - -[![Github file size](https://img.shields.io/github/size/webcaetano/craft/build/craft.min.js.svg)](https://github.com/PuShaoWei/arithmetic-php) -[![](https://img.shields.io/github/issues-pr-raw/cdnjs/cdnjs.svg)](https://github.com/PuShaoWei/arithmetic-php) -[![PyPI](https://img.shields.io/pypi/status/Django.svg)](https://github.com/PuShaoWei/arithmetic-php) -[![Travis](https://img.shields.io/travis/rust-lang/rust.svg)](https://github.com/PuShaoWei/arithmetic-php) -[![Codacy grade](https://img.shields.io/codacy/grade/e27821fb6289410b8f58338c7e0bc686.svg)](https://github.com/PuShaoWei/arithmetic-php) -[![AUR](https://img.shields.io/aur/license/yaourt.svg)]() +

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

+ +

+ + php + + + Github file size + + + + + + + + + + + + + + + + +

## About > 如果说各种编程语言是程序员的招式,那么数据结构和算法就相当于程序员的内功。 - ## 简易结构 ├──Package From 3f5fdb7757b2fa31145cf8f6d8b186693d9f4c43 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 5 Sep 2017 13:36:39 +0800 Subject: [PATCH 032/127] fix: update readme :pencil2: --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index a169c15..09c553f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,9 @@ -

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

+

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

php - - Github file size - @@ -19,9 +16,6 @@ - - -

From 5afcdc516516cd6461a5586f49045f40b28588af Mon Sep 17 00:00:00 2001 From: Openset Date: Thu, 7 Sep 2017 17:29:11 +0800 Subject: [PATCH 033/127] refactor: StealingApples --- package/Other/StealingApples.php | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php index d1a04f5..42170b0 100644 --- a/package/Other/StealingApples.php +++ b/package/Other/StealingApples.php @@ -43,4 +43,27 @@ } } $i++; -} \ No newline at end of file +} + +// +---------------------------------------------------------------------- +// | 方法二 +// +---------------------------------------------------------------------- +/** + * @author Openset + * @date 2017/9/7 + * @param int $n N个人 + */ +for ($r = 1, $n = 5; ; $r++) { + $t = $r; + for ($i = 0; $i <= $n; $i++) { + if ($t % 5 == 1) { + $t = $t - round($t / 5) - 1; + } else { + continue 2; + } + } + echo $r; + break; +} + +//15621 From 6d0996a06d31cb7ddbd55cb4c314093f07d152c2 Mon Sep 17 00:00:00 2001 From: Openset Date: Thu, 7 Sep 2017 17:54:06 +0800 Subject: [PATCH 034/127] fix: openset --- package/Other/StealingApples.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php index 42170b0..6f09f56 100644 --- a/package/Other/StealingApples.php +++ b/package/Other/StealingApples.php @@ -49,9 +49,11 @@ // | 方法二 // +---------------------------------------------------------------------- /** - * @author Openset + * @author Openset + * @link https://github.com/openset * @date 2017/9/7 * @param int $n N个人 + * @param int $r 共有多少苹果 */ for ($r = 1, $n = 5; ; $r++) { $t = $r; From b2812a0903685349e97f5290a09484c56d96b0b6 Mon Sep 17 00:00:00 2001 From: Openset Date: Thu, 7 Sep 2017 21:11:04 +0800 Subject: [PATCH 035/127] Add: OnlyNumbersV2 --- package/Other/OnlyNumbers.php | 30 ++++++++++++++++++++++++++---- package/Other/StealingApples.php | 4 ++-- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/package/Other/OnlyNumbers.php b/package/Other/OnlyNumbers.php index 9a08ba1..e211a4a 100644 --- a/package/Other/OnlyNumbers.php +++ b/package/Other/OnlyNumbers.php @@ -14,14 +14,15 @@ * @param array $container * @return mixed */ -function OnlyNumbers(array $container){ +function OnlyNumbers(array $container) +{ $count = count($container); - if( $count <= 1 ) { + if ($count <= 1) { return $container; } $exist = []; for ($i = 0; $i < $count; $i++) { - if(isset($exist[$container[$i]])){ + if (isset($exist[$container[$i]])) { unset($exist[$container[$i]]); continue; } @@ -29,4 +30,25 @@ function OnlyNumbers(array $container){ } return !empty($exist) ? array_keys($exist)[0] : false; } -var_dump(OnlyNumbers([11,22,22,11,5,63,13,5,63,18,89,13,89])); \ No newline at end of file + +var_dump(OnlyNumbers([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); + + +// +---------------------------------------------------------------------- +// | 方法二 +// +---------------------------------------------------------------------- +/** + * @author Openset + * @link https://github.com/openset + * @date 2017/9/7 + * @param array $container + * @return null + */ +function OnlyNumbersV2(array $container) +{ + $res = array_flip(array_count_values($container)); + + return isset($res[1]) ? $res[1] : null; +} + +var_dump(OnlyNumbersV2([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php index 6f09f56..3bd223d 100644 --- a/package/Other/StealingApples.php +++ b/package/Other/StealingApples.php @@ -58,8 +58,8 @@ for ($r = 1, $n = 5; ; $r++) { $t = $r; for ($i = 0; $i <= $n; $i++) { - if ($t % 5 == 1) { - $t = $t - round($t / 5) - 1; + if ($t % $n == 1) { + $t = $t - round($t / $n) - 1; } else { continue 2; } From a677dd165a01b8b3b372350cb6639ce90870b85b Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 9 Sep 2017 17:28:29 +0800 Subject: [PATCH 036/127] fix: modify readme :apple: --- README-EN.md | 127 ++++++++++++++++++++++++++++++++++++++++++++ README.md | 145 +++++++++++++++++++++------------------------------ 2 files changed, 186 insertions(+), 86 deletions(-) create mode 100644 README-EN.md diff --git a/README-EN.md b/README-EN.md new file mode 100644 index 0000000..adc7444 --- /dev/null +++ b/README-EN.md @@ -0,0 +1,127 @@ +

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

+ +

+ + php + + + +1 + + + + + + + + + +

+

中文版 

+ + +## 简易结构 + + ├──Package + │ ├── Sort + │ │ ├── BubbleSort.php + │ │ ├── QuickSort.php + │ │ ├── ShellSort.php + │ │ ├── MergeSort.php + │ │ ├── InsertSort.php + │ │ └── SelectSort.php + │ │ + │ ├── Query 查找篇 + │ │ ├── BinaryQuery.php + │ │ ├── InseertQuery.php + │ │ ├── FibonacciQuery.php + │ │ └── QulickQuery.php + │ │ + │ └── Other 其他 + │ ├── MonkeyKing.php + │ ├── DynamicProgramming.php + │ ├── Fibonacci.php + │ ├── StealingApples.php + │ ├── HanoiGames.php + │ ├── ColorBricks.php + │ ├── GetCattle.php + │ ├── OnlyNumbers.php + │ └── BigSmallReplace.php + │ + ├──LICENSE + └──README.md + +## What to do? + To record their understanding algorithms, data structure, the process of simple comprehensive and detailed as possible, let the learning algorithm using flexible, refueling(ง •̀_•́)ง + +## logarithmic +log10100 It's equivalent to saying, "how many tens do you multiply?" the answer is, of course, two +so log10100=2,The logarithmic operation is the inverse of the power operation + +left|right +---|--- +23 = 8 | log28 = 3 +24 = 16 | log216 = 4 +25 = 32 | log232 = 5 + +If you don't, we won't wait for you + +## The elapsed time +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. +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 +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)` + +## Big O notation +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. +In this case, you know how fast these algorithms are + +- The running time of the algorithm increases at different speeds + - For example, the difference between a simple find and a binary search + element|Easy to find|Binary search + ---|---|--- + 100|100ms|7ms + 10000|10s|14ms + 1 000 000 000 |11day|30ms + - ` 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 + Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` +- Some common big O runtime + - O(log n) ,It's also called log time, and this algorithm includes binary algorithms + - O(n),Also known as linear time, this algorithm includes simple lookups. + - O(n * log n) Quick sort + - O(n2),Selection sort + - O(n!) Factorial time +- Here is the point + - The speed of the algorithm is not the time, but the growth of operands + - When we talk about the speed of the algorithm, what we're talking about is how fast will it run as the input increases + - The running time of the algorithm is expressed in large O notation + - 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 + + +## A simple comparison of recursion and loops: + +1. From a procedural point of view, the recursion manifests itself as calling itself, and the loop does not have this form. +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. +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. +4.In general, non-recursive efficiency is higher than recursion. And recursive function calls are expensive and recursive times are limited by stack size. + +## Progressive learning +1. Fork 我的项目并提交你的 `idea` +2. Pull Request +3. Merge + +## 纠错 +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 + +> 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) + +## Contributors + +Thanks for the issue or pull request of the following friends: + +- [hailwood ](https://github.com/hailwood) +- [zhangxuanru](https://github.com/zhangxuanru) +- [ifreesec](https://github.com/ifreesec) +- [openset](https://github.com/openset) + +## License +MIT \ No newline at end of file diff --git a/README.md b/README.md index 09c553f..2f1bdb6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ - +1 @@ -17,12 +17,9 @@

+

English 

-## About - -> 如果说各种编程语言是程序员的招式,那么数据结构和算法就相当于程序员的内功。 - ## 简易结构 ├──Package @@ -53,91 +50,64 @@ │ ├──LICENSE └──README.md - -## 时间复杂度 - -> #### 时间频度 - 一个算法执行所耗费的时间,从理论上是不能算出来的,必须上机运行测试才能知道。 - 但我们不可能也没有必要对每个算法都上机测试,只需知道哪个算法花费的时间多,哪个算法花费的时间少就可以了。 - 并且一个算法花费的时间与算法中语句的执行次数成正比例,哪个算法中语句执行次数多,它花费时间就多。 - 一个算法中的语句执行次数称为语句频度或时间频度。记为 `T(n)`。 - -> #### 时间复杂度 - 在刚才提到的时间频度中,n称为问题的规模,当n不断变化时,时间频度T(n)也会不断变化。 - 但有时我们想知道它变化时呈现什么规律。为此,我们引入时间复杂度概念。 - 一般情况下,算法中基本操作重复执行的次数是问题规模n的某个函数,用T(n)表示, - 若有某个辅助函数f(n),使得当n趋近于无穷大时,T(n)/f(n)的极限值为不等于零的常数,则称f(n)是T(n)的同数量级函数。 - 记作T(n)=O(f(n)),称O(f(n)) 为算法的渐进时间复杂度,简称时间复杂度。时间频度不同,但时间复杂度可能相同。 - 如:T(n)=n2+3n+4与T(n)=4n2+2n+1它们的频度不同,但时间复杂度相同,都为O(n2)。 - 按数量级递增排列,常见的时间复杂度有:常数阶O(1),对数阶O(log2n),线性阶O(n), 线性对数阶O(nlog2n),平方阶O(n2),立方阶O(n3),..., k次方阶O(nk),指数阶O(2n)。 - 随着问题规模n的不断增大,上述时间复杂度不断增大,算法的执行效率越低。 - -> #### 最坏时间复杂度和平均时间复杂度   - 最坏情况下的时间复杂度称最坏时间复杂度。一般不特别说明,讨论的时间复杂度均是最坏情况下的时间复杂度。 - 这样做的原因是:最坏情况下的时间复杂度是算法在任何输入实例上运行时间的上界,这就保证了算法的运行时间不会比任何更长。 - 在最坏情况下的时间复杂度为T(n)=0(n),它表示对于任何输入实例,该算法的运行时间不可能大于0(n)。 - 平均时间复杂度是指所有可能的输入实例均以等概率出现的情况下,算法的期望运行时间。指数阶0(2n),显然,时间复杂度为指数阶0(2n)的算法效率极低,当n值稍大时就无法应用。 - -> #### 求时间复杂度 -> 如果算法的执行时间不随着问题规模n的增加而增长,即使算法中有上千条语句,其执行时间也不过是一个较大的常数。此类算法的时间复杂度是O(1)。 -``` - x=91; y=100; - while(y>0) if(x>100) {x=x-10;y--;} else x++; -``` -解答: T(n)=O(1), -这个程序看起来有点吓人,总共循环运行了1100次,但是我们看到n没有? -没。这段程序的运行是和n无关的, -就算它再循环一万年,我们也不管他,只是一个常数阶的函数 -- 当有若干个循环语句时,算法的时间复杂度是由嵌套层数最多的循环语句中最内层语句的频度f(n)决定的。 -``` - x=1; -for(i=1;i<=n;i++) - for(j=1;j<=i;j++) - for(k=1;k<=j;k++) - x++;    -``` -该程序段中频度最大的语句是(5),内循环的执行次数虽然与问题规模n没有直接关系,但是却与外层循环的变量取值有关,而最外层循环的次数直接与n有关, -因此可以从内层循环向外层分析语句(5)的执行次数: 则该程序段的时间复杂度为T(n)=O(n3/6+低次项)=O(n3) -- 算法的时间复杂度不仅仅依赖于问题的规模,还与输入实例的初始状态有关。 -在数值A[0..n-1]中查找给定值K的算法大致如下: -``` -i=n-1; -while(i>=0&&(A[i]!=k)) - i--; -return i; -``` -此算法中的语句(3)的频度不仅与问题规模n有关,还与输入实例中A的各元素取值及K的取值有关: - - ①若A中没有与K相等的元素,则语句(3)的频度f(n)=n; - - ②若A的最后一个元素等于K, 则语句(3)的频度f(n)是常数0。 - -- 时间复杂度评价性能 - 有两个算法A1和A2求解同一问题,时间复杂度分别是T1(n)=100n2,T2(n)=5n3。 - (1)当输入量n<20时,有T1(n)>T2(n),后者花费的时间较少。 - (2)随着问题规模n的增大,两个算法的时间开销之比5n3/100n2=n/20亦随着增大。即当问题规模较大时,算法A1比算法A2要有效地多。 - 它们的渐近时间复杂度O(n2)和O(n3)从宏观上评价了这两个算法在时间方面的质量。 - 在算法分析时,往往对算法的时间复杂度和渐近时间复杂度不予区分,而经常是将渐近时间复杂度T(n)=O(f(n))简称为时间复杂度, - 其中的f(n)一般是算法中频度最大的语句频度。 - -## 空间复杂度 - 一个程序的空间复杂度是指运行完一个程序所需内存的大小。 - 利用程序的空间复杂度,可以对程序的运行所需要的内存多少有个预先估计。一个程序执行时除了需要存储空间和存储本身所使用的指令、常数、变量和输入数据外, - 还需要一些对数据进行操作的工作单元和存储一些为现实计算所需信息的辅助空间。程序执行时所需存储空间包括以下两部分。   -> #### 固定部分 - 这部分空间的大小与输入/输出的数据的个数多少、数值无关。主要包括指令空间(即代码空间)、数据空间(常量、简单变量)等所占的空间。这部分属于静态空间。 -> #### 可变空间,这部分空间的主要包括动态分配的空间,以及递归栈所需的空间等。这部分的空间大小与算法有关。 - 一个算法所需的存储空间用f(n)表示。S(n)=O(f(n))  其中n为问题的规模,S(n)表示空间复杂度。 + +## 要做什么? + 记录自己理解算法,数据结构的过程,尽可能的简单全面以及详细,让算法学习运用灵活自如,加油(ง •̀_•́)ง + +## 对数 +log10100 相当于问"降多少个10相乘的结果为100",答案当然是2个了 +因此log10100=2,即对数运算是幂运算的逆运算 + +left|right +---|--- +23 = 8 | log28 = 3 +24 = 16 | log216 = 4 +25 = 32 | log232 = 5 + +就是酱紫,你要是没有学会,我们也不会等你 + +## 运行时间 +以二分查找为例,使用它可节省多少时间呢?简单查找诸葛地检查数字,如果列表包含100个数字,最多需要猜100次。 +换而言之嘴多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 +最多需要7次,如果列表包含40亿个数字,最多需猜32次,而分查找的运行时间为对数时间 `O(log)` + +## 大O表示法 +大O表示法是一种特殊的表示法 ,指出了算法的速度有多快。有个屌用啊,实际上,你经常要去复制别人的代码。 +在这种情况下,知道这些算法的速度有快有慢 + +- 算法的运行时间以不同的速度增加 + - 例如简单查找与二分查找的区别 + 元素|简单查找|二分查找 + ---|---|--- + 100个元素|100ms|7ms + 10000个元素|10s|14ms + 1 000 000 000 个元素|11天|30ms + - 大`O`表示发指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 + 使用大`O`表示发这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` +- 一些常见的大O运行时间 + - O(log n) ,也叫对数时间,这样的算法包括二分算法 + - O(n),也叫线性时间,这样的算法包括简单查找。 + - O(n * log n) 快速排序 + - O(n2),选择排序 + - O(n!) 即阶乘时间 +- 这里是重点 + - 算法的速度指的并非时间,而是操作数的增速 + - 谈论算法的速度时间时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加 + - 算法的运行时间用大O表示发表示 + - O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 + ## 递归和循环的简单比较: - 1、从程序上看,递归表现为自己调用自己,循环则没有这样的形式。 - 2、递归是从问题的最终目标出发,逐渐将复杂问题化为简单问题,并且简单的问题的解决思路和复杂问题一样,同时存在基准情况,就能最终求得问题,是逆向的。而循环是从简单问题出发,一步步的向前发展,最终求得问题,是正向的。 - 3、任意循环都是可以用递归来表示的,但是想用循环来实现递归(除了单向递归和尾递归),都必须引入栈结构进行压栈出栈。 - 4、一般来说,非递归的效率高于递归。而且递归函数调用是有开销的,递归的次数受堆栈大小的限制。 +1. 从程序上看,递归表现为自己调用自己,循环则没有这样的形式。 +2. 递归是从问题的最终目标出发,逐渐将复杂问题化为简单问题,并且简单的问题的解决思路和复杂问题一样,同时存在基准情况,就能最终求得问题,是逆向的。而循环是从简单问题出发,一步步的向前发展,最终求得问题,是正向的。 +3. 任意循环都是可以用递归来表示的,但是想用循环来实现递归(除了单向递归和尾递归),都必须引入栈结构进行压栈出栈。 +4. 一般来说,非递归的效率高于递归。而且递归函数调用是有开销的,递归的次数受堆栈大小的限制。 ## 一起进步学习 - 1. Fork 我的项目并提交你的 `idea` - 2. Pull Request - 3. Merge +1. Fork 我的项目并提交你的 `idea` +2. Pull Request +3. Merge ## 纠错 @@ -150,4 +120,7 @@ return i; - [hailwood ](https://github.com/hailwood) - [zhangxuanru](https://github.com/zhangxuanru) - [ifreesec](https://github.com/ifreesec) -- [openset](https://github.com/openset) \ No newline at end of file +- [openset](https://github.com/openset) + +## License +MIT \ No newline at end of file From 09c356a338a35d7e4b6b3cd8321cd1cf7da09e8a Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 9 Sep 2017 17:30:02 +0800 Subject: [PATCH 037/127] fix: modify readme :bug: --- README-EN.md | 12 +++++++----- README.md | 12 +++++++----- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/README-EN.md b/README-EN.md index adc7444..6e6ed8b 100644 --- a/README-EN.md +++ b/README-EN.md @@ -77,11 +77,13 @@ In this case, you know how fast these algorithms are - The running time of the algorithm increases at different speeds - For example, the difference between a simple find and a binary search - element|Easy to find|Binary search - ---|---|--- - 100|100ms|7ms - 10000|10s|14ms - 1 000 000 000 |11day|30ms + +element|Easy to find|Binary search +---|---|--- +100|100ms|7ms +10000|10s|14ms +1 000 000 000 |11day|30ms + - ` 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 Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` - Some common big O runtime diff --git a/README.md b/README.md index 2f1bdb6..03b39f5 100644 --- a/README.md +++ b/README.md @@ -77,11 +77,13 @@ left|right - 算法的运行时间以不同的速度增加 - 例如简单查找与二分查找的区别 - 元素|简单查找|二分查找 - ---|---|--- - 100个元素|100ms|7ms - 10000个元素|10s|14ms - 1 000 000 000 个元素|11天|30ms + +元素|简单查找|二分查找 +---|---|--- +100个元素|100ms|7ms +10000个元素|10s|14ms +1 000 000 000 个元素|11天|30ms + - 大`O`表示发指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 使用大`O`表示发这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` - 一些常见的大O运行时间 From 536c6a0e8d613b34c6e01c16581a2de1284b475d Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 9 Sep 2017 17:31:58 +0800 Subject: [PATCH 038/127] fix: modify readme :rocket: --- README-EN.md | 6 +++--- README.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README-EN.md b/README-EN.md index 6e6ed8b..3d78ce1 100644 --- a/README-EN.md +++ b/README-EN.md @@ -1,4 +1,4 @@ -

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

+

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

@@ -6,7 +6,7 @@ -1 + @@ -20,7 +20,7 @@

中文版 

-## 简易结构 +## Simple structure, ├──Package │ ├── Sort diff --git a/README.md b/README.md index 03b39f5..218dbe6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ -1 + From afcbfe1c8f741cd7ce450c40ecaf3b9e8ff2c790 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 13 Sep 2017 21:39:31 +0800 Subject: [PATCH 039/127] feat: add bidirectionalQueue :rewind: --- README-EN.md | 3 +- README.md | 1 + package/Other/BidirectionalQueue.php | 144 +++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 package/Other/BidirectionalQueue.php diff --git a/README-EN.md b/README-EN.md index 3d78ce1..7cfdcce 100644 --- a/README-EN.md +++ b/README-EN.md @@ -42,7 +42,8 @@ │ ├── DynamicProgramming.php │ ├── Fibonacci.php │ ├── StealingApples.php - │ ├── HanoiGames.php + │ ├── HanoiGames.php + │ ├── BidirectionalQueue.php │ ├── ColorBricks.php │ ├── GetCattle.php │ ├── OnlyNumbers.php diff --git a/README.md b/README.md index 218dbe6..42e24ea 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ │ ├── Fibonacci.php 斐波那契数列 │ ├── StealingApples.php 偷苹果求余 │ ├── HanoiGames.php 汉诺塔游戏 + │ ├── BidirectionalQueue.php 双向队列 │ ├── ColorBricks.php 彩色砖块 │ ├── GetCattle.php 牛年求牛 │ ├── OnlyNumbers.php 求唯一数 diff --git a/package/Other/BidirectionalQueue.php b/package/Other/BidirectionalQueue.php new file mode 100644 index 0000000..4bbd921 --- /dev/null +++ b/package/Other/BidirectionalQueue.php @@ -0,0 +1,144 @@ + + * @date 2017/9/13 + * @license MIT + * ------------------------------------------------------------- + * 思路分析: 考察PHP几个内置数组的函数 + * ------------------------------------------------------------- + *双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素 + * @param $n + * @return int + */ +class BidirectionalQueue +{ + /** + * @var array + */ + public $queue = []; + public $maxLength = 0; // 对列最大长度,0表示不限 + public $type = 0; // 对列类型 + public $frontNum = 0; // 前端插入的数量 + public $rearNum = 0; // 后端插入的数量 + + const C_AT_BOTH_ENDS = 1; // 1:两端均可输入输出 + const C_FRONT_ONLY_INPUT = 2; // 2:前端只能输入,后端可输入输出 + const C_FRONT_ONLY_OUTPUT = 3; // 3:前端只能输出,后端可输入输出 + const C_BACK_ONLY_INPUT = 4; // 4:后端只能输入,前端可输入输出 + const C_BACK_ONLY_OUTPUT = 5; // 5:后端只能输出,前端可输入输出 + const C_BOTH_WAY_ONLY_INPUT = 6; // 6:两端均可输入输出,在哪端输入只能从哪端输出 + + /** + * BidirectionalQueue 初始化. + * + * @param int $type + + * @param int $maxLength + */ + public function __construct($type = self::C_AT_BOTH_ENDS, $maxLength = 0) + { + var_dump($this->getConfig()); + $this->_type = in_array($type, [1, 2, 3, 4, 5, 6]) ? $type : self::C_AT_BOTH_ENDS; + $this->_maxLength = intval($maxLength); + } + + /** + * addFirst 前端入列 + * + * @param $item + * @return int + */ + public function addFirst($item) + { + return array_unshift($this->queue, $item); + } + + /** + * addLast 尾部入列 + * + * @param $item + * @return int + */ + public function addLast($item) + { + return array_push($this->queue, $item); + } + + /** + * removeFirst 头部出列 + * + * @return mixed + */ + public function removeFirst() + { + return array_shift($this->queue); + } + + /** + * removeLast 尾部出列 + * + * @return mixed + */ + public function removeLast() + { + return array_pop($this->queue); + } + + /** + * 清空队列 + */ + public function makeEmpty() + { + unset($this->queue); + } + + /** + * 获取列头 + * + * @return mixed + */ + public function getFirst() + { + return reset($this->queue); + } + + /** + * 获取列尾 + * + * @return mixed + */ + public function getLast() + { + return end($this->queue); + } + + /** + * 获取长度 + * + * @return int + */ + public function getLength() + { + return count($this->queue); + } + + /** + * 获取配置常量 + * + */ + protected function getConfig() + { + return [ + self::C_AT_BOTH_ENDS, // 1:两端均可输入输出 + self::C_FRONT_ONLY_INPUT, // 2:前端只能输入,后端可输入输出 + self::C_FRONT_ONLY_OUTPUT, // 3:前端只能输出,后端可输入输出 + self::C_BACK_ONLY_INPUT, // 4:后端只能输入,前端可输入输出 + self::C_BACK_ONLY_OUTPUT, // 5:后端只能输出,前端可输入输出 + self::C_BOTH_WAY_ONLY_INPUT, // 6:两端均可输入输出,在哪端输入只能从哪端输出 + ]; + } +} +new BidirectionalQueue(); \ No newline at end of file From 5bb34e220da2ca19925901d915a9fc38b8c82703 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Thu, 14 Sep 2017 20:42:07 +0800 Subject: [PATCH 040/127] docs: update :speech_balloon: --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 42e24ea..e522686 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ left|right ## 运行时间 以二分查找为例,使用它可节省多少时间呢?简单查找诸葛地检查数字,如果列表包含100个数字,最多需要猜100次。 -换而言之嘴多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 +换而言之最多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 最多需要7次,如果列表包含40亿个数字,最多需猜32次,而分查找的运行时间为对数时间 `O(log)` ## 大O表示法 @@ -126,4 +126,4 @@ left|right - [openset](https://github.com/openset) ## License -MIT \ No newline at end of file +MIT From 634be07a08ae2ecb3e9ca09d5e1af32a3159010e Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sun, 17 Sep 2017 17:18:36 +0800 Subject: [PATCH 041/127] feat: Yield :truck: --- package/Query/YieldExample.php | 313 +++++++++++++++++++++++++++++++++ 1 file changed, 313 insertions(+) create mode 100644 package/Query/YieldExample.php diff --git a/package/Query/YieldExample.php b/package/Query/YieldExample.php new file mode 100644 index 0000000..0e8dc36 --- /dev/null +++ b/package/Query/YieldExample.php @@ -0,0 +1,313 @@ + + * @date 2017/9/17 + * @license MIT + * ------------------------------------------------------------- + * 思路分析:笔记局 ,觉得需要认真学习的 Yield + * ------------------------------------------------------------- + * [由来] + * PHP从5.5引入了yield关键字,增加了迭代生成器和协程的支持,但并未在言本身级别实现一个完善的协程解决方案。 + * PHP协程也是基于Generator,Generator可以视为一种“可中断”的函数,而 yield 构成了一系列的“中断点”。 + * PHP 协程没有resume关键字,而是“在使用的时候唤起”协程。了解如何在PHP中实现协程,首先要解决迭代生成器。 + * PHP > 手册 > 语言参考 > 生成器 http://php.net/manual/zh/language.generators.overview.php + * ------------------------------------------------------------- + * [概念] + * “协程”(Coroutine)概念最早由 Melvin Conway 于1958年提出。 + * 协程可以理解为纯用户态的线程,其通过协作而不是抢占来进行切换。 + * 相对于进程或者线程,协程所有的操作都可以在用户态完成,创建和切换的消耗更低。 + * 总的来说,协程为协同任务提供了一种运行时抽象,这种抽象非常适合于协同多任务调度和数据流处理。 + * 在现代操作系统和编程语言中,因为用户态线程切换代价比内核态线程小,协程成为了一种轻量级的多任务模型。 + * ------------------------------------------------------------- + * [协程与进程线程的区别] + * 对于操作系统来说只有进程和线程,协程的控制由应用程序显式调度,非抢占式的 + * 协程的执行最终靠的还是线程,应用程序来调度协程选择合适的线程来获取执行权 + * 切换非常快,成本低。一般占用栈大小远小于线程(协程KB级别,线程MB级别), + * 所以可以开更多的协程,协程比线程更轻量级 + * ------------------------------------------------------------- + */ + +/** + * 协程生产器 + * + * @param $start + * @param $end + * @param int $step + * @return \Generator + */ +$SyncFactory = function ($start, $end, $step = 1) { + for ($i = $start; $i <= $end; $i += $step) { + yield $i; + } +}; +/** + * 普通的生产器 + * + * @param $start + * @param $end + * @param int $step + */ +$UsualFactory = function ($start, $end, $step = 1) { + for ($i = $start; $i <= $end; $i += $step) { + //var_dump($i); + } +}; + +$SyncFactory(1, 100000); //class Generator#2 PHP 协程没有resume关键字,而是“在使用的时候唤起”协程 +// Generator 这个东西是从 generators返回的 http://php.net/manual/zh/class.generator.php +$UsualFactory(1, 100000); + +/** + * 从编程角度上看,协程的思想本质上就是控制流的主动让出(yield)和恢复(resume)机制,迭代器常被用来实现协程, + * 所以大部分的语言实现的协程中都有yield关键字,比如Python、PHP、Lua。但也有特殊比如Go就使用的是通道来通信。 + */ +foreach ($SyncFactory(1, 10) as $value) { + echo $value . "\n"; // 我理解的是相当于开了100000协程跑这次输出操作 +} // 那就尝试将它唤醒吧 + +/** + * [中断点] + * 我们从生成器认识协程需要认识到:生成器是一种具有中断点的函数,而yield构成了中断点。 + * 比如, 你调用$range->rewind(),那么xrange()里的代码就会运行到控制流第一次出现yield的地方, + * 而函数内传递给yield语句的值,即为迭代的当前值,可以通过$xrange->current()获取。 + * [PHP中的协程实现] + * PHP的协程支持是在迭代生成器的基础上,增加了可以回送数据给生成器的功能,从而达到双向通信即: + * ------------------------------------------------------------- + * >>> 生成器<---数据--->调用者 <<< + * ------------------------------------------------------------- + */ +echo '/* ------------------------- Yield接收与发送数据 ------------------------- */'; +/** + * 容器接收示例 + */ +function container() +{ + $test = yield "Hello "; + var_dump($test); + $test = yield "World "; + var_dump($test); +} + +$container = container(); // 这里又进化成 Generator对象了,还记得SPL 那一坨么? 传送门 [http://php.net/manual/zh/book.spl.php] + +var_dump($container->key()); // 返回当前产生的键 +var_dump($container->current()); // 返回当前产生的值 + +$container->next(); // 生成器继续执行 ,这个next 看下输出结果发现返回了个NULL 你打印什么了? +$container->send('强势占位'); + +var_dump($container->key()); // null +var_dump($container->current()); // null + +if (!$container->valid()) { + echo "我没有被关闭" . PHP_EOL; +} + +echo '/* ------------------------- 协程与任务调度 ------------------------- */'; + +/** + * yield指令提供了任务中断自身的一种方法,然后把控制交回给任务调度器。 + * 而PHP语言本身只是提供程序中断的功能,至于任务调度器需要我们自己实现, + * 同时协程在运行多个其他任务时,yield还可以用来在任务和调度器之间进行通信。 + */ + +/** + * PHP协程任务 + * 简单的定义具有任何ID标识的协程函数,如一个轻量级的协程函数示例代码 + * @form http://wiki.phpboy.net/doku.php?id=2017-07:54-PHP_Yield%E5%8D%8F%E7%A8%8B%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E7%B2%BE%E9%80%9A.md + * + * @version 1.0 + */ +class Task +{ + protected $taskId; + protected $coroutine; + protected $sendValue = null; + protected $beforeFirstYield = true; + + /** + * Task constructor. + * + * @param $taskId + * @param \Generator $coroutine + */ + public function __construct($taskId, Generator $coroutine) + { + $this->taskId = $taskId; + $this->coroutine = $coroutine; + } + + /** + * setSendValue + * + * @param $sendValue + */ + public function setSendValue($sendValue) + { + $this->sendValue = $sendValue; + } + + /** + * 跑起来的巨人 + * + * @return mixed + */ + public function run() + { + if ($this->beforeFirstYield) { + $this->beforeFirstYield = false; + return $this->coroutine->current(); + } else { + $retval = $this->coroutine->send($this->sendValue); + $this->sendValue = null; + return $retval; + } + } + + /** + * getTaskId + * + * @return mixed + */ + public function getTaskId() + { + return $this->taskId; + } + + /** + * 协程关了没? + * + * @return bool + */ + public function isFinished() + { + return !$this->coroutine->valid(); + } +} + +/** + * PHP协程调度器 + * 简单来说,是可以在多个任务之间相互协调,及任务之间相互切换的一种进程资源的分配器。 + * 调度器的实现方式有多种,大致分为两类:一是,队列;二是,定时器 + * + * @version 1.0 + */ +class Scheduler +{ + protected $maxTaskId = 0; + protected $taskMap = []; // taskId => task + protected $taskQueue; + + public function __construct(SplQueue $spl) + { + // SplQueue + // http://php.net/manual/zh/class.splqueue.php + $this->taskQueue = $spl; + } + + public function newTask(Generator $coroutine) + { + $tid = ++$this->maxTaskId; + $task = new Task($tid, $coroutine); + + $this->taskMap[$tid] = $task; + $this->schedule($task); + return $tid; + } + + public function schedule(Task $task) + { + $this->taskQueue->enqueue($task); + } + + public function run() + { + GLOBAL $i; + while (!$this->taskQueue->isEmpty()) { + $task = $this->taskQueue->dequeue(); + $retval = $task->run(); + + echo "Scheduler runtime:" . ++$i . " retval is:\n"; + var_dump($retval); + + if ($retval instanceof SystemCall) { + $retval($task, $this); + continue; + } + + if ($task->isFinished()) { + unset($this->taskMap[$task->getTaskId()]); + } else { + $this->schedule($task); + } + } + } +} + +class SystemCall +{ + protected $callback; + + public function __construct($callback) + { + $this->callback = $callback; + } + + public function __invoke(Task $task, Scheduler $scheduler) + { + $callback = $this->callback; + return $callback($task, $scheduler); + } +} + +/** + * newTask()方法创建一个新任务,然后把这个任务放入任务map数组里,接着它通过把任务放入任务队列里来实现对任务的调度。 + * 接着run()方法扫描任务队列,运行任务,如果一个任务结束了,那么它将从队列里删除,否则它将在队列的末尾再次被调度。 + */ + +function getTaskId() +{ + return new SystemCall(function (Task $task, Scheduler $scheduler) { + $task->setSendValue($task->getTaskId()); + $scheduler->schedule($task); + }); +} + +function task($max) +{ + $tid = (yield getTaskId()); + for ($i = 0; $i < $max; $i++) { + echo "this is task $tid iteration $i .\n"; + yield; + } +} + +$scheduler = new Scheduler(new SplQueue()); +$scheduler->newTask(task(10)); +$scheduler->newTask(task(5)); +function testYield() +{ + yield getTaskId(); +} + +//var_dump(testYield()->current()); +$scheduler->run(); + + +function task1() { + for ($i = 1; $i <= 10; ++$i) { + echo "This is task 1 iteration $i.\n"; + yield; + } +} + +function task2() { + for ($i = 1; $i <= 5; ++$i) { + echo "This is task 2 iteration $i.\n"; + yield; + } +} +$scheduler->newTask(task1()); +$scheduler->newTask(task2()); From 631de97f86c5d979511bb34f7f7dc53eac4775dc Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 09:47:50 +0800 Subject: [PATCH 042/127] feat: new medal :bug: --- .travis.yml | 26 +++++ package/Other/PokerGames.php | 94 ++++++++++++++++++ package/Query/YieldExample.php | 173 +++++++++++++++++++++++++++++---- 3 files changed, 273 insertions(+), 20 deletions(-) create mode 100644 .travis.yml create mode 100644 package/Other/PokerGames.php diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..1fcf63f --- /dev/null +++ b/.travis.yml @@ -0,0 +1,26 @@ +language: php + +sudo: false +php: + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - hhvm + +matrix: + include: + - php: 5.5 + env: dependencies=lowest + +before_script: + - if [[ $(phpenv version-name) == '5.6' ]]; then composer require satooshi/php-coveralls:dev-master -n ; fi + - if [[ $(phpenv version-name) != '5.6' ]]; then composer install -n ; fi + - if [ "$dependencies" = "lowest" ]; then composer update --prefer-lowest --prefer-stable -n; fi; + +script: + - if [[ $(phpenv version-name) == '5.6' ]]; then vendor/bin/phpunit --coverage-clover clover.xml ; fi + - if [[ $(phpenv version-name) != '5.6' ]]; then vendor/bin/phpunit ; fi + +after_script: + - if [[ $(phpenv version-name) == '5.6' ]]; then php vendor/bin/coveralls -v ; fi diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php new file mode 100644 index 0000000..a3783e0 --- /dev/null +++ b/package/Other/PokerGames.php @@ -0,0 +1,94 @@ + + * @date 2017/9/18 + * @license MIT + */ + +$card_num = 54;//牌数 +function wash_card($card_num) +{ + $cards = $tmp = array (); + $tmp = range(0,$card_num); + + for ($i = 0; $i < $card_num; $i++) { + $index = rand(0, $card_num - $i - 1); + $cards[$i] = $tmp[$index]; + unset($tmp[$index]); + $tmp = array_values($tmp); + } + return $cards; +} + +// 测试: +//var_dump(wash_card($card_num)); + +/** + * description + * + * @uses description + * @version 1.0 + * @author Pu ShaoWei + */ +class PokerGames extends SplQueue +{ + /** + * PokerGames constructor. + * + * @param $num + */ + public function __construct($num) + { + $this->setIteratorMode(SplQueue::IT_MODE_DELETE); + while ($num--) { + $this->enqueue($num); + } + + $generator = $this->generator(22); + $generator->send("s"); + + while (!$generator->valid()){ + $generator->rewind(); + $generator->current(); + } + + } + + /** + * __destruct, + */ + public function __destruct(){ + } + + /** + * generator + * + * @param $limit + * @return \Generator + */ + public function generator($limit) + { + for ($i = 0; $i <= $limit; $i++) { + yield $i; + } + } + + public function makePoker() + { + + } +} + +/** + * 红桃 2 3 4 5 6 7 8 9 10 J Q K A + 黑桃 2 3 4 5 6 7 8 9 10 J Q K A + 梅花 2 3 4 5 6 7 8 9 10 J Q K A + 方块 2 3 4 5 6 7 8 9 10 J Q K A + Joker joker + */ + +$porker = new PokerGames(); +var_dump($porker); diff --git a/package/Query/YieldExample.php b/package/Query/YieldExample.php index 0e8dc36..6824554 100644 --- a/package/Query/YieldExample.php +++ b/package/Query/YieldExample.php @@ -200,13 +200,18 @@ class Scheduler protected $taskMap = []; // taskId => task protected $taskQueue; - public function __construct(SplQueue $spl) + public function __construct() { - // SplQueue // http://php.net/manual/zh/class.splqueue.php - $this->taskQueue = $spl; + $this->taskQueue = new SplQueue(); } + /** + * 创建一个task 开启一个协程 + * + * @param \Generator $coroutine + * @return int + */ public function newTask(Generator $coroutine) { $tid = ++$this->maxTaskId; @@ -217,30 +222,37 @@ public function newTask(Generator $coroutine) return $tid; } + /** + * 队列入队 + * + * @param \Task $task + */ public function schedule(Task $task) { $this->taskQueue->enqueue($task); } + /** + * 消费队列内容 + */ public function run() { GLOBAL $i; while (!$this->taskQueue->isEmpty()) { + // 出队列 $task = $this->taskQueue->dequeue(); - $retval = $task->run(); + $retval = $task->run(); // 跑Task 中的 run echo "Scheduler runtime:" . ++$i . " retval is:\n"; - var_dump($retval); - if ($retval instanceof SystemCall) { - $retval($task, $this); + $retval($task, $this); // 如果为函数调用则这样跑起来 continue; } - if ($task->isFinished()) { + if ($task->isFinished()) { // 结束了就删掉 unset($this->taskMap[$task->getTaskId()]); } else { - $this->schedule($task); + $this->schedule($task); // 那就回炉重造 } } } @@ -250,11 +262,18 @@ class SystemCall { protected $callback; - public function __construct($callback) + public function __construct(callable $callback) { $this->callback = $callback; } + /** + * 以函数方式调用 + * + * @param \Task $task + * @param \Scheduler $scheduler + * @return mixed + */ public function __invoke(Task $task, Scheduler $scheduler) { $callback = $this->callback; @@ -284,18 +303,19 @@ function task($max) } } -$scheduler = new Scheduler(new SplQueue()); -$scheduler->newTask(task(10)); -$scheduler->newTask(task(5)); -function testYield() -{ - yield getTaskId(); -} +$scheduler = new Scheduler(); +$scheduler->newTask(task(3)); +$scheduler->newTask(task(3)); + +//function testYield() +//{ +// yield getTaskId(); +//} //var_dump(testYield()->current()); $scheduler->run(); - +/* function task1() { for ($i = 1; $i <= 10; ++$i) { echo "This is task 1 iteration $i.\n"; @@ -309,5 +329,118 @@ function task2() { yield; } } -$scheduler->newTask(task1()); -$scheduler->newTask(task2()); +$scheduler->newTask(task1(21)); +$scheduler->newTask(task2(21)); +$scheduler->run(); +*/ + +// 最后回顾一下知识点,协程不一定能提高速度,但它一定能节约到内存 +/** + * 协程创建 + * + * @param $start + * @param $limit + * @param int $step + * @return \Generator + */ +function xrange($start, $limit, $step = 1) +{ + for ($i = $start; $i <= $limit; $i += $step) { + yield $i; + } +} + +$max = 999999; +$c = new codeStatus(true); +$c->timeStart(); + +$simpleStart = microtime(true); +foreach (range(1, $max, 2) as $number) { +} +$simpleEnd = microtime(true); +$c->timeEnd(); +print_r($c->showStatus()); + +$c = new codeStatus(true); +$c->timeStart(); +$start = microtime(true); +foreach (xrange(1, $max, 2) as $number) { +} + +$end = microtime(true); +$c->timeEnd(); +print_r($c->showStatus()); + + +/** + * 程序耗时统计 + * + * @version 1.0 + */ +class codeStatus +{ + /** + * @param:boolen $time_type时间类型, boolen$show_m是否显示内存, + * boolen$show_type,false是array,ture为json,$regmax是数据保留几位 + */ + public $regmax; + public $runTime = 0; + public $time_type; + public $is_show_memory; + public $show_type; + private static $t1; + private static $t2; + + public function __construct($time_type = false, $show_m = true, $show_type = false, $regmax = 3) + { + $this->regmax = $regmax; + $this->is_show_memory = $show_m; + $this->time_type = $time_type; + $this->show_type = $show_type; + } + + public function timeStart() + { + self::$t1 = microtime(true); + } + + public function timeEnd() + { + self::$t2 = microtime(true); + } + + private function getTime() + { + if (self::$t1 != '' && self::$t2 != '') { + if ($this->time_type == false) { + return '耗时' . round(self::$t2 - self::$t1, $this->regmax) . '秒'; + } else if ($this->time_type == true) { + return '耗时' . round(self::$t2 - self::$t1, ($this->regmax + 3)) * 1000 . '毫秒'; + } + } else { + return "error param"; + } + } + + private function getmemory() + { + $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage() / 1024, $this->regmax) . 'KB'; + return '占用内存:' . $memory; + } + + public function showStatus() + { + if ($this->is_show_memory == true) { + $arr = array (self::getTime(), self::getmemory()); + } else { + $arr = array (self::getTime()); + } + if ($this->show_type == false) { + return $arr; + } else { + return json_encode($arr); + } + } + + +} From 0be4592951cb8659fb5b9d1ca4684587e17a49ac Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 09:51:06 +0800 Subject: [PATCH 043/127] fix: medal :checkered_flag: --- .travis.yml | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/.travis.yml b/.travis.yml index 1fcf63f..d307869 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,26 +1,8 @@ language: php - sudo: false php: - 5.5 - 5.6 - 7.0 - 7.1 - - hhvm - -matrix: - include: - - php: 5.5 - env: dependencies=lowest - -before_script: - - if [[ $(phpenv version-name) == '5.6' ]]; then composer require satooshi/php-coveralls:dev-master -n ; fi - - if [[ $(phpenv version-name) != '5.6' ]]; then composer install -n ; fi - - if [ "$dependencies" = "lowest" ]; then composer update --prefer-lowest --prefer-stable -n; fi; - -script: - - if [[ $(phpenv version-name) == '5.6' ]]; then vendor/bin/phpunit --coverage-clover clover.xml ; fi - - if [[ $(phpenv version-name) != '5.6' ]]; then vendor/bin/phpunit ; fi -after_script: - - if [[ $(phpenv version-name) == '5.6' ]]; then php vendor/bin/coveralls -v ; fi From 86edfe1ef5b5ff7f003f8db96fd94374071b0949 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 09:53:22 +0800 Subject: [PATCH 044/127] fix: medal :heavy_minus_sign: --- .travis.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.travis.yml b/.travis.yml index d307869..a5e0510 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,3 +6,18 @@ php: - 7.0 - 7.1 +services: + - mysql + +before_install: + - mysql -e 'SET @@GLOBAL.wait_timeout=3' + - mysql -e 'SET @@GLOBAL.interactive_timeout=3' + - mysql -e 'CREATE DATABASE IF NOT EXISTS ci;' + - mysql -e 'use ci;' + - mysql -e 'CREATE TABLE `ci`.`hello` (`id` int(11) NOT NULL AUTO_INCREMENT,`content` varchar(255) NOT NULL,`user` varchar(255) NOT NULL,`created` datetime NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;' + +script: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover + +after_script: + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover coverage.clover \ No newline at end of file From 2ef9a721d3f9d6590164a542a30a85215bd9017b Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 09:57:31 +0800 Subject: [PATCH 045/127] fix: medal :penguin: --- .travis.yml | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index a5e0510..14d23d6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,20 +4,19 @@ php: - 5.5 - 5.6 - 7.0 - - 7.1 services: - mysql before_install: - - mysql -e 'SET @@GLOBAL.wait_timeout=3' - - mysql -e 'SET @@GLOBAL.interactive_timeout=3' - - mysql -e 'CREATE DATABASE IF NOT EXISTS ci;' - - mysql -e 'use ci;' - - mysql -e 'CREATE TABLE `ci`.`hello` (`id` int(11) NOT NULL AUTO_INCREMENT,`content` varchar(255) NOT NULL,`user` varchar(255) NOT NULL,`created` datetime NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;' + - travis_retry composer self-update -script: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover +install: + - travis_retry composer install -after_script: - - wget https://scrutinizer-ci.com/ocular.phar - - php ocular.phar code-coverage:upload --format=php-clover coverage.clover \ No newline at end of file +script: vendor/bin/phpunit + +matrix: + allow_failures: + - php: 5.6 + fast_finish: true \ No newline at end of file From b89bd3ea2295828c1e287e135cb9df877662799f Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 15:43:24 +0800 Subject: [PATCH 046/127] feat: pokerGames; :package: --- README.md | 23 +++--- package/Other/PokerGames.php | 138 ++++++++++++++++++++++++++--------- 2 files changed, 115 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index e522686..7a41029 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ ## 简易结构 - + ├──Package │ ├── Sort 排序篇 │ │ ├── BubbleSort.php 冒泡排序 @@ -30,14 +30,14 @@ │ │ ├── MergeSort.php 归并排序 │ │ ├── InsertSort.php 插入排序 │ │ └── SelectSort.php 选择排序 - │ │ + │ │ │ ├── Query 查找篇 │ │ ├── BinaryQuery.php 二分查找 │ │ ├── InseertQuery.php 插入查找 │ │ ├── FibonacciQuery.php 斐波那契查找 - │ │ └── QulickQuery.php 快速查找 + │ │ └── QulickQuery.php 快速查找 │ │ - │ └── Other 其他 + │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 │ ├── DynamicProgramming.php 动态规划 │ ├── Fibonacci.php 斐波那契数列 @@ -47,9 +47,10 @@ │ ├── ColorBricks.php 彩色砖块 │ ├── GetCattle.php 牛年求牛 │ ├── OnlyNumbers.php 求唯一数 + │ ├── PokerGames.php 洗扑克牌 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ - ├──LICENSE + ├──LICENSE └──README.md ## 要做什么? @@ -78,13 +79,13 @@ left|right - 算法的运行时间以不同的速度增加 - 例如简单查找与二分查找的区别 - + 元素|简单查找|二分查找 ---|---|--- 100个元素|100ms|7ms 10000个元素|10s|14ms 1 000 000 000 个元素|11天|30ms - + - 大`O`表示发指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 使用大`O`表示发这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` - 一些常见的大O运行时间 @@ -109,10 +110,10 @@ left|right ## 一起进步学习 1. Fork 我的项目并提交你的 `idea` -2. Pull Request -3. Merge +2. Pull Request +3. Merge -## 纠错 +## 纠错 如果大家发现有什么不对的地方,可以发起一个[issue](https://github.com/PuShaoWei/arithmetic-php/issues)或者[pull request](https://github.com/PuShaoWei/arithmetic-php/pulls),我会及时纠正 > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) @@ -126,4 +127,4 @@ left|right - [openset](https://github.com/openset) ## License -MIT +MIT diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index a3783e0..8515503 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -9,11 +9,10 @@ */ $card_num = 54;//牌数 -function wash_card($card_num) +function washCard($card_num) { $cards = $tmp = array (); - $tmp = range(0,$card_num); - + $tmp = range(0, $card_num); for ($i = 0; $i < $card_num; $i++) { $index = rand(0, $card_num - $i - 1); $cards[$i] = $tmp[$index]; @@ -24,71 +23,140 @@ function wash_card($card_num) } // 测试: -//var_dump(wash_card($card_num)); +//var_dump(washCard($card_num));die; /** - * description + * PokerGames 纯属娱乐,有空再优化, 这样够随机吧 * * @uses description * @version 1.0 * @author Pu ShaoWei */ -class PokerGames extends SplQueue +class PokerGames { + const RANDOM = "https://www.random.org/integers/?num=%d&min=1&max=%d&col=1&base=10&format=plain&rnd=new"; + const LIMIT = 10; + + protected $resources; + protected $tally; + protected $i ; + protected $count; + protected $container = array (); + protected $poker = array (); + /** * PokerGames constructor. - * - * @param $num */ - public function __construct($num) + public function __construct() { - $this->setIteratorMode(SplQueue::IT_MODE_DELETE); - while ($num--) { - $this->enqueue($num); - } - - $generator = $this->generator(22); - $generator->send("s"); + $this->container = $this->makePoker(); + $this->count = count($this->container); + $this->i = $this->tally = round(100 / $this->count,2); + $this->taskJob($this->generator($this->count, $this->count)); + } - while (!$generator->valid()){ - $generator->rewind(); - $generator->current(); + /** + * 弄着玩,不推进实际生产里玩 + * + * @param \Generator $task + */ + public function taskJob(Generator $task) + { + foreach ($task as $value) { + if (isset($this->container[$value])) { + array_push($this->poker, $this->container[$value]); + unset($this->container[$value]); + echo "{$this->tally}% 正在洗牌中..\n"; + $this->tally += $this->i; + } else { + $this->taskJob($this->generator($this->count)); + } } - } /** * __destruct, */ - public function __destruct(){ + public function __destruct() + { + curl_close($this->resources); + var_dump($this->poker); } /** - * generator + * generator 好像没别的用 就为了装 * * @param $limit + * @param $max * @return \Generator */ - public function generator($limit) + public function generator($max,$limit = 1) { - for ($i = 0; $i <= $limit; $i++) { - yield $i; + while ($limit--) { + yield $this->makeRand($max); } } + /** + * 创建一副扑克牌 + * + * @return array + */ public function makePoker() { + $porker = array ('大王', '小王'); + foreach (array ('红桃', '方块', '梅花', '黑桃') as $pValue) { + $limit = 13; + while ($limit--) { + switch ($limit) { + case 0: + $temp = "J"; + break; + case 1: + $temp = "A"; + break; + case 11: + $temp = "Q"; + break; + case 12: + $temp = "K"; + break; + default: + $temp = $limit; + break; + } + array_push($porker, $pValue . $temp); + } + } + return $porker; + } + /** + * 去大气噪音那里拿随机数 + * + * @param $max + * @return int + */ + public function makeRand($max) + { + $ch = curl_init(); + curl_setopt_array($ch, [ + CURLOPT_URL => sprintf(self::RANDOM, 1, $max), + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HTTPHEADER => array ('Expect:'), + CURLOPT_HEADER => false, + CURLOPT_CONNECTTIMEOUT => self::LIMIT, + CURLOPT_TIMEOUT => self::LIMIT, + ]); + $result = curl_exec($ch); + $code = curl_getinfo($ch)['http_code']; + $this->resources = $ch; + if ($code == 200) { + return (int)$result; + } + return 0; } } -/** - * 红桃 2 3 4 5 6 7 8 9 10 J Q K A - 黑桃 2 3 4 5 6 7 8 9 10 J Q K A - 梅花 2 3 4 5 6 7 8 9 10 J Q K A - 方块 2 3 4 5 6 7 8 9 10 J Q K A - Joker joker - */ - -$porker = new PokerGames(); -var_dump($porker); +new PokerGames(); From 83f56a1e15925be9fc6e75391ca9780267b7617a Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 15:44:06 +0800 Subject: [PATCH 047/127] feat: pokerGames :page_facing_up: --- package/Other/PokerGames.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index 8515503..1067892 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -66,7 +66,7 @@ public function taskJob(Generator $task) if (isset($this->container[$value])) { array_push($this->poker, $this->container[$value]); unset($this->container[$value]); - echo "{$this->tally}% 正在洗牌中..\n"; + echo "正在洗牌中.. {$this->tally}% \n"; $this->tally += $this->i; } else { $this->taskJob($this->generator($this->count)); From 3ca27c6522388412be36ea3be125afe9ea517dc2 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 16:06:46 +0800 Subject: [PATCH 048/127] feat: poker games :tada: --- package/Other/PokerGames.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index 1067892..fe1b9f7 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -41,6 +41,7 @@ class PokerGames protected $tally; protected $i ; protected $count; + protected $clear; protected $container = array (); protected $poker = array (); @@ -52,6 +53,7 @@ public function __construct() $this->container = $this->makePoker(); $this->count = count($this->container); $this->i = $this->tally = round(100 / $this->count,2); + $this->clear = in_array(PHP_OS,array ('Darwin','Linux')); $this->taskJob($this->generator($this->count, $this->count)); } @@ -62,11 +64,12 @@ public function __construct() */ public function taskJob(Generator $task) { - foreach ($task as $value) { + foreach ($task as $value) { // 1. 这是无脑递归 if (isset($this->container[$value])) { array_push($this->poker, $this->container[$value]); unset($this->container[$value]); - echo "正在洗牌中.. {$this->tally}% \n"; + $this->clear && system("clear"); + echo "正在洗牌中.. ".intval($this->tally)."% \n"; $this->tally += $this->i; } else { $this->taskJob($this->generator($this->count)); @@ -79,7 +82,7 @@ public function taskJob(Generator $task) */ public function __destruct() { - curl_close($this->resources); + curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 var_dump($this->poker); } @@ -158,5 +161,4 @@ public function makeRand($max) return 0; } } - new PokerGames(); From ddb87e2127af8f9ac73b17cb56859faacb2a2702 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 17:11:54 +0800 Subject: [PATCH 049/127] feat: poker games :lock: --- package/Other/PokerGames.php | 48 +++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index fe1b9f7..394adab 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -39,7 +39,7 @@ class PokerGames protected $resources; protected $tally; - protected $i ; + protected $i; protected $count; protected $clear; protected $container = array (); @@ -51,10 +51,13 @@ class PokerGames public function __construct() { $this->container = $this->makePoker(); - $this->count = count($this->container); - $this->i = $this->tally = round(100 / $this->count,2); - $this->clear = in_array(PHP_OS,array ('Darwin','Linux')); - $this->taskJob($this->generator($this->count, $this->count)); + $count = count($this->container); + $this->i = $this->tally = round(100 / $count, 2); + $this->clear = in_array(PHP_OS, array ('Darwin', 'Linux')); + $this->taskJob($this->generator($count, round($count / 2))); + if (array_diff_assoc($this->container, $this->poker)) { + $this->taskJob($this->generator(max(array_keys($this->container)), round($count / 2))); + } } /** @@ -64,15 +67,19 @@ public function __construct() */ public function taskJob(Generator $task) { - foreach ($task as $value) { // 1. 这是无脑递归 - if (isset($this->container[$value])) { - array_push($this->poker, $this->container[$value]); - unset($this->container[$value]); - $this->clear && system("clear"); - echo "正在洗牌中.. ".intval($this->tally)."% \n"; - $this->tally += $this->i; - } else { - $this->taskJob($this->generator($this->count)); + foreach ($task as $value) { // 1. 这里无脑搞 + if (empty($value)) { + break; + } + foreach ($value as $_value) { + if (isset($this->container[$_value])) { + array_push($this->poker, $this->container[$_value]); + unset($this->container[$_value]); + $this->clear && system("clear"); + echo "正在洗牌中.. " . intval($this->tally) . "% \n"; + $this->tally += $this->i; + } + continue; } } } @@ -82,7 +89,6 @@ public function taskJob(Generator $task) */ public function __destruct() { - curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 var_dump($this->poker); } @@ -93,7 +99,7 @@ public function __destruct() * @param $max * @return \Generator */ - public function generator($max,$limit = 1) + public function generator($max, $limit = 1) { while ($limit--) { yield $this->makeRand($max); @@ -138,13 +144,13 @@ public function makePoker() * 去大气噪音那里拿随机数 * * @param $max - * @return int + * @return mixed */ public function makeRand($max) { $ch = curl_init(); curl_setopt_array($ch, [ - CURLOPT_URL => sprintf(self::RANDOM, 1, $max), + CURLOPT_URL => sprintf(self::RANDOM, $max, $max), CURLOPT_SSL_VERIFYPEER => false, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array ('Expect:'), @@ -155,10 +161,12 @@ public function makeRand($max) $result = curl_exec($ch); $code = curl_getinfo($ch)['http_code']; $this->resources = $ch; + curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 if ($code == 200) { - return (int)$result; + return explode(PHP_EOL, $result); } - return 0; + return false; } } + new PokerGames(); From f9bc36690b748c75a7d2747d6963e2e8e9060826 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Sep 2017 17:17:04 +0800 Subject: [PATCH 050/127] fix: qulick :green_apple: --- package/Other/PokerGames.php | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index 394adab..850f55d 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -55,19 +55,16 @@ public function __construct() $this->i = $this->tally = round(100 / $count, 2); $this->clear = in_array(PHP_OS, array ('Darwin', 'Linux')); $this->taskJob($this->generator($count, round($count / 2))); - if (array_diff_assoc($this->container, $this->poker)) { - $this->taskJob($this->generator(max(array_keys($this->container)), round($count / 2))); - } } /** - * 弄着玩,不推进实际生产里玩 + * 弄着玩,不推进实际生产里玩 | 无脑方法2 * * @param \Generator $task */ public function taskJob(Generator $task) { - foreach ($task as $value) { // 1. 这里无脑搞 + foreach ($task as $value) { if (empty($value)) { break; } @@ -89,6 +86,8 @@ public function taskJob(Generator $task) */ public function __destruct() { + curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 + $this->poker = array_merge($this->poker, array_diff_assoc($this->container, $this->poker)); var_dump($this->poker); } @@ -161,7 +160,6 @@ public function makeRand($max) $result = curl_exec($ch); $code = curl_getinfo($ch)['http_code']; $this->resources = $ch; - curl_close($this->resources); // 2. 关闭资源在这个时候关闭是否合适 有待考究 if ($code == 200) { return explode(PHP_EOL, $result); } From e6bec0830eb6cc18366ffc07ba13549ca3259ddc Mon Sep 17 00:00:00 2001 From: Marco Date: Thu, 21 Sep 2017 10:18:27 +0800 Subject: [PATCH 051/127] Create CODE_OF_CONDUCT.md --- CODE_OF_CONDUCT.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..7ee229d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +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. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +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. + +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. + +## Scope + +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. + +## Enforcement + +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. + +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. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ From 04cf78a8ef89009f8283f4b179d28efcd0223fd0 Mon Sep 17 00:00:00 2001 From: Marco Date: Thu, 21 Sep 2017 10:21:10 +0800 Subject: [PATCH 052/127] Create CONTRIBUTING.md --- CONTRIBUTING.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..cc8499a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,15 @@ +What does “open source” mean? + +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. + +Open source is powerful because it lowers the barriers to adoption, allowing ideas to spread quickly. + +To understand how it works, imagine your friend is having a potluck, and you bring a cherry pie. + +Everybody tries the pie (use) +The pie is a hit! They ask you for the recipe, which you provide (view) +One friend, Alex, who’s a pastry chef, suggests reducing the sugar (modify) +Another friend, Lisa, asks to use it for a dinner next week (distribute) +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. + +Why do people open source their work? From bce8e826bf3bbceb5a9b062ffebb2d5cc2b5625d Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 22 Sep 2017 15:30:46 +0800 Subject: [PATCH 053/127] fix: modify bug :sparkles: --- package/Sort/ShellSort.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/package/Sort/ShellSort.php b/package/Sort/ShellSort.php index 809c8cd..45ba10a 100644 --- a/package/Sort/ShellSort.php +++ b/package/Sort/ShellSort.php @@ -9,18 +9,17 @@ * ------------------------------------------------------------- * 希尔排序中一个常数因子n,原数组被分成各个小组,每个小组由h个元素组成,很可能会有多余的元素。 * 当然每次循环的时候,h也是递减的(h=h/n)。第一次循环就是从下标为h开始。希尔排序的一个思想就是,分成小组去排序。 - * * @param array $container * @return array */ -function ShellSort( array $container ) +function ShellSort(array $container) { $count = count($container); - for ( $increment = intval($count / 2); $increment > 0; $increment = intval($increment / 2) ) { - for ( $i = $increment; $i < $count; $i++ ) { + for ($increment = intval($count / 2); $increment > 0; $increment = intval($increment / 2)) { + for ($i = $increment; $i < $count; $i++) { $temp = $container[$i]; - for ( $j = $i; $j >= $increment; $j -= $increment ) { - if ( $temp < $container[$j - $increment] ) { + for ($j = $i; $j >= $increment; $j -= $increment) { + if ($temp < $container[$j - $increment]) { $container[$j] = $container[$j - $increment]; } else { break; @@ -32,5 +31,6 @@ function ShellSort( array $container ) return $container; } -var_dump( ShellSort([6,13,21,99,18,2,25,33,19,84])); +//var_dump(ShellSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); + From d98ec862c27a7660ee081ee1d13b8f588bd762ce Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 26 Sep 2017 17:21:14 +0800 Subject: [PATCH 054/127] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a41029..02c2d4c 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ left|right 24 = 16 | log216 = 4 25 = 32 | log232 = 5 -就是酱紫,你要是没有学会,我们也不会等你 +战斗吧!少年 ## 运行时间 以二分查找为例,使用它可节省多少时间呢?简单查找诸葛地检查数字,如果列表包含100个数字,最多需要猜100次。 From 3bb5d353a0e1bcc850c4ecd0242421392e4c30eb Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Thu, 28 Sep 2017 21:01:57 +0800 Subject: [PATCH 055/127] fix: Modify the redundant loop :art: --- package/Sort/BubbleSort.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package/Sort/BubbleSort.php b/package/Sort/BubbleSort.php index 66c0133..bb49948 100644 --- a/package/Sort/BubbleSort.php +++ b/package/Sort/BubbleSort.php @@ -64,7 +64,7 @@ function BubbleSortV2(array $container) { $len = count($container); // 也可以用foreach - for ($i = 0; $i < $len; $i++) { + for ($i = 0; $i < $len - 1; $i++) { for ($j = $i + 1; $j < $len; $j++) { if ($container[$i] > $container[$j]) { list($container[$i], $container[$j]) = array($container[$j], $container[$i]); From d8367e7188c012d2044cb32b4ca1052979c7506b Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Fri, 29 Sep 2017 21:07:37 +0800 Subject: [PATCH 056/127] feat: linear list add :rotating_light: --- README.md | 68 +++++ package/Structure/LinearList.php | 425 +++++++++++++++++++++++++++++++ 2 files changed, 493 insertions(+) create mode 100644 package/Structure/LinearList.php diff --git a/README.md b/README.md index 02c2d4c..87dfc42 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,9 @@ │ │ ├── FibonacciQuery.php 斐波那契查找 │ │ └── QulickQuery.php 快速查找 │ │ + │ ├── Structure 数据结构 + │ │ └── LinearList.php 线性表 + │ │ │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 │ ├── DynamicProgramming.php 动态规划 @@ -100,6 +103,71 @@ left|right - 算法的运行时间用大O表示发表示 - O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 +## 编写解决实际问题的程序过程 + +- 如何用数据形式描述问题,即将问题抽象为一个数学模型 +- 问题所涉及到的数据量的大小及数据之间的关系 +- 如何在计算机中储存数据及体现数据之间的关系 +- 处理数据时需要对数据执行的操作 +- 编写的程序的性能是否良好 + +## 数据(Data) + +- 是客观事物的符号表示,在计算机科学中指的是所有能输入到计算机中并被计算机程序处理的符号的总称。 +- 数据元素(Data Element) :是数据的基本单位,在程序中通常作为一个整体来进行考虑和处理。一个数据元素可由若干个数据项(Data Item)组成。 +- 数据项(Data Item) : 是数据的不可分割的最小单位。数据项是对客观事物某一方面特性的数据描述。 +- 数据对象(Data Object) :是性质相同的数据元素的集合,是数据的一个子集。如字符集合C={‘A’,’B’,’C,…} 。 +- 数据结构 :相互之间具有一定联系的数据元素的集合。 +- 数据的逻辑结构 : 数据元素之间的相互关系称为逻辑结构。 +- 数据操作 : 对数据要进行的运算 +- 数据类型(Data Type):指的是一个值的集合和定义在该值集上的一组操作的总称。 + +## 数据的逻辑结构有四种基本类型 + +- 集合:结构中数据元素之间除了“属于同一个集合"外,再也没有其他的关系 +- 线性结构:结构中的数据元素存在一对一的关系 +- 树形结构:结构中的数据元素存在一对多的关系 +- 网状或者图状结构:结构中的数据元素存在多对多的关系 + +## 数据结构的储存方式 + +由数据元素之间的关系在计算机中有两种不同的表示方法——顺序表示和非顺序表示,从则导出两种储存方式,顺序储存结构和链式储存结构 + +- 顺序存储结构:用数据元素在存储器中的相对位置来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是连续的 +- 链式存储结构:在每一个数据元素中增加一个存放另一个元素地址的指针(pointer ),用该指针来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是否连续没有要求 + +数据的逻辑结构和物理结构是密不可分的两个方面,一个算法的设计取决于所选定的逻辑结构,而算法的实现依赖于所采用的存储结构 + + +## 算法(Algorithm) + +是对特定问题求解方法(步骤)的一种描述,是指令的有限序列,其中每一条指令表示一个或多个操作。 +> 算法具有以下五个特性 + +- 有穷性: 一个算法必须总是在执行有穷步之后结束,且每一步都在有穷时间内完成 +- 确定性:算法中每一条指令必须有确切的含义,不存在二义性,且算法只有一个入口和一个出口 +- 可行性: 一个算法是能行的,即算法描述的操作都可以通过已经实现的基本运算执行有限次来实现 +- 输入: 一个算法有零个或多个输入,这些输入取自于某个特定的对象集合 +- 输出: 一个算法有一个或多个输出,这些输出是同输入有着某些特定关系的量 + +> 算法和程序是两个不同的概念 + +一个计算机程序是对一个算法使用某种程序设计语言的具体实现。算法必须可终止意味着不是所有的计算机程序都是算法。 + +> 评价一个好的算法有以下几个标准 + +- 正确性(Correctness ): 算法应满足具体问题的需 +- 可读性(Readability): 算法应容易供人阅读和交流,可读性好的算法有助于对算法的理解和修改 +- 健壮性(Robustness): 算法应具有容错处理,当输入非法或错误数据时,算法应能适当地作出反应或进行处理,而不会产生莫名其妙的输出结果 +- 通用性(Generality): 算法应具有一般性 ,即算法的处理结果对于一般的数据集合都成立 + +> 效率与存储量需求: 效率指的是算法执行的时间;存储量需求指算法执行过程中所需要的最大存储空间,一般地,这两者与问题的规模有关 + +## 算法的时间复杂度 +算法中基本操作重复执行的次数是问题规模n的某个函数,其时间量度记作T(n)=O(f(n)),称作算法的渐近时间复杂度(Asymptotic Time complexity),简称时间复杂度 + +## 算法的空间复杂度 +是指算法编写成程序后,在计算机中运行时所需存储空间大小的度量,记作:S(n)=O(f(n)),其中n为问题规模 ## 递归和循环的简单比较: diff --git a/package/Structure/LinearList.php b/package/Structure/LinearList.php new file mode 100644 index 0000000..05cb04f --- /dev/null +++ b/package/Structure/LinearList.php @@ -0,0 +1,425 @@ + + * @date 2017/9/29 + * @license MIT + * ------------------------------------------------------------- + * [基本说明] + * ======= + * 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的 + * 注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储) + * 但是把最后一个数据元素的尾指针指向了首位结点)。 + * [基本特点] + * ======= + * - 存在一个唯一的被称为`第一个`的数据元素 + * - 存在一个唯一的被称为`最后一个`的数据元素 + * - 除第一个元素外,每个元素均有唯一一个直接前驱 + * - 除最后一个元素外,每个元素均有唯一一个直接后继 + * ------------------------------------------------------------- + * [定义] + * ======= + * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 + * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 + * 当n=0时,称为空表。 + * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 + * ------------------------------------------------------------- + * [线性表顺序存储] + * ======= + * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称顺序表。 + * ------------------------------------------------------------- + * [顺序存储的线性表的特点] + * ======= + * - 线性表的逻辑顺序与物理顺序一致; + * - 数据元素之间的关系是以元素在计算机内“物理位置相邻”来体现。 + * ------------------------------------------------------------- + * @param array + */ +class LinearList +{ + const PRECURSOR_KEY = 0; + const PRECURSOR_VALUE = 1; + + const SUBSEQUENT_KEY = 0; + const SUBSEQUENT_VALUE = 1; + + const ASSIGN_KEY = 0; + const DEFAULT_KEY = 1; + + + /** + * @var array|mixed 顺序表 + */ + public $oll; + + /** + * LinearList constructor. 顺序表初始化 + * + * @param array $oll + */ + public function __construct($oll = array ()) + { + $this->oll = $oll; + } + + /** + * @return void 清空顺序表 + */ + public function __destruct() + { + $this->preDispatch(); // 调试用,请无视 + foreach ($this->oll as $key => $value) { + unset($this->oll[$key]); + } + } + + /** + * 判断顺序表是否为空 + * + * @return boolean 为空返回true,否则返回false + */ + public function isEmpty() + { + $this->preDispatch(); // 调试用,请无视 + return count($this->oll) > 0 ? false : true; + } + + /** + * 返回顺序表的长度 + * + * @return int + */ + public function getLength() + { + $this->preDispatch(); // 调试用,请无视 + return count($this->oll); + } + + /** + * 返回顺序表中下标为$key的元素 + * + * @param mixed $key 顺序表元素的下标 + * @return mixed + */ + public function getElement($key) + { + $this->preDispatch(); // 调试用,请无视 + return $this->oll[$key]; + } + + /** + * 返回顺序表中某个元素的位置 + * + * @param mixed $value 顺序表中某个元素的值 + * @return int 从1开始,如果返回-1表示不存在该元素 + */ + public function getElementPosition($value) + { + $this->preDispatch(); // 调试用,请无视 + $i = 0; + foreach ($this->oll as $val) { + $i++; + if (strcmp($value, $val) === 0) { + return $i; + } + } + return -1; + } + + /** + * 返回顺序表中某个元素的直接前驱元素 + * + * @param string $value 顺序表中某个元素的值 + * @param int $tag 如果$value为下标则为1, 如果$value为元素值则为0 + * @return array|bool array('value'=>...)直接前驱元素值,array('key'=>...)直接前驱元素下标 + */ + public function getElementPrecursor($value, $tag = self::PRECURSOR_VALUE) + { + $this->preDispatch(); // 调试用,请无视 + $i = 0; + foreach ($this->oll as $key => $val) { + $i++; + if ($tag == self::PRECURSOR_VALUE) { + if (strcmp($key, $value) === 0) { + if ($i == 1) { + return false; + } + prev($this->oll); + prev($this->oll); + return array ('value' => current($this->oll), 'key' => key($this->oll)); + } + } + + if ($tag == self::PRECURSOR_KEY) { + if (strcmp($val, $value) === 0) { + if ($i == 1) { + return false; + } + prev($this->oll); + prev($this->oll); + return array ('value' => current($this->oll), 'key' => key($this->oll)); + } + } + } + } + + /** + * 返回某个元素的直接后继元素 + * + * @param $value $value顺序表中某个元素的值 + * @param int $tag 如果$value为下标则为1,如果$value为元素值则为0 + * @return array|bool array('value'=>...)直接后继元素值,array('key'=>...)直接后继元素下标 + */ + public function getElementSubsequent($value, $tag = self::SUBSEQUENT_KEY) + { + $this->preDispatch(); // 调试用,请无视 + $i = 0; + $len = count($this->oll); + foreach ($this->oll as $key => $val) { + $i++; + if ($tag == self::SUBSEQUENT_KEY) { + if (strcmp($key, $value) == 0) { + if ($i == $len) { + return false; + } + return array ('value' => current($this->oll), 'key' => key($this->oll)); + } + } + if ($tag == self::SUBSEQUENT_VALUE) { + if (strcmp($val, $value) == 0) { + if ($i == $len) { + return false; + } + return array ('value' => current($this->oll), 'key' => key($this->oll)); + } + } + } + return false; + } + + /** + * 在指定位置插入一个新的结点 + * + * @param string $p 新结点插入位置,从1开始 + * @param string $value 顺序表新结点的值 + * @param null $key 顺序表新结点的下标 + * @param int $tag 是否指定新结点的下标,1表示默认下标,0表示指定下标 + * @return bool 插入成功返回true,失败返回false + */ + public function getInsertElement($p, $value, $key = null, $tag = self::DEFAULT_KEY) + { + $this->preDispatch(); // 调试用,请无视 + + $p = (int)$p; + $len = count($this->oll); + $oll = array (); + $i = 0; + if ($p > $len || $p < 1) { + return false; + } + + foreach ($this->oll as $k => $v) { + $i++; + if ($i == (int)$p) { + if ($tag == self::DEFAULT_KEY) { + $oll[] = $value; + } else if ($tag == self::ASSIGN_KEY) { + $keys = array_keys($oll); + $j = 0; + if (is_int($key)) { + while (in_array($key, $keys, true)) { + $key++; + } + } else { + while (in_array($key, $keys, true)) { + $j++; + $key .= (string)$j; + } + } + $oll[$key] = $value; + } else { + return false; + } + + $key = $k; + $j = 0; + $keys = array_keys($oll); + if (is_int($key)) { + $oll[] = $v; + } else { + while (in_array($key, $keys, true)) { + $j++; + $key .= (string)$j; + } + $oll[$key] = $v; + } + } else { + if ($i > $p) { + $key = $k; + $j = 0; + $keys = array_keys($oll); + if (is_int($key)) { + $oll[] = $v; + } else { + while (in_array($key, $keys, true)) { + $j++; + $key .= (string)$j; + } + $oll[$key] = $v; + } + } else { + if (is_int($k)) { + $oll[] = $v; + } else { + $oll[$k] = $v; + } + } + } + } + $this->oll = $oll; + return true; + } + + /** + * 根据元素位置返回顺序表中的某个元素 + * + * @param mixed $position 元素位置从1开始 + * @return array|bool array('value'=>...)元素值,array('key'=>...)元素下标 + */ + public function getElemForPos($position) + { + $this->preDispatch(); // 调试用,请无视 + + $i = 0; + $len = count($this->oll); + $position = (int)$position; + + if ($position > $len || $position < 1) { + return false; + } + + foreach ($this->oll as $value) { + $i++; + if ($i == $position) { + return array ('value' => current($this->oll), 'key' => key($this->oll)); + } + } + } + + /** + * 根据下标或者元素值删除顺序表中的某个元素 + * + * @param mixed $value 元素下标或者值 + * @param int $tag 1表示$value为下标,2表示$value为元素值 + * @return bool 成功返回true,失败返回false + */ + public function getDeleteElement($value, $tag = 1) + { + $this->preDispatch(); // 调试用,请无视 + + $len = count($this->oll); + $oll = array (); + foreach ($this->oll as $k => $v) { + if ($tag == 1) { + if (strcmp($k, $value) === 0) { + } else { + if (is_int($k)) { + $oll[] = $v; + } else { + $oll[$k] = $v; + } + } + } + + if ($tag == 2) { + if (strcmp($v, $value) === 0) { + } else { + if (is_int($k)) { + $oll[] = $v; + } else { + $oll[$k] = $v; + } + } + } + } + $this->oll = $oll; + if (count($this->oll) == $len) { + return false; + } + return true; + } + + /** + * 根据元素位置删除顺序表中的某个元素 + * + * @param int $position 元素位置从1开始 + * @return bool 成功返回true,失败返回false + */ + public function getDeleteEleForPos($position) + { + $this->preDispatch(); // 调试用,请无视 + + $len = count($this->oll); + $i = 0; + $position = (int)$position; + $oll = array (); + if ($position > $len || $position < 1) { + return false; + } + + foreach ($this->oll as $k => $v) { + $i++; + if ($i == $position) { + } else { + if (is_int($k)) { + $oll[] = $v; + } else { + $oll[$k] = $v; + } + } + } + + $this->oll = $oll; + if (count($this->oll) == $len) { + return false; + } + return true; + } + + /** + * 调试用 + * + * @param bool $isDebug + * @return mixed + */ + public function preDispatch($isDebug = true) + { + if(!$isDebug){ + return false; + } + $debug = debug_backtrace()[1]; + $args = isset($debug['args']) ? implode(',',$debug['args']) : ""; + echo "{$debug['function']}({$args})\n".PHP_EOL; + } +} + +$echo = function () { + $args = func_get_args(); + echo $args[0] . "\t->\t" . var_export($args[1], true) . PHP_EOL; + echo "--------------------------- " . PHP_EOL; +}; + +$oll = new LinearList(array ('name' => 'Jack', 10, "age", 'msg' => 10, 455)); +$echo('判断顺序表是否为空,返回false说明不为空', $oll->isEmpty()); +$echo('返回顺序表的长度 返回6', $oll->getLength()); +$echo('根据下标返回顺序表中的某个元素', $oll->getElement(1)); +$echo('返回顺序表中某个元素的位置', $oll->getElementPosition(455)); +$echo('返回顺序表中某个元素的直接前驱元素', $oll->getElementPrecursor(455, 2)); +$echo('返回顺序表中某个元素的直接后继元素', $oll->getElementSubsequent(455, 2)); +$echo('根据元素位置返回顺序表中的某个元素', $oll->getElemForPos(2)); +$echo('根据下标或者元素值删除顺序表中的某个元素', $oll->getDeleteElement('name', $tag = 2)); +$echo('根据元素位置删除顺序表中的某个元素', $oll->getDeleteEleForPos(1)); +$echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", $key = "msg", $tag = 2)); +$echo('$oll->oll的内容 ', $oll->oll); \ No newline at end of file From 1965544d03473c50aea68ebdf730a37e78509b50 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 30 Sep 2017 12:41:44 +0800 Subject: [PATCH 057/127] fix: Fixed redundancy :construction_worker: --- package/Structure/LinearList.php | 359 +++++++++++++------------------ 1 file changed, 150 insertions(+), 209 deletions(-) diff --git a/package/Structure/LinearList.php b/package/Structure/LinearList.php index 05cb04f..59b9412 100644 --- a/package/Structure/LinearList.php +++ b/package/Structure/LinearList.php @@ -28,7 +28,7 @@ * ------------------------------------------------------------- * [线性表顺序存储] * ======= - * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称顺序表。 + * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称线性表。 * ------------------------------------------------------------- * [顺序存储的线性表的特点] * ======= @@ -37,164 +37,181 @@ * ------------------------------------------------------------- * @param array */ -class LinearList +class LinearList extends ArrayObject { - const PRECURSOR_KEY = 0; - const PRECURSOR_VALUE = 1; + const PRECURSOR_KEY = 0; + const PRECURSOR_VALUE = 1; const SUBSEQUENT_KEY = 0; const SUBSEQUENT_VALUE = 1; - const ASSIGN_KEY = 0; - const DEFAULT_KEY = 1; + const ASSIGN_KEY = 0; + const DEFAULT_KEY = 1; + const DELETE_KEY = 0; + const DELETE_VALUE = 1; /** - * @var array|mixed 顺序表 + * @var array|mixed 线性表 */ public $oll; /** - * LinearList constructor. 顺序表初始化 + * LinearList constructor. 线性表初始化 * * @param array $oll */ public function __construct($oll = array ()) { - $this->oll = $oll; + echo '---------------------------'.PHP_EOL; + echo var_export($oll).PHP_EOL; + echo '---------------------------'.PHP_EOL; + parent::__construct($oll); + $this->oll = $this->getIterator(); } /** - * @return void 清空顺序表 + * @return void 清空线性表 */ public function __destruct() + { + unset($this->oll); + } + + /** + * 调试用请无视 + * + * @param $name + * @param $arguments + * @return mixed + */ + public function __call($name, $arguments) { $this->preDispatch(); // 调试用,请无视 - foreach ($this->oll as $key => $value) { - unset($this->oll[$key]); - } + return call_user_func_array(array($this, $name), $arguments); } /** - * 判断顺序表是否为空 + * 判断线性表是否为空 * * @return boolean 为空返回true,否则返回false */ - public function isEmpty() + protected function isEmpty() { - $this->preDispatch(); // 调试用,请无视 - return count($this->oll) > 0 ? false : true; + return $this->getLength() > 0 ? false : true; } /** - * 返回顺序表的长度 + * 返回线性表的长度 * * @return int */ - public function getLength() + protected function getLength() { - $this->preDispatch(); // 调试用,请无视 - return count($this->oll); + return $this->oll->count(); } /** - * 返回顺序表中下标为$key的元素 + * 返回线性表中下标为$key的元素 * - * @param mixed $key 顺序表元素的下标 + * @param mixed $key 线性表元素的下标 * @return mixed */ - public function getElement($key) + protected function getElement($key) { - $this->preDispatch(); // 调试用,请无视 - return $this->oll[$key]; + return $this->oll->offsetGet($key); } /** - * 返回顺序表中某个元素的位置 + * 返回线性表中某个元素的位置 * - * @param mixed $value 顺序表中某个元素的值 + * @param mixed $value 线性表中某个元素的值 * @return int 从1开始,如果返回-1表示不存在该元素 */ - public function getElementPosition($value) + protected function getElementPosition($value) { - $this->preDispatch(); // 调试用,请无视 $i = 0; - foreach ($this->oll as $val) { + $this->oll->rewind(); + while ($this->oll->valid()) { $i++; - if (strcmp($value, $val) === 0) { + if (strcmp($value, $this->oll->current()) === 0) { return $i; } + $this->oll-> next(); } return -1; } /** - * 返回顺序表中某个元素的直接前驱元素 + * 返回线性表中某个元素的直接前驱元素 * - * @param string $value 顺序表中某个元素的值 + * @param string $value 线性表中某个元素的值 * @param int $tag 如果$value为下标则为1, 如果$value为元素值则为0 * @return array|bool array('value'=>...)直接前驱元素值,array('key'=>...)直接前驱元素下标 */ - public function getElementPrecursor($value, $tag = self::PRECURSOR_VALUE) + protected function getElementPrecursor($value, $tag = self::PRECURSOR_VALUE) { - $this->preDispatch(); // 调试用,请无视 - $i = 0; - foreach ($this->oll as $key => $val) { - $i++; - if ($tag == self::PRECURSOR_VALUE) { - if (strcmp($key, $value) === 0) { - if ($i == 1) { - return false; - } - prev($this->oll); - prev($this->oll); - return array ('value' => current($this->oll), 'key' => key($this->oll)); + $i = 0; + $prev = null; + $this->oll->rewind(); + while ($this->oll->valid()) { + $key = $this->oll->key(); + $current = $this->oll->current(); + if (strcmp($key, $value) === 0) { + if ($i == 1) { + return false; } + return array ('value' => $this->getElement($prev), 'key' => $prev); } - - if ($tag == self::PRECURSOR_KEY) { - if (strcmp($val, $value) === 0) { + if ($tag == self::PRECURSOR_VALUE) { + if (strcmp($current, $value) === 0) { if ($i == 1) { return false; } - prev($this->oll); - prev($this->oll); - return array ('value' => current($this->oll), 'key' => key($this->oll)); + return array ('value' => $this->getElement($prev), 'key' => $prev); } } + $i++; + $prev = $this->oll->key(); + $this->oll->next(); } } /** * 返回某个元素的直接后继元素 * - * @param $value $value顺序表中某个元素的值 + * @param string $value $value线性表中某个元素的值 * @param int $tag 如果$value为下标则为1,如果$value为元素值则为0 * @return array|bool array('value'=>...)直接后继元素值,array('key'=>...)直接后继元素下标 */ - public function getElementSubsequent($value, $tag = self::SUBSEQUENT_KEY) + protected function getElementSubsequent($value, $tag = self::SUBSEQUENT_KEY) { - $this->preDispatch(); // 调试用,请无视 $i = 0; - $len = count($this->oll); - foreach ($this->oll as $key => $val) { - $i++; + $len = $this->getLength(); + $this->oll->rewind(); + while ($this->oll->valid()) { + $key = $this->oll->key(); + $current = $this->oll->current(); if ($tag == self::SUBSEQUENT_KEY) { if (strcmp($key, $value) == 0) { if ($i == $len) { return false; } - return array ('value' => current($this->oll), 'key' => key($this->oll)); + $this->oll->next(); + return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); } } if ($tag == self::SUBSEQUENT_VALUE) { - if (strcmp($val, $value) == 0) { + if (strcmp($current, $value) == 0) { if ($i == $len) { return false; } - return array ('value' => current($this->oll), 'key' => key($this->oll)); + $this->oll->next(); + return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); } } + $i++; + $this->oll->next(); } return false; } @@ -202,188 +219,112 @@ public function getElementSubsequent($value, $tag = self::SUBSEQUENT_KEY) /** * 在指定位置插入一个新的结点 * - * @param string $p 新结点插入位置,从1开始 - * @param string $value 顺序表新结点的值 - * @param null $key 顺序表新结点的下标 + * @param string $p 新结点插入位置,从0开始 + * @param string $value 线性表新结点的值 + * @param null $key 线性表新结点的下标 * @param int $tag 是否指定新结点的下标,1表示默认下标,0表示指定下标 - * @return bool 插入成功返回true,失败返回false + * @return bool 插入成功返回true,失败返回false */ - public function getInsertElement($p, $value, $key = null, $tag = self::DEFAULT_KEY) + protected function getInsertElement($p, $value, $key = null, $tag = self::DEFAULT_KEY) { - $this->preDispatch(); // 调试用,请无视 - $p = (int)$p; - $len = count($this->oll); - $oll = array (); $i = 0; - if ($p > $len || $p < 1) { + if ($p > $this->getLength() || $p < 1) { return false; } - - foreach ($this->oll as $k => $v) { - $i++; - if ($i == (int)$p) { - if ($tag == self::DEFAULT_KEY) { - $oll[] = $value; - } else if ($tag == self::ASSIGN_KEY) { - $keys = array_keys($oll); - $j = 0; - if (is_int($key)) { - while (in_array($key, $keys, true)) { - $key++; - } - } else { - while (in_array($key, $keys, true)) { - $j++; - $key .= (string)$j; - } - } - $oll[$key] = $value; - } else { - return false; - } - - $key = $k; - $j = 0; - $keys = array_keys($oll); - if (is_int($key)) { - $oll[] = $v; - } else { - while (in_array($key, $keys, true)) { - $j++; - $key .= (string)$j; - } - $oll[$key] = $v; - } - } else { - if ($i > $p) { - $key = $k; - $j = 0; - $keys = array_keys($oll); - if (is_int($key)) { - $oll[] = $v; - } else { - while (in_array($key, $keys, true)) { - $j++; - $key .= (string)$j; - } - $oll[$key] = $v; - } - } else { - if (is_int($k)) { - $oll[] = $v; - } else { - $oll[$k] = $v; - } - } + $this->oll->rewind(); + while ($this->oll->valid()) { + if ($i != $p) { + $i++; + $this->oll->next(); + } + switch ($tag){ + case self::DEFAULT_KEY: + $this->oll->append($value); + break 2; + case self::ASSIGN_KEY: + $this->oll->offsetSet($key, $value); + break 2; } } - $this->oll = $oll; return true; } /** - * 根据元素位置返回顺序表中的某个元素 + * 根据元素位置返回线性表中的某个元素 * * @param mixed $position 元素位置从1开始 * @return array|bool array('value'=>...)元素值,array('key'=>...)元素下标 */ - public function getElemForPos($position) + protected function getElemForPos($position) { - $this->preDispatch(); // 调试用,请无视 - $i = 0; - $len = count($this->oll); + $len = $this->getLength(); $position = (int)$position; - if ($position > $len || $position < 1) { return false; } - - foreach ($this->oll as $value) { - $i++; + $this->oll->rewind(); + while ($this->oll->valid()) { if ($i == $position) { - return array ('value' => current($this->oll), 'key' => key($this->oll)); + return array ('value' => $this->oll->current(), 'key' => $this->oll->key()); } + $i++; + $this->oll->next(); } } /** - * 根据下标或者元素值删除顺序表中的某个元素 + * 根据下标或者元素值删除线性表中的某个元素 * * @param mixed $value 元素下标或者值 - * @param int $tag 1表示$value为下标,2表示$value为元素值 + * @param int $tag 0表示$value为下标,1表示$value为元素值 * @return bool 成功返回true,失败返回false */ - public function getDeleteElement($value, $tag = 1) + protected function getDeleteElement($value, $tag = self::DELETE_KEY) { - $this->preDispatch(); // 调试用,请无视 - - $len = count($this->oll); - $oll = array (); - foreach ($this->oll as $k => $v) { - if ($tag == 1) { - if (strcmp($k, $value) === 0) { - } else { - if (is_int($k)) { - $oll[] = $v; - } else { - $oll[$k] = $v; - } + $this->oll->rewind(); + while ($this->oll->valid()) + { + $key = $this->oll->key(); + $current = $this->oll->current(); + if ($tag == self::DELETE_KEY) { + if (strcmp($key, $value) === 0) { + $this->oll->offsetUnset($key); } } - - if ($tag == 2) { - if (strcmp($v, $value) === 0) { - } else { - if (is_int($k)) { - $oll[] = $v; - } else { - $oll[$k] = $v; - } + if ($tag == self::DELETE_VALUE) { + if (strcmp($current, $value) === 0) { + $this->oll->offsetUnset($key); } } - } - $this->oll = $oll; - if (count($this->oll) == $len) { - return false; + $this->oll->next(); } return true; } /** - * 根据元素位置删除顺序表中的某个元素 + * 根据元素位置删除线性表中的某个元素 * * @param int $position 元素位置从1开始 * @return bool 成功返回true,失败返回false */ - public function getDeleteEleForPos($position) + protected function getDeleteEleForPos($position) { - $this->preDispatch(); // 调试用,请无视 - - $len = count($this->oll); + $len = $this->getLength(); $i = 0; $position = (int)$position; - $oll = array (); if ($position > $len || $position < 1) { return false; } - - foreach ($this->oll as $k => $v) { - $i++; + $this->oll->rewind(); + while ($this->oll->valid()) { + $key = $this->oll->key(); if ($i == $position) { - } else { - if (is_int($k)) { - $oll[] = $v; - } else { - $oll[$k] = $v; - } + $this->oll->offsetUnset($key); } - } - - $this->oll = $oll; - if (count($this->oll) == $len) { - return false; + $i++; + $this->oll->next(); } return true; } @@ -392,34 +333,34 @@ public function getDeleteEleForPos($position) * 调试用 * * @param bool $isDebug - * @return mixed + * @return bool */ - public function preDispatch($isDebug = true) + protected function preDispatch($isDebug = true) { - if(!$isDebug){ + if (!$isDebug) { return false; } - $debug = debug_backtrace()[1]; - $args = isset($debug['args']) ? implode(',',$debug['args']) : ""; - echo "{$debug['function']}({$args})\n".PHP_EOL; + $debug = debug_backtrace()[1]; + $reflection = new ReflectionMethod($this, $debug['args'][0]); + $args = isset($debug['args'][1]) ? implode(',', $debug['args'][1]) : ""; + echo $reflection->getDocComment() . PHP_EOL; + echo "{$debug['args'][0]}({$args})\n" . PHP_EOL; } } -$echo = function () { - $args = func_get_args(); - echo $args[0] . "\t->\t" . var_export($args[1], true) . PHP_EOL; +$echo = function ($str, $action) { + echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; echo "--------------------------- " . PHP_EOL; }; -$oll = new LinearList(array ('name' => 'Jack', 10, "age", 'msg' => 10, 455)); -$echo('判断顺序表是否为空,返回false说明不为空', $oll->isEmpty()); -$echo('返回顺序表的长度 返回6', $oll->getLength()); -$echo('根据下标返回顺序表中的某个元素', $oll->getElement(1)); -$echo('返回顺序表中某个元素的位置', $oll->getElementPosition(455)); -$echo('返回顺序表中某个元素的直接前驱元素', $oll->getElementPrecursor(455, 2)); -$echo('返回顺序表中某个元素的直接后继元素', $oll->getElementSubsequent(455, 2)); -$echo('根据元素位置返回顺序表中的某个元素', $oll->getElemForPos(2)); -$echo('根据下标或者元素值删除顺序表中的某个元素', $oll->getDeleteElement('name', $tag = 2)); -$echo('根据元素位置删除顺序表中的某个元素', $oll->getDeleteEleForPos(1)); -$echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", $key = "msg", $tag = 2)); +$oll = new LinearList(array ('name' => 'Jack', 10, "age", 'msg' => 10, 666)); +$echo('判断线性表是否为空', $oll->isEmpty()); +$echo('返回线性表的长度', $oll->getLength()); +$echo('根据下标返回线性表中的某个元素', $oll->getElement(1)); +$echo('返回线性表中某个元素的位置', $oll->getElementPosition(666)); +$echo('返回线性表中某个元素的直接前驱元素', $oll->getElementPrecursor(666, LinearList::PRECURSOR_VALUE)); +$echo('返回线性表中某个元素的直接后继元素', $oll->getElementSubsequent(0, LinearList::SUBSEQUENT_KEY)); +$echo('根据元素位置返回线性表中的某个元素', $oll->getElemForPos(2)); +$echo('根据下标或者元素值删除线性表中的某个元素', $oll->getDeleteElement('name', LinearList::DELETE_KEY)); +$echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", "qzone", LinearList::ASSIGN_KEY)); $echo('$oll->oll的内容 ', $oll->oll); \ No newline at end of file From cd392ea7db2ce6f8d06d3f5baad98db9451a149f Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 30 Sep 2017 17:06:37 +0800 Subject: [PATCH 058/127] feat: add linearChain :twisted_rightwards_arrows: --- README.md | 3 +- package/Structure/LinearChain.php | 390 ++++++++++++++++++ .../{LinearList.php => LinearOrder.php} | 28 +- 3 files changed, 411 insertions(+), 10 deletions(-) create mode 100644 package/Structure/LinearChain.php rename package/Structure/{LinearList.php => LinearOrder.php} (93%) diff --git a/README.md b/README.md index 87dfc42..fa77abe 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,8 @@ │ │ └── QulickQuery.php 快速查找 │ │ │ ├── Structure 数据结构 - │ │ └── LinearList.php 线性表 + │ │ ├── LinearChain.php 线性表 单链存储 + │ │ └── LinearOrder.php 线性表 顺序存储 │ │ │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 diff --git a/package/Structure/LinearChain.php b/package/Structure/LinearChain.php new file mode 100644 index 0000000..0e434e4 --- /dev/null +++ b/package/Structure/LinearChain.php @@ -0,0 +1,390 @@ + + * @date 2017/9/29 + * @license MIT + * ------------------------------------------------------------- + * [基本说明] + * ======= + * 线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的 + * 注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储) + * 但是把最后一个数据元素的尾指针指向了首位结点)。 + * [基本特点] + * ======= + * - 存在一个唯一的被称为`第一个`的数据元素 + * - 存在一个唯一的被称为`最后一个`的数据元素 + * - 除第一个元素外,每个元素均有唯一一个直接前驱 + * - 除最后一个元素外,每个元素均有唯一一个直接后继 + * ------------------------------------------------------------- + * [定义] + * ======= + * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 + * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 + * 当n=0时,称为空表。 + * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 + * ------------------------------------------------------------- + * [线性表顺序存储] + * ======= + * 用一组任意的存储单元存储线性表中的数据元素,用这种方法存储的线性表简称线性链表。 + * ------------------------------------------------------------- + * [顺序存储的线性表的特点] + * ======= + * - 存储链表中结点的一组任意的存储单元可以是连续的,也可以是不连续的,甚至是零散分布在内存中的任意位置上 + * - 链表中结点的逻辑顺序和物理顺序不一定相同 + * ------------------------------------------------------------- + * @param array + */ +class LinearChain +{ + /** + * @var string 下一结点指针 + */ + public $next; + + /** + * @var string 头结点数据 + */ + public $elem; + + /** + * @var int 链表长度 + */ + public $length; + + /** + * LinearChain constructor. 线性表初始化 + */ + public function __construct() + { + $this->next = $this->elem = $this->length = null; + } + + /** + * 清空单链表 + * + * @return mixed + */ + public function clearChain() + { + if ($this->length <= 0) { + return false; + } + while ($this->next != null) { + $q = $this->next->next; + $this->next = null; + unset($this->next); + $this->next = $q; + } + $this->length = 0; + } + + /** + * 返回单链表长度 + * + * @return mixed + */ + public function getLength() + { + return $this->length; + } + + /** + * 判断单链表是否为空 + * + * @return bool 为空返回true,不为空返回false + */ + public function getIsEmpty() + { + return $this->length == 0 && $this->next == null; + } + + /** + * 头插入法建表 + * + * @param array $arr 建立单链表的数据 + * @return mixed + */ + protected function getHeadCreateChain(array $arr) + { + $this->clearChain(); + foreach ($arr as $value) { + $node = new stdClass(); + $node->elem = $value; + $node->next = $this->next; + $this->next = $node; + $this->length++; + } + return $this->next; + } + + /** + * 尾插入法建表 + * + * @param array $arr 建立单链表的数据 + * @return mixed + */ + protected function getTailCreateChain(array $arr) + { + $this->clearChain(); + $q = $this; + foreach ($arr as $value) { + $node = new stdClass(); + $node->elem = $value; + $node->next = $q->next; + $q->next = $node; + $q = $node; + $this->length++; + } + return $this->next; + } + + /** + * 返回第$i个元素 + * + * @param int $i 元素位序,从1开始 + * @return mixed + */ + protected function getElemForPos($i) + { + $i = (int)$i; + if ($i > $this->length || $i < 1) { + return null; + } + $j = 1; + $p = $this->next; + while ($j < $i) { + $q = $p->next; + $p = $q; + $j++; + } + return $p; + } + + /** + * 查找单链表中是否存在某个值的元素 + * 如果有返回该元素结点,否则返回null + * + * @param mixed $value 查找的值 + * @return mixed + */ + protected function getElemIsExist($value) + { + $p = $this; + while ($p->next != null && strcmp($p->elem, $value) !== 0) { + $p = $p->next; + } + if (strcmp($p->elem, $value) === 0) { + return $p; + } + return null; + } + + /** + * 查找单链表中是否存在某个值的元素 + * 如果有返回该元素位序,否则返回-1 + * + * @param mixed $value 查找的值 + * @return mixed + */ + protected function getElemPosition($value) + { + $p = $this; + $j = 0; + while ($p->next != null && strcmp($p->elem, $value) !== 0) { + $p = $p->next; + $j++; + } + if (strcmp($p->elem, $value) === 0) { + return $j; + } + return -1; + } + + /** + * 单链表的插入操作 + * + * @param int $i 插入元素的位序,即在什么位置插入新的元素,从1开始 + * @param mixed $e 插入的新的元素值 + * @return boolean 插入成功返回true,失败返回false + */ + protected function getInsertElem($i, $e) + { + if ($i > $this->length || $i < 1) { + return false; + } + $j = 1; + $p = $this; + while ($p->next != null && $j < $i) { + $p = $p->next; + $j++; + } + $q = new stdClass(); + $q->elem = $e; + $q->next = $p->next; + $p->next = $q; + $this->length++; + return true; + } + + /** + * 遍历单链表中的所有元素 + * + * @return array 包括单链中的所有元素 + */ + protected function getAllElem() + { + $result = array (); + if ($this->getIsEmpty()) { + return $result; + } + $p = $this->next; + while ($p->next != null) { + $result[] = $p->elem; + $p = $p->next; + } + $result[] = $p->elem; + return $result; + } + + /** + * 删除单链中第$i个元素 + * + * @param int $i 元素位序 + * @return boolean 删除成功返回true,失败返回false + */ + protected function getDeleteElem($i) + { + $i = (int)$i; + if ($i > $this->length || $i < 1) { + return false; + } + $p = $this; + $j = 1; + while ($j < $i) { + $p = $p->next; + $j++; + } + $q = $p->next; + $p->next = $q->next; + $this->length--; + return true; + } + + /** + * 删除单链表中值为$value的前$i($i>=1)个结点 + * + * @param mixed mixed 待查找的值 + * @param $i mixed 删除的次数,即删除查找到的前$i个 + * @return mixed + */ + protected function getDeleteElemForValue($value, $i = 1) + { + if ($i > 1) { + $this->getDeleteElemForValue($value, $i - 1); + } + $vp = $this->getElemPosition($value); + $this->getDeleteElem($vp); + return $this->getAllElem(); + } + + /** + * 删除单链表所有重复的值 + * + * @return mixed + */ + protected function getElemUnique() + { + if (!$this->getIsEmpty()) { + $p = $this; + while ($p->next != null) { + $q = $p->next; + $ptr = $p; + while ($q->next != null) { + if (strcmp($p->elem, $q->elem) === 0) { + $ptr->next = $q->next; + $q->next = null; + unset($q->next); + $q = $ptr->next; + $this->length--; + } else { + $ptr = $q; + $q = $q->next; + } + } + if (strcmp($p->elem, $q->elem) === 0) { + $ptr->next = null; + $this->length--; + } + $p = $p->next; + } + } + return $this->getAllElem(); + } + + /** + * 调试用请无视 + * + * @param $name + * @param $arguments + * @return mixed + */ + public function __call($name, $arguments) + { + $this->preDispatch(); // 调试用,请无视 + return call_user_func_array(array ($this, $name), $arguments); + } + + /** + * 调试用请无视! + * + * @param bool $isDebug + * @return bool + */ + protected function preDispatch($isDebug = true) + { + if (!$isDebug) { + return false; + } + $debug = debug_backtrace()[1]; + $reflection = new ReflectionMethod($this, $debug['args'][0]); + $args = ''; + if (isset($debug['args'][1])) { + foreach ($debug['args'][1] as &$value) { + if (is_array($value)) { + $args .= json_encode($debug['args'][1]) . ', '; + } else { + $args .= $value . ', '; + } + } + } + $args = trim($args, ', '); + echo "\t" . $reflection->getDocComment() . PHP_EOL; + echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; + } +} + +$echo = function ($str, $action) { + echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; + echo "--------------------------- " . PHP_EOL; +}; +$personal = array ( + "One", + "Two", + "Three", + "Four", +); + +$oll = new LinearChain(); +$echo('头插入链表数据', $oll->getHeadCreateChain($personal)); +$echo('尾插入链表数据', $oll->getTailCreateChain($personal)); +$echo('返回第二个数据', $oll->getElemForPos(2)); +$echo('是否存在Tow呢?', $oll->getElemIsExist("Two")); +$echo('One 的下标示是', $oll->getElemPosition("One")); +$echo('从2号位插入一个Four', $oll->getInsertElem(2, "Four")); +$echo('遍历整个单链表', $oll->getAllElem()); +$echo('删除第一个元素', $oll->getDeleteElem(1)); +$echo('删除Three 前一个', $oll->getDeleteElemForValue("Three", 1)); +$echo('去重链表中重复值', $oll->getElemUnique()); \ No newline at end of file diff --git a/package/Structure/LinearList.php b/package/Structure/LinearOrder.php similarity index 93% rename from package/Structure/LinearList.php rename to package/Structure/LinearOrder.php index 59b9412..926f749 100644 --- a/package/Structure/LinearList.php +++ b/package/Structure/LinearOrder.php @@ -37,7 +37,7 @@ * ------------------------------------------------------------- * @param array */ -class LinearList extends ArrayObject +class LinearOrder extends ArrayObject { const PRECURSOR_KEY = 0; const PRECURSOR_VALUE = 1; @@ -342,9 +342,19 @@ protected function preDispatch($isDebug = true) } $debug = debug_backtrace()[1]; $reflection = new ReflectionMethod($this, $debug['args'][0]); - $args = isset($debug['args'][1]) ? implode(',', $debug['args'][1]) : ""; - echo $reflection->getDocComment() . PHP_EOL; - echo "{$debug['args'][0]}({$args})\n" . PHP_EOL; + $args = ''; + if(isset($debug['args'][1])){ + foreach ($debug['args'][1] as &$value){ + if( is_array($value )){ + $args .= json_encode($debug['args'][1]).', '; + }else{ + $args .= $value.', '; + } + } + } + $args = trim($args,', '); + echo "\t".$reflection->getDocComment() . PHP_EOL; + echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; } } @@ -353,14 +363,14 @@ protected function preDispatch($isDebug = true) echo "--------------------------- " . PHP_EOL; }; -$oll = new LinearList(array ('name' => 'Jack', 10, "age", 'msg' => 10, 666)); +$oll = new LinearOrder(array ('name' => 'Jack', 10, "age", 'msg' => 10, 666)); $echo('判断线性表是否为空', $oll->isEmpty()); $echo('返回线性表的长度', $oll->getLength()); $echo('根据下标返回线性表中的某个元素', $oll->getElement(1)); $echo('返回线性表中某个元素的位置', $oll->getElementPosition(666)); -$echo('返回线性表中某个元素的直接前驱元素', $oll->getElementPrecursor(666, LinearList::PRECURSOR_VALUE)); -$echo('返回线性表中某个元素的直接后继元素', $oll->getElementSubsequent(0, LinearList::SUBSEQUENT_KEY)); +$echo('返回线性表中某个元素的直接前驱元素', $oll->getElementPrecursor(666, LinearOrder::PRECURSOR_VALUE)); +$echo('返回线性表中某个元素的直接后继元素', $oll->getElementSubsequent(0, LinearOrder::SUBSEQUENT_KEY)); $echo('根据元素位置返回线性表中的某个元素', $oll->getElemForPos(2)); -$echo('根据下标或者元素值删除线性表中的某个元素', $oll->getDeleteElement('name', LinearList::DELETE_KEY)); -$echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", "qzone", LinearList::ASSIGN_KEY)); +$echo('根据下标或者元素值删除线性表中的某个元素', $oll->getDeleteElement('name', LinearOrder::DELETE_KEY)); +$echo('在指定位置插入一个新的结点', $oll->getInsertElement(3, "插入新节点", "qzone", LinearOrder::ASSIGN_KEY)); $echo('$oll->oll的内容 ', $oll->oll); \ No newline at end of file From 468d807ea0b55636aae1009d974425ca6ca4f77b Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 30 Sep 2017 18:01:27 +0800 Subject: [PATCH 059/127] fix: Follow the specifications :truck: --- README.md | 4 +- package/Structure/LinearChain.php | 175 +++++++++++++++++------------- 2 files changed, 100 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index fa77abe..84c52ee 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@

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

+> 每周最少一更,求出题,求虐待 +

php @@ -135,7 +137,7 @@ left|right 由数据元素之间的关系在计算机中有两种不同的表示方法——顺序表示和非顺序表示,从则导出两种储存方式,顺序储存结构和链式储存结构 - 顺序存储结构:用数据元素在存储器中的相对位置来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是连续的 -- 链式存储结构:在每一个数据元素中增加一个存放另一个元素地址的指针(pointer ),用该指针来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是否连续没有要求 +- 链式存储结构:在每一个数据元素中增加一个存放另一个元素地址的指针(pointer),用该指针来表示数据元素之间的逻辑结构(关系),数据元素存放的地址是否连续没有要求 数据的逻辑结构和物理结构是密不可分的两个方面,一个算法的设计取决于所选定的逻辑结构,而算法的实现依赖于所采用的存储结构 diff --git a/package/Structure/LinearChain.php b/package/Structure/LinearChain.php index 0e434e4..ba118b1 100644 --- a/package/Structure/LinearChain.php +++ b/package/Structure/LinearChain.php @@ -110,12 +110,15 @@ public function getIsEmpty() protected function getHeadCreateChain(array $arr) { $this->clearChain(); - foreach ($arr as $value) { + $iterator = $this->generator($arr); + $iterator->rewind(); + while ($iterator->valid()) { $node = new stdClass(); - $node->elem = $value; + $node->elem = $iterator->current(); $node->next = $this->next; $this->next = $node; $this->length++; + $iterator->next(); } return $this->next; } @@ -129,13 +132,16 @@ protected function getHeadCreateChain(array $arr) protected function getTailCreateChain(array $arr) { $this->clearChain(); - $q = $this; - foreach ($arr as $value) { + $self = $this; + $iterator = $this->generator($arr); + $iterator->rewind(); + while ($iterator->valid()) { $node = new stdClass(); - $node->elem = $value; - $node->next = $q->next; - $q->next = $node; - $q = $node; + $node->elem = $iterator->current(); + $node->next = $self->next; + $self->next = $node; + $self = $node; + $iterator->next(); $this->length++; } return $this->next; @@ -153,14 +159,14 @@ protected function getElemForPos($i) if ($i > $this->length || $i < 1) { return null; } - $j = 1; - $p = $this->next; - while ($j < $i) { - $q = $p->next; - $p = $q; - $j++; + $mark = 1; + $self = $this->next; + while ($mark < $i) { + $box = $self->next; + $self = $box; + $mark++; } - return $p; + return $self; } /** @@ -172,12 +178,12 @@ protected function getElemForPos($i) */ protected function getElemIsExist($value) { - $p = $this; - while ($p->next != null && strcmp($p->elem, $value) !== 0) { - $p = $p->next; + $self = $this; + while ($self->next != null && strcmp($self->elem, $value) !== 0) { + $self = $self->next; } - if (strcmp($p->elem, $value) === 0) { - return $p; + if (strcmp($self->elem, $value) === 0) { + return $self; } return null; } @@ -191,14 +197,14 @@ protected function getElemIsExist($value) */ protected function getElemPosition($value) { - $p = $this; - $j = 0; - while ($p->next != null && strcmp($p->elem, $value) !== 0) { - $p = $p->next; - $j++; + $self = $this; + $mark = 0; + while ($self->next != null && strcmp($self->elem, $value) !== 0) { + $self = $self->next; + $mark++; } - if (strcmp($p->elem, $value) === 0) { - return $j; + if (strcmp($self->elem, $value) === 0) { + return $mark; } return -1; } @@ -206,25 +212,25 @@ protected function getElemPosition($value) /** * 单链表的插入操作 * - * @param int $i 插入元素的位序,即在什么位置插入新的元素,从1开始 - * @param mixed $e 插入的新的元素值 + * @param int $key 插入元素的位序,即在什么位置插入新的元素,从1开始 + * @param mixed $value 插入的新的元素值 * @return boolean 插入成功返回true,失败返回false */ - protected function getInsertElem($i, $e) + protected function getInsertElem($key, $value) { - if ($i > $this->length || $i < 1) { + if ($key > $this->length || $key < 1) { return false; } - $j = 1; - $p = $this; - while ($p->next != null && $j < $i) { - $p = $p->next; - $j++; + $mark = 1; + $self = $this; + while ($self->next != null && $mark < $key) { + $self = $self->next; + $mark++; } - $q = new stdClass(); - $q->elem = $e; - $q->next = $p->next; - $p->next = $q; + $node = new stdClass(); + $node->elem = $value; + $node->next = $self->next; + $self->next = $node; $this->length++; return true; } @@ -240,41 +246,41 @@ protected function getAllElem() if ($this->getIsEmpty()) { return $result; } - $p = $this->next; - while ($p->next != null) { - $result[] = $p->elem; - $p = $p->next; + $self = $this->next; + while ($self->next != null) { + array_push($result, $self->elem); + $self = $self->next; } - $result[] = $p->elem; + array_push($result, $self->elem); return $result; } /** - * 删除单链中第$i个元素 + * 根据Key 删除单链中的元素 * - * @param int $i 元素位序 + * @param int $key 元素位序 * @return boolean 删除成功返回true,失败返回false */ - protected function getDeleteElem($i) + protected function getDeleteElem($key) { - $i = (int)$i; - if ($i > $this->length || $i < 1) { + $key = (int)$key; + if ($key > $this->length || $key < 1) { return false; } - $p = $this; - $j = 1; - while ($j < $i) { - $p = $p->next; - $j++; + $self = $this; + $mark = 1; + while ($mark < $key) { + $self = $self->next; + $mark++; } - $q = $p->next; - $p->next = $q->next; + $node = $self->next; + $self->next = $node->next; $this->length--; return true; } /** - * 删除单链表中值为$value的前$i($i>=1)个结点 + * 删除单链表中值为$value的前 $i($i>=1) 个结点 * * @param mixed mixed 待查找的值 * @param $i mixed 删除的次数,即删除查找到的前$i个 @@ -297,33 +303,45 @@ protected function getDeleteElemForValue($value, $i = 1) */ protected function getElemUnique() { - if (!$this->getIsEmpty()) { - $p = $this; - while ($p->next != null) { - $q = $p->next; - $ptr = $p; - while ($q->next != null) { - if (strcmp($p->elem, $q->elem) === 0) { - $ptr->next = $q->next; - $q->next = null; - unset($q->next); - $q = $ptr->next; - $this->length--; - } else { - $ptr = $q; - $q = $q->next; - } - } - if (strcmp($p->elem, $q->elem) === 0) { - $ptr->next = null; + if ($this->getIsEmpty()) { + return $this->getAllElem(); + } + $self = $this; + while ($self->next != null) { + $node = $self->next; + $ptr = $self; + while ($node->next != null) { + if (strcmp($self->elem, $node->elem) === 0) { + $ptr->next = $node->next; + $node->next = null; + unset($node->next); + $node = $ptr->next; $this->length--; + } else { + $ptr = $node; + $node = $node->next; } - $p = $p->next; } + if (strcmp($self->elem, $node->elem) === 0) { + $ptr->next = null; + $this->length--; + } + $self = $self->next; } return $this->getAllElem(); } + /** + * 迭代器生产 + * + * @param array $info + * @return \ArrayIterator + */ + protected function generator(array $info) + { + return (new ArrayObject($info))->getIterator(); + } + /** * 调试用请无视 * @@ -375,6 +393,7 @@ protected function preDispatch($isDebug = true) "Two", "Three", "Four", + "Five", ); $oll = new LinearChain(); From 2cdb309a7e795f34866a5ef88e9dedcf15080f5b Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 30 Sep 2017 18:03:52 +0800 Subject: [PATCH 060/127] docs: deliberate provocation :package: --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 84c52ee..e399005 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@

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

-> 每周最少一更,求出题,求虐待 -

php @@ -21,6 +19,7 @@

English 

+> 每周最少一更,求出题,求虐待 At least once a week, ask for problems and abuse ## 简易结构 From b5590918dc5bcfb4f92d90cbe21a816be0d03d98 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 30 Sep 2017 18:51:54 +0800 Subject: [PATCH 061/127] fix: Follow the specifications :ambulance: --- .travis.yml | 18 +----------------- package/Structure/LinearChain.php | 11 +++-------- 2 files changed, 4 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 14d23d6..c85eb70 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,20 +3,4 @@ sudo: false php: - 5.5 - 5.6 - - 7.0 - -services: - - mysql - -before_install: - - travis_retry composer self-update - -install: - - travis_retry composer install - -script: vendor/bin/phpunit - -matrix: - allow_failures: - - php: 5.6 - fast_finish: true \ No newline at end of file + - 7.0 \ No newline at end of file diff --git a/package/Structure/LinearChain.php b/package/Structure/LinearChain.php index ba118b1..909d335 100644 --- a/package/Structure/LinearChain.php +++ b/package/Structure/LinearChain.php @@ -26,11 +26,11 @@ * 当n=0时,称为空表。 * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 * ------------------------------------------------------------- - * [线性表顺序存储] + * [线性表单链存储] * ======= * 用一组任意的存储单元存储线性表中的数据元素,用这种方法存储的线性表简称线性链表。 * ------------------------------------------------------------- - * [顺序存储的线性表的特点] + * [单链存储的线性表的特点] * ======= * - 存储链表中结点的一组任意的存储单元可以是连续的,也可以是不连续的,甚至是零散分布在内存中的任意位置上 * - 链表中结点的逻辑顺序和物理顺序不一定相同 @@ -312,8 +312,7 @@ protected function getElemUnique() $ptr = $self; while ($node->next != null) { if (strcmp($self->elem, $node->elem) === 0) { - $ptr->next = $node->next; - $node->next = null; + $ptr->next = $node->next; unset($node->next); $node = $ptr->next; $this->length--; @@ -322,10 +321,6 @@ protected function getElemUnique() $node = $node->next; } } - if (strcmp($self->elem, $node->elem) === 0) { - $ptr->next = null; - $this->length--; - } $self = $self->next; } return $this->getAllElem(); From fa963e18679f97ee72d5357f997677c33b58bd8a Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 16 Oct 2017 11:41:15 +0800 Subject: [PATCH 062/127] feat: stack example finish :hammer: --- README.md | 1 + package/Structure/StackExample.php | 224 +++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 package/Structure/StackExample.php diff --git a/README.md b/README.md index e399005..2b057cb 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ │ │ └── QulickQuery.php 快速查找 │ │ │ ├── Structure 数据结构 + │ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) │ │ ├── LinearChain.php 线性表 单链存储 │ │ └── LinearOrder.php 线性表 顺序存储 │ │ diff --git a/package/Structure/StackExample.php b/package/Structure/StackExample.php new file mode 100644 index 0000000..a29cec4 --- /dev/null +++ b/package/Structure/StackExample.php @@ -0,0 +1,224 @@ + + * @date 2017/10/16 + * @license MIT + * ------------------------------------------------------------- + * [栈的定义] + * ======= + * 栈(Stack):是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。 + * 栈顶(Top):允许进行插入、删除操作的一端,又称为表尾。用栈顶指针(top)来指示栈顶元素。 + * 栈底(Bottom):是固定端,又称为表头。 + * 空栈:当表中没有元素时称为空栈。 + * [栈的实现方式] + * ======= + * - 硬堆栈:利用CPU中的某些寄存器组或类似的硬件或使用内存的特殊区域来实现。这类堆栈容量有限,但速度很快; + * - 软堆栈:这类堆栈主要在内存中实现。堆栈容量可以达到很大。在实现方式上,又有动态方式和静态方式两种 + * ------------------------------------------------------------- + * [定义] + * ======= + * 线性表(Linear List) :是由n(n≧0)个数据元素(结点) [a1,a2, …an] 组成的有限序列。数据元素是一个抽象的符号,其具体含义在不同的情况下一般不同。 + * 该序列中的所有结点具有相同的数据类型。其中数据元素的个数n称为线性表的长度。 + * 当n=0时,称为空表。 + * 当n>0时,将非空的线性表记作: (a1,a2,…an) a1称为线性表的第一个(首)结点,an称为线性表的最后一个(尾)结点。 + * ------------------------------------------------------------- + * [线性表顺序存储] + * ======= + * 把线性表的结点按逻辑顺序依次存放在一组地址连续的存储单元里,用这种方法存储的线性表简称线性表。 + * ------------------------------------------------------------- + * [顺序存储的线性表的特点] + * ======= + * - 线性表的逻辑顺序与物理顺序一致; + * - 数据元素之间的关系是以元素在计算机内“物理位置相邻”来体现。 + * ------------------------------------------------------------- + * @param array + */ +class StackExample +{ + /** + * @var null 栈元素 + */ + protected $elem; + /** + * @var null 下一个节点 + */ + protected $next; + /** + * @var int 栈长度 + */ + protected $length; + + /** + * 初始化栈 + * StackExample constructor. + */ + public function __construct() + { + $this->elem = $this->next = null; + $this->length = 0; + } + + /** + * 判断栈是否空栈 + * + * @return boolean 如果为空栈返回true,否则返回false + */ + protected function getIsEmpty() + { + return $this->elem ? false : true; + } + + /** + * 将所有元素出栈 + * + * @return array 返回所有栈内元素 + */ + protected function getAllPopStack() + { + $result = array (); + if ($this->getIsEmpty()) { + return $result; + } + while ($this->elem != null) { + $result[] = $this->elem->elem; + $this->elem = $this->elem->next; + } + $this->length = 0; + return $result; + } + + /** + * 返回栈内元素个数 + * + * @return int + */ + protected function getLength() + { + return $this->length; + } + + /** + * 元素进栈 + * + * @param mixed $element 进栈元素值 + * @return void + **/ + protected function setPushStack($element) + { + $stack = new stdClass(); + $stack->elem = $element; + $stack->next = $this->elem; + $this->elem = &$stack; + $this->length++; + } + + /** + * 元素出栈 + * + * @return boolean 出栈成功返回true,否则返回false + **/ + protected function getPopStack() + { + if ($this->getIsEmpty()) { + return false; + } + $node = $this->elem; + $this->elem = $node->next; + $this->length--; + } + + /** + * 仅返回栈内所有元素 + * + * @return array 栈内所有元素组成的一个数组 + */ + protected function getAllElem() + { + $result = array (); + if ($this->getIsEmpty()) { + return $result; + } + $node = $this->elem; + while ($node != null) { + $result[] = $node->elem; + $node = $node->next; + } + return $result; + } + + /** + * 返回栈内某个元素的个数 + * + * @param mixed $elem 待查找的元素的值 + * @return int + **/ + protected function getCountForElem($elem) + { + $result = $this->getAllElem(); + $count = 0; + foreach ($result as $value) { + if ($elem === $value) { + $count++; + } + } + return $count; + } + + /** + * 调试用请无视 + * + * @param $name + * @param $arguments + * @return mixed + */ + public function __call($name, $arguments) + { + $this->preDispatch(); // 调试用,请无视 + return call_user_func_array(array ($this, $name), $arguments); + } + + /** + * 调试用 + * + * @param bool $isDebug + * @return bool + */ + protected function preDispatch($isDebug = true) + { + if (!$isDebug) { + return false; + } + $debug = debug_backtrace()[1]; + $reflection = new ReflectionMethod($this, $debug['args'][0]); + $args = ''; + if (isset($debug['args'][1])) { + foreach ($debug['args'][1] as &$value) { + if (is_array($value)) { + $args .= json_encode($debug['args'][1]) . ', '; + } else { + $args .= $value . ', '; + } + } + } + $args = trim($args, ', '); + echo "\t" . $reflection->getDocComment() . PHP_EOL; + echo "\t{$debug['args'][0]}({$args})\n" . PHP_EOL; + } +} + +$echo = function ($str, $action) { + echo $str . "\t->\t" . var_export($action, true) . PHP_EOL; + echo "--------------------------- " . PHP_EOL; +}; + +$stack = new StackExample(); +$stack->setPushStack('First'); +$stack->setPushStack('Second'); +$echo('返回栈内所有元素', $stack->getAllElem()); +$stack->setPushStack('Third'); +$echo('返回栈内所有元素', $stack->getAllElem()); +$stack->getPopStack(); +$echo('返回栈内所有元素', $stack->getAllElem()); From ceaf540326b55453e9b4c84b086626ab9e17347f Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Mon, 16 Oct 2017 12:23:05 +0800 Subject: [PATCH 063/127] feat: system the switch tools :bug: --- README.md | 3 + package/Structure/StackExample.php | 16 ++--- package/Tools/SystemSwitch.php | 100 +++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 8 deletions(-) create mode 100644 package/Tools/SystemSwitch.php diff --git a/README.md b/README.md index 2b057cb..061fc85 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,9 @@ │ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) │ │ ├── LinearChain.php 线性表 单链存储 │ │ └── LinearOrder.php 线性表 顺序存储 + │ │ + │ ├── Tools 小工具集 + │ │ └── SystemSwitch.php 堆栈实现进制转换 │ │ │ └── Other 其他 │ ├── MonkeyKing.php 猴子选大王 diff --git a/package/Structure/StackExample.php b/package/Structure/StackExample.php index a29cec4..a8b4f30 100644 --- a/package/Structure/StackExample.php +++ b/package/Structure/StackExample.php @@ -214,11 +214,11 @@ protected function preDispatch($isDebug = true) echo "--------------------------- " . PHP_EOL; }; -$stack = new StackExample(); -$stack->setPushStack('First'); -$stack->setPushStack('Second'); -$echo('返回栈内所有元素', $stack->getAllElem()); -$stack->setPushStack('Third'); -$echo('返回栈内所有元素', $stack->getAllElem()); -$stack->getPopStack(); -$echo('返回栈内所有元素', $stack->getAllElem()); +//$stack = new StackExample(); +//$stack->setPushStack('First'); +//$stack->setPushStack('Second'); +//$echo('返回栈内所有元素', $stack->getAllElem()); +//$stack->setPushStack('Third'); +//$echo('返回栈内所有元素', $stack->getAllElem()); +//$stack->getPopStack(); +//$echo('返回栈内所有元素', $stack->getAllElem()); diff --git a/package/Tools/SystemSwitch.php b/package/Tools/SystemSwitch.php new file mode 100644 index 0000000..135419e --- /dev/null +++ b/package/Tools/SystemSwitch.php @@ -0,0 +1,100 @@ + + * @date 2017/10/16 + * @license MIT + * ------------------------------------------------------------- + * 十进制整数转换为二、八、十六进制整数 n = (n div d) * d + n mod d + * ------------------------------------------------------------- + * @param array + */ +class SystemSwitch +{ + /** + * @var array + */ + protected $systemGather; + + /** + * @var int + */ + protected $input; + + /** + * @var mixed + */ + protected $output; + + /** + * SystemSwitch constructor. + * + * @param $input + * @param $output + */ + public function __construct($input, $output) + { + $this->systemGather = array (2, 8, 16); + $this->input = $input; + $this->output = $output; + } + + public function run() + { + $before = $this->input; + $stack = new StackExample(); + while ($this->input != 0) { + $mod = $this->input % $this->output; + $stack->setPushStack($mod); + $this->input = (int)($this->input - $mod) / $this->output; + } + $output = ''; + if ($this->output == 16) { + $output .= '0x'; + } else if ($this->output == 8) { + $output .= '0'; + } + + foreach ($stack->getAllPopStack() as $value) { + if ($this->output == 16) { + switch ($value) { + case 10: + $value = 'A'; + break; + case 11: + $value = 'B'; + break; + case 12: + $value = 'C'; + break; + case 13: + $value = 'D'; + break; + case 14: + $value = 'E'; + break; + case 15: + $value = 'F'; + break; + } + } + $output .= $value; + } + // 因为输出语句会自动将整型的数转换为10进制输出 + // 也即如果转换后的结果为0xff,直接将0xff输出会得到255,所以返回一数组 + return array ( + 'before' => $before, // 转换之前 + 'after' => intval($output, $this->output), // 转换后的整型数(整型) + 'string' => $output // 转换后的整型数的字符串表示(字符串型) + ); + } +} + +// load the stack +define("DS", DIRECTORY_SEPARATOR); +require_once dirname(__DIR__) . DS . 'Structure' . DS . 'StackExample.php'; +$systemObj = new SystemSwitch(6, 16); +$result = $systemObj->run(); +var_dump($result); \ No newline at end of file From 72799be400b1fa833e1a30214b78be8bdbe6b2e6 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Thu, 19 Oct 2017 19:30:57 +0800 Subject: [PATCH 064/127] feat: add heap sort :bulb: --- README.md | 16 +++++- package/Sort/HeapSort.php | 111 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 package/Sort/HeapSort.php diff --git a/README.md b/README.md index 061fc85..fc17829 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,9 @@ ├──Package │ ├── Sort 排序篇 │ │ ├── BubbleSort.php 冒泡排序 + │ │ ├── HeapSort.php 堆排序 大根堆 + │ │ ├── MBaseSort.php 基数排序 MSD + │ │ ├── LBaseSort.php 基数排序 LSD │ │ ├── QuickSort.php 快速排序 │ │ ├── ShellSort.php 希尔排序 │ │ ├── MergeSort.php 归并排序 @@ -47,7 +50,7 @@ │ │ └── SystemSwitch.php 堆栈实现进制转换 │ │ │ └── Other 其他 - │ ├── MonkeyKing.php 猴子选大王 + │ ├── MonkeyKing.php 约瑟夫环 │ ├── DynamicProgramming.php 动态规划 │ ├── Fibonacci.php 斐波那契数列 │ ├── StealingApples.php 偷苹果求余 @@ -64,6 +67,17 @@ ## 要做什么? 记录自己理解算法,数据结构的过程,尽可能的简单全面以及详细,让算法学习运用灵活自如,加油(ง •̀_•́)ง + +## 当然 + 用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这觉不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 + +## 什么是算法? +直白地说,算法就是任何明确定义的计算过程,它接收一些值或集合作为输入,并产生一些值或集合作为输出。这样,算法就是将输入转换为输出的一系列计算过程。来源:Thomas H. Cormen, Chales E. Leiserson (2009), 《算法导论第三版》。 + +简而言之,我们可以说算法就是用来解决一个特定任务的一系列步骤(是的,不止计算机在使用算法,人类也同样如此)。目前,一个有效的算法应该含有三个重要特性: +- 它必须是有限的:如果你设计的算法永无休止地尝试解决问题,那么它是无用的。 +- 它必须具备明确定义的指令:算法的每一步都必须准确定义,在任何场景下指令都应当没有歧义。 +- 它必须是有效的:一个算法被设计用以解决某个问题,那么它就应当能解决这个问题,并且仅仅使用纸和笔就能证明该算法是收敛的。 ## 对数 log10100 相当于问"降多少个10相乘的结果为100",答案当然是2个了 diff --git a/package/Sort/HeapSort.php b/package/Sort/HeapSort.php new file mode 100644 index 0000000..0523a70 --- /dev/null +++ b/package/Sort/HeapSort.php @@ -0,0 +1,111 @@ + + * @date 2017/10/9 + * @license MIT + * ------------------------------------------------------------- + * 思路分析:堆排序利用了大根堆堆顶记录的关键字最大(或最小)这一特征 + * ------------------------------------------------------------- + * 堆排序(HeapSort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,它是选择排序的一种。 + * 可以利用数组的特点快速定位指定索引的元素。堆分为大根堆和小根堆,是完全二叉树。 + * 大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆, + * 因为根据大根堆的要求可知,最大的值一定在堆顶。 + */ +class HeapSort +{ + /** + * @var int + */ + protected $count; + + /** + * @var array + */ + protected $data; + + /** + * HeapSort constructor. + * + * @param array $data + */ + public function __construct(array $data) + { + $this->count = count($data); + $this->data = $data; + } + + /** + * Action + * + * @return array + */ + public function run() + { + $this->createHeap(); + while ($this->count > 0) { + /* 这是一个大顶堆 , 所以堆顶的节点必须是最大的 + 根据此特点 , 每次都将堆顶数据移到最后一位 + 然后对剩余数据节点再次建造堆就可以 */ + $this->swap($this->data[0], $this->data[--$this->count]); + $this->buildHeap($this->data, 0, $this->count); + } + return $this->data; + } + + /** + * 创建一个堆 + */ + public function createHeap() + { + $i = ceil($this->count / 2) + 1; + while ($i--) { + $this->buildHeap($this->data, $i, $this->count); + } + } + + /** + * 从 数组 的第 $i 个节点开始至 数组长度为0 结束 , 递归的将其 ( 包括其子节点 ) 转化为一个小顶堆 + * + * @param $data + * @param $i + * @param $count + */ + public function buildHeap(array &$data, $i, $count) + { + if (false === $i < $count) { + return; + } + // 获取左 / 右节点 + $right = ($left = 2 * $i + 1) + 1; + $max = $i; + // 如果左子节点大于当前节点 , 那么记录左节点键名 + if ($left < $count && $data[$i] < $data[$left]) { + $max = $left; + } + // 如果右节点大于刚刚记录的 $max , 那么再次交换 + if ($right < $count && $data[$max] < $data[$right]) { + $max = $right; + } + if ($max !== $i && $max < $count) { + $this->swap($data[$i], $data[$max]); + $this->buildHeap($data, $max, $count); + } + } + + /** + * 交换空间 + * + * @param $left + * @param $right + */ + public function swap(&$left, &$right) + { + list($left, $right) = array ($right, $left); + } +} + +$array = array (4, 21, 41, 2, 53, 1, 213, 31, 21, 423, 56); +$result = (new HeapSort($array))->run(); +var_dump($result); From b6f2e8df19726314e99baac1b7afe9c20eb1dcba Mon Sep 17 00:00:00 2001 From: qii404 Date: Mon, 6 Nov 2017 18:56:16 -0600 Subject: [PATCH 065/127] =?UTF-8?q?=E5=BC=BA=E8=BF=AB=E7=97=87=E8=A1=A8?= =?UTF-8?q?=E7=A4=BA=E4=B8=8D=E8=83=BD=E5=BF=8D...?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 恩...... --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fc17829..5139550 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ - 它必须是有效的:一个算法被设计用以解决某个问题,那么它就应当能解决这个问题,并且仅仅使用纸和笔就能证明该算法是收敛的。 ## 对数 -log10100 相当于问"降多少个10相乘的结果为100",答案当然是2个了 +log10100 相当于问"将多少个10相乘的结果为100",答案当然是2个了 因此log10100=2,即对数运算是幂运算的逆运算 left|right @@ -92,7 +92,7 @@ left|right 战斗吧!少年 ## 运行时间 -以二分查找为例,使用它可节省多少时间呢?简单查找诸葛地检查数字,如果列表包含100个数字,最多需要猜100次。 +以二分查找为例,使用它可节省多少时间呢?简单查找逐个地检查数字,如果列表包含100个数字,最多需要猜100次。 换而言之最多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 最多需要7次,如果列表包含40亿个数字,最多需猜32次,而分查找的运行时间为对数时间 `O(log)` From 19b2e466f66d326dd42567a5c5b6bc85ce1665ee Mon Sep 17 00:00:00 2001 From: chenishr Date: Mon, 13 Nov 2017 00:54:50 +0800 Subject: [PATCH 066/127] =?UTF-8?q?=E9=81=BF=E5=85=8D=E6=AF=8F=E6=AC=A1?= =?UTF-8?q?=E5=AF=B9=E6=95=B0=E7=BB=84=E9=87=8D=E6=96=B0=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/PokerGames.php | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index 850f55d..4daa248 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -11,13 +11,10 @@ $card_num = 54;//牌数 function washCard($card_num) { - $cards = $tmp = array (); - $tmp = range(0, $card_num); - for ($i = 0; $i < $card_num; $i++) { - $index = rand(0, $card_num - $i - 1); - $cards[$i] = $tmp[$index]; - unset($tmp[$index]); - $tmp = array_values($tmp); + $cards = range(1, $card_num); + for ($i = $card_num - 1; $i > 0; $i--) { + $rnd = rand(0,$i - 1); + list($cards[$rnd],$cards[$i]) = array($cards[$i],$cards[$rnd]); } return $cards; } From 4355c81f48ffb872cf84fb8354139ebf4fe9007a Mon Sep 17 00:00:00 2001 From: Marco Date: Tue, 19 Dec 2017 11:20:22 +0800 Subject: [PATCH 067/127] Set theme jekyll-theme-cayman --- _config.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 _config.yml diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..c419263 --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-cayman \ No newline at end of file From 83d847d7a9334a36dcebca0679a981089e99abc9 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Tue, 19 Dec 2017 13:34:26 +0800 Subject: [PATCH 068/127] feat: ShuttleSort :lock: --- README.md | 1 + package/Other/BidirectionalQueue.php | 2 +- package/Query/BinaryQuery.php | 5 +- package/Query/InsertQuery.php | 12 +++-- package/Query/QulickQuery.php | 5 ++ package/Sort/BubbleSort.php | 44 +++--------------- package/Sort/InsertSort.php | 8 +++- package/Sort/QuickSort.php | 46 +++++++++++++++---- package/Sort/SelectSort.php | 8 +++- package/Sort/ShellSort.php | 5 ++ package/Sort/ShuttleSort.php | 68 ++++++++++++++++++++++++++++ package/Structure/KitchenQueue.php | 52 +++++++++++++++++++++ 12 files changed, 202 insertions(+), 54 deletions(-) create mode 100644 package/Sort/ShuttleSort.php create mode 100644 package/Structure/KitchenQueue.php diff --git a/README.md b/README.md index 5139550..6d0250f 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ │ │ ├── MBaseSort.php 基数排序 MSD │ │ ├── LBaseSort.php 基数排序 LSD │ │ ├── QuickSort.php 快速排序 + │ │ ├── ShuttleSort.php 飞梭排序 │ │ ├── ShellSort.php 希尔排序 │ │ ├── MergeSort.php 归并排序 │ │ ├── InsertSort.php 插入排序 diff --git a/package/Other/BidirectionalQueue.php b/package/Other/BidirectionalQueue.php index 4bbd921..b644ca2 100644 --- a/package/Other/BidirectionalQueue.php +++ b/package/Other/BidirectionalQueue.php @@ -9,7 +9,7 @@ * ------------------------------------------------------------- * 思路分析: 考察PHP几个内置数组的函数 * ------------------------------------------------------------- - *双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素 + * 双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素 * @param $n * @return int */ diff --git a/package/Query/BinaryQuery.php b/package/Query/BinaryQuery.php index 4994862..5b5051c 100644 --- a/package/Query/BinaryQuery.php +++ b/package/Query/BinaryQuery.php @@ -11,8 +11,11 @@ * 若比中间值大则将首值替换为中间位置下一个位置,继续第一步的操作; * 若比中间值小,则将尾值替换为中间位置上一个位置,继续第一步操作 * 重复第二步操作直至找出目标数字 - * + */ + +/** * 非递归版 二分查找 + * * @param array $container * @param $search * @return int|string diff --git a/package/Query/InsertQuery.php b/package/Query/InsertQuery.php index f331409..f244fd8 100644 --- a/package/Query/InsertQuery.php +++ b/package/Query/InsertQuery.php @@ -12,9 +12,14 @@ * 在英文词典里查找“apple”,你下意识里翻开词典是翻前面的书页还是后面的书页呢?如果再查“zoo”,你又会怎么查? * 显然你不会从词典中间开始查起,而是有一定目的地往前或往后翻。 * - * @param $container - * @param $num - * @return int + */ + +/** + * insertQuery + * + * @param array $container + * @param $num + * @return bool|float|int */ function insertQuery(array $container, $num) { @@ -47,3 +52,4 @@ function insertQuery(array $container, $num) } echo insertQuery([4, 5, 7, 8, 9, 10, 8], 8); +// 6 \ No newline at end of file diff --git a/package/Query/QulickQuery.php b/package/Query/QulickQuery.php index 6c8fb4c..cbbde35 100644 --- a/package/Query/QulickQuery.php +++ b/package/Query/QulickQuery.php @@ -11,6 +11,11 @@ * ------------------------------------------------------------- * 重复第二步操作直至找出目标数字 * + */ + +/** + * QulickQuery + * * @param $array * @param $k * @param int $low diff --git a/package/Sort/BubbleSort.php b/package/Sort/BubbleSort.php index bb49948..d382668 100644 --- a/package/Sort/BubbleSort.php +++ b/package/Sort/BubbleSort.php @@ -12,7 +12,12 @@ * 然后再从底至上地这样升,循环直至十个气泡大小有序。 * 在冒泡排序中,最重要的思想是两两比较,将两者较少的升上去 * - * @param array $container + */ + +/** + * BubbleSort + * + * @param array $container * @return array */ function BubbleSort(array $container) @@ -55,39 +60,4 @@ function BubbleSort(array $container) [9] => int(423) } - */ - -// +---------------------------------------------------------------------- -// | 方法二 -// +---------------------------------------------------------------------- -function BubbleSortV2(array $container) -{ - $len = count($container); - // 也可以用foreach - for ($i = 0; $i < $len - 1; $i++) { - for ($j = $i + 1; $j < $len; $j++) { - if ($container[$i] > $container[$j]) { - list($container[$i], $container[$j]) = array($container[$j], $container[$i]); - } - } - } - - return $container; -} - -print_r(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); -/* -Array -( - [0] => 1 - [1] => 2 - [2] => 4 - [3] => 21 - [4] => 21 - [5] => 31 - [6] => 41 - [7] => 53 - [8] => 213 - [9] => 423 -) - */ + */ \ No newline at end of file diff --git a/package/Sort/InsertSort.php b/package/Sort/InsertSort.php index 58b8ff1..01b03da 100644 --- a/package/Sort/InsertSort.php +++ b/package/Sort/InsertSort.php @@ -14,10 +14,14 @@ * 但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。 * 在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。 * - * @param $container - * @return mixed */ +/** + * InsertSort + * + * @param array $container + * @return array + */ function InsertSort(array $container) { $count = count($container); diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index 057effc..ff38a68 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -10,26 +10,56 @@ * 重新排序数列,所有元素比基准值小的摆放在基准前面 * 所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。 * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 + */ + +/** + * QulickSort * - * @param array $container - * @return mixed + * @param array $container + * @return array */ -function QulickSort( array $container ){ - $count = count( $container ); - if( $count <= 1 ) { +function QulickSort(array $container) +{ + $count = count($container); + if ($count <= 1) { return $container; } $left = $right = []; for ($i = 1; $i < $count; $i++) { if ($container[$i] < $container[0]) { - $left[] = $container[$i]; + $left[] = $container[$i]; } else { $right[] = $container[$i]; } } $left = QulickSort($left); $right = QulickSort($right); - return array_merge($left,[$container[0]],$right); + return array_merge($left, [$container[0]], $right); +} + +var_dump(QulickSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); +/** + * array(10) { +[0] => +int(1) +[1] => +int(2) +[2] => +int(4) +[3] => +int(21) +[4] => +int(21) +[5] => +int(31) +[6] => +int(41) +[7] => +int(53) +[8] => +int(213) +[9] => +int(423) } -var_dump( QulickSort([4,21,41,2,53,1,213,31,21,423]) ); \ No newline at end of file + */ \ No newline at end of file diff --git a/package/Sort/SelectSort.php b/package/Sort/SelectSort.php index 0c8fedf..f218293 100644 --- a/package/Sort/SelectSort.php +++ b/package/Sort/SelectSort.php @@ -10,9 +10,13 @@ * ------------------------------------------------------------- * 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 * 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。 + */ + +/** + * SelectSort * - * @param $container - * @return mixed + * @param array $container + * @return array */ function SelectSort(array $container) { diff --git a/package/Sort/ShellSort.php b/package/Sort/ShellSort.php index 45ba10a..4fc7db0 100644 --- a/package/Sort/ShellSort.php +++ b/package/Sort/ShellSort.php @@ -9,6 +9,11 @@ * ------------------------------------------------------------- * 希尔排序中一个常数因子n,原数组被分成各个小组,每个小组由h个元素组成,很可能会有多余的元素。 * 当然每次循环的时候,h也是递减的(h=h/n)。第一次循环就是从下标为h开始。希尔排序的一个思想就是,分成小组去排序。 + */ + +/** + * ShellSort + * * @param array $container * @return array */ diff --git a/package/Sort/ShuttleSort.php b/package/Sort/ShuttleSort.php new file mode 100644 index 0000000..b4200ac --- /dev/null +++ b/package/Sort/ShuttleSort.php @@ -0,0 +1,68 @@ + + * @date 2017/12/19 + * @version 1.0 + * ------------------------------------------------------------- + * 思路分析:飞梭排序是冒泡排序的轻微变形。不同的地方在于,飞梭排序是从低到高然后从高到低来回排序,而冒泡排序则仅从低到高去比较序列里的每个元素。 + * ------------------------------------------------------------- + * 先对数组从左到右进行冒泡排序(升序),则最大的元素去到最右端 + * 再对数组从右到左进行冒泡排序(降序),则最小的元素去到最左端 + * 以此类推,依次改变冒泡的方向,并不断缩小未排序元素的范围,直到最后一个元素结束 + */ + + +/** + * ShuttleSort + * + * @param array $data + * @return array + */ +function ShuttleSort(array $data) +{ + /** + * 替换方法 + * + * @param array $data + * @param $i + * @param $j + * @return array + */ + $swap = function (array &$data, $i, $j) { + $temp = $data[$i]; + $data[$i] = $data[$j]; + $data[$j] = $temp; + return $data; + }; + + $count = count($data); + $left = 0; + $right = $count - 1; + + while ($left < $right) { + // 从左到右 + $lastRight = 0; + for ($i = $left; $i < $right; $i++) { + if ($data[$i] > $data[$i + 1]) { + $swap($data, $i, 1 + $i); + $lastRight = $i; + } + } + $right = $lastRight; + // 从右到左 + $lastLeft = 0; + for ($j = $right; $left < $j; $j--) { + if ($data[$j - 1] > $data[$j]) { + $swap($data, $j - 1, $j); + $lastLeft = $j; + } + } + $left = $lastLeft; + } + return $data; +} + +var_dump(ShuttleSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); diff --git a/package/Structure/KitchenQueue.php b/package/Structure/KitchenQueue.php new file mode 100644 index 0000000..27a4a73 --- /dev/null +++ b/package/Structure/KitchenQueue.php @@ -0,0 +1,52 @@ + + * @date 2017/12/3 + * @version 1.0 + * @license QiHoo + */ +class KitchenQueue +{ + /** + * @var \stdClass $cooking + */ + protected $cooking; + + /** + * 服务员 + * + * @param $dishes + */ + public function waiter($dishes) + { + $node = new \stdClass(); + $node->element = $dishes; + $node->next = $this->cooking; + $this->cooking = $node; + } + + /** + * 厨师 + * + * @return \stdClass + */ + public function kitchen() + { + return $this->cooking; + } +} + +$kitchen = new KitchenQueue(); +$kitchen->waiter("Qin Jiao Rou Si"); +$kitchen->waiter("Ma Po Dou Fu"); +$kitchen->waiter("Fu Qi Fei Pian"); +$kitchen->waiter("Kou Shui Ji"); +var_dump($kitchen->kichen()); From a5014cc86662b8cc8bec4d357efdc1de556c37a8 Mon Sep 17 00:00:00 2001 From: LXZ Date: Tue, 9 Jan 2018 11:47:52 +0800 Subject: [PATCH 069/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=8A=BD=E5=A5=96?= =?UTF-8?q?=E5=8C=BA=E9=97=B4=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/Interval.php | 69 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 package/Other/Interval.php diff --git a/package/Other/Interval.php b/package/Other/Interval.php new file mode 100644 index 0000000..497f3e4 --- /dev/null +++ b/package/Other/Interval.php @@ -0,0 +1,69 @@ + $val) { + $arr[$key] = $val['v']; + } + $proSum = array_sum($arr); // 计算总权重 + $randNum = mt_rand(1, $proSum); + $d1 = 0; + $d2 = 0; + for ($i = 0; $i < count($arr); $i++) { + $d2 += $arr[$i]; + if ($i == 0) { + $d1 = 0; + } else { + $d1 += $arr[$i - 1]; + } + if ($randNum >= $d1 && $randNum <= $d2) { + $result = $proArr[$i]; + } + } + unset ($arr); + return $result; +} + +/** + * 使用较多的为这个方法 + */ +function get_rand1($proArr) +{ + $result = array(); + foreach ($proArr as $key => $val) { + $arr[$key] = $val['v']; + } + // 概率数组的总概率 + $proSum = array_sum($arr); + asort($arr); + // 概率数组循环 + foreach ($arr as $k => $v) { + $randNum = mt_rand(1, $proSum); + if ($randNum <= $v) { + $result = $proArr[$k]; + break; + } else { + $proSum -= $v; + } + } + return $result; +} + +$arr = array( + array('id' => 1, 'name' => '特等奖', 'v' => 1), + array('id' => 2, 'name' => '一等奖', 'v' => 5), + array('id' => 3, 'name' => '二等奖', 'v' => 10), + array('id' => 4, 'name' => '三等奖', 'v' => 12), + array('id' => 5, 'name' => '四等奖', 'v' => 22), + array('id' => 6, 'name' => '没中奖', 'v' => 50) +); + +var_dump(get_rand($arr)); + From 925650f3a4a1bcee30366e17e2e0798f3e040b50 Mon Sep 17 00:00:00 2001 From: LXZ Date: Tue, 9 Jan 2018 11:56:26 +0800 Subject: [PATCH 070/127] update --- README-EN.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README-EN.md b/README-EN.md index 7cfdcce..5e1f88e 100644 --- a/README-EN.md +++ b/README-EN.md @@ -47,6 +47,7 @@ │ ├── ColorBricks.php │ ├── GetCattle.php │ ├── OnlyNumbers.php + │ ├── Interval.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index 6d0250f..53ee1ff 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ │ ├── GetCattle.php 牛年求牛 │ ├── OnlyNumbers.php 求唯一数 │ ├── PokerGames.php 洗扑克牌 + │ ├── Interval.php 抽奖区间算法 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE From a4331d941c4586b359d4409e9d8296a0d22dfae2 Mon Sep 17 00:00:00 2001 From: LXZ Date: Tue, 9 Jan 2018 13:00:33 +0800 Subject: [PATCH 071/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AF=B9=E7=A7=B0?= =?UTF-8?q?=E5=8A=A0=E5=AF=86=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/Encryption.php | 45 ++++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 package/Other/Encryption.php diff --git a/README-EN.md b/README-EN.md index 5e1f88e..9a7349b 100644 --- a/README-EN.md +++ b/README-EN.md @@ -48,6 +48,7 @@ │ ├── GetCattle.php │ ├── OnlyNumbers.php │ ├── Interval.php + │ ├── Encryption.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index 53ee1ff..f143836 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ │ ├── OnlyNumbers.php 求唯一数 │ ├── PokerGames.php 洗扑克牌 │ ├── Interval.php 抽奖区间算法 + │ ├── Encryption.php 对称加密算法 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/Encryption.php b/package/Other/Encryption.php new file mode 100644 index 0000000..c8e3200 --- /dev/null +++ b/package/Other/Encryption.php @@ -0,0 +1,45 @@ + Date: Thu, 11 Jan 2018 12:59:29 +0800 Subject: [PATCH 072/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=9A=82=E8=9A=81?= =?UTF-8?q?=E7=88=AC=E6=9D=86=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/AntsClimb.php | 97 +++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+) create mode 100644 package/Other/AntsClimb.php diff --git a/README-EN.md b/README-EN.md index 5e1f88e..460a4a6 100644 --- a/README-EN.md +++ b/README-EN.md @@ -48,6 +48,7 @@ │ ├── GetCattle.php │ ├── OnlyNumbers.php │ ├── Interval.php + │ ├── AntsClimb.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index 53ee1ff..4cbf608 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,7 @@ │ ├── OnlyNumbers.php 求唯一数 │ ├── PokerGames.php 洗扑克牌 │ ├── Interval.php 抽奖区间算法 + │ ├── AntsClimb.php 蚂蚁爬杆算法 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/AntsClimb.php b/package/Other/AntsClimb.php new file mode 100644 index 0000000..5900341 --- /dev/null +++ b/package/Other/AntsClimb.php @@ -0,0 +1,97 @@ + $i) { + return $directionArr; + } + if (0 == $directionArr[$i]) { + $directionArr[$i] = 1; + return $directionArr; + } + $directionArr[$i] = 0; + return add2($directionArr, $count, $i - 1); +} + + +function path($positionArr) +{ + // 生成测试路径 + $pathCalculate = array(); + $count = count($positionArr); + $directionArr = array_fill(0, $count, 0); + //print_r($directionArr);exit; + + // 朝向 + $end = str_repeat('1', $count); + while (true) { + $path = implode('', $directionArr); + //$pathArray = array_combine($positionArr, $directionArr); + $total = calculate($positionArr, $directionArr); + $pathCalculate['路径:' . $path] = $total; + if ($end == $path) { // 遍历完成 + break; + } + $directionArr = add2($directionArr, $count, $count - 1); + } + return $pathCalculate; +} + +function calculate($positionArr, $directionArr) +{ + //print_r($positionArr); + //print_r($directionArr); + $total = 0; + // 总用时 + $length = 27; + // 木杆长度 + while ($positionArr) { + $total++; // 步增耗时 + $nextArr = array(); // 下一步位置 + foreach ($positionArr as $key => $value) { + if (0 == $directionArr[$key]) { + $next = $value - 1; // 向0方向走一步 + } else { + $next = $value + 1; // 向1方向走一步 + } + if (0 == $next) { // 在0方向走出 + continue; + } + if ($length == $next) { // 在1方向走出 + continue; + } + $nextArr[$key] = $next; + } + $positionArr = $nextArr;// 将$positionArr置为临时被查找数组 + + foreach ($nextArr as $key => $value) { + $findArr = array_keys($positionArr, $value); + if (count($findArr) < 2) { + // 没有重合的位置 + continue; + } + foreach ($findArr as $findIndex) { + $directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1; + // 反向处理 + unset($positionArr[$findIndex]); + // 防止重复查找计算 + } + } + $positionArr = $nextArr; + // 将$positionArr置为下一步结果数组 + } + return $total; +} + +$positionArr = array(3, 7, 11, 17, 23); +$pathCalculate = path($positionArr); +echo '

计算-';
+print_r($pathCalculate);
+echo '排序-';
+asort($pathCalculate);
+print_r($pathCalculate);
\ No newline at end of file

From 8edf11a6ac7e5311d3cc4248f780af72a7626eeb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E5=8D=97=E4=B8=9E?= 
Date: Sat, 13 Jan 2018 23:19:15 +0800
Subject: [PATCH 073/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=BF=B7=E5=AE=AB?=
 =?UTF-8?q?=E5=AF=BB=E5=9D=80=E7=AE=97=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .idea/vcs.xml          |   6 +++
 package/Other/Maze.php | 108 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 114 insertions(+)
 create mode 100644 .idea/vcs.xml
 create mode 100644 package/Other/Maze.php

diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+  
+    
+  
+
\ No newline at end of file
diff --git a/package/Other/Maze.php b/package/Other/Maze.php
new file mode 100644
index 0000000..b33a0cb
--- /dev/null
+++ b/package/Other/Maze.php
@@ -0,0 +1,108 @@
+ 0) {
+    $tmpArr = array();
+    foreach ($_posArr as $val) {
+        $nx = $x + $val[0];
+        $ny = $y + $val[1];
+        if (isset($maze[$nx][$ny])) {//未破墙过的格子
+            $tmpArr[] = array($nx, $ny);
+        }
+    }
+    if ($tmpArr) {//有未破墙的格子,随机出一个,破墙
+        list($nx, $ny) = $tmpArr[array_rand($tmpArr)];
+        $maze2[$nx][$ny] = $maze[$nx][$ny];
+        if (empty($maze2[$x][$y])) $maze2[$x][$y] = $maze[$x][$y];
+        $pos = array($nx - $x, $ny - $y);
+        foreach ($_posArr as $key => $val) {//循环四个方向,找出需要破的墙
+            if ($pos == $val) {
+                $maze2[$x][$y][$key] = 0;//原格子破墙
+                $maze2[$nx][$ny][($key + 2) % 4] = 0;//新格子破墙
+            }
+        }
+        //设置新的当前格后返回继续while循环
+        $x = $nx;
+        $y = $ny;
+        $mazeOrder[] = array($x, $y);
+        unset($maze[$x][$y]);//去掉已破墙的格子
+        if (empty($maze[$x])) unset($maze[$x]);
+    } else {//当前xy周围不存在未破墙的格子,返回上一个格子继续破墙
+        array_pop($mazeOrder);
+        if ($mazeOrder) list($x, $y) = $mazeOrder[count($mazeOrder) - 1];
+    }
+}
+//留出出口
+$maze = $maze2;
+$maze[0][0][3] = 0;
+$maze[M][M][1] = 0;
+
+//寻址
+$pathArr = findPath($maze, 0, 0, false);
+var_dump($pathArr);exit;
+/*printMaze($maze, $pathArr);
+
+echo " 刷新";
+
+//打印迷宫和寻址结果by z@cot8.com
+function printMaze($maze, $pathArr)
+{
+    $im = ImageCreate((M + 1) * S + 1, (M + 1) * S + 1);
+    $bg = ImageColorAllocate($im, 236, 233, 216);
+    $pathColor = ImageColorAllocate($im, 255, 0, 0);
+    $exitColor = ImageColorAllocate($im, 134, 255, 0);
+    $borderColor = ImageColorAllocate($im, 0, 0, 0);
+    ImageRectangle($im, 0, 0, (M + 1) * S, (M + 1) * S, $borderColor);//包边
+    ImageLine($im, 0, 0, 0, S, $bg);//右上边开口
+    ImageLine($im, (M + 1) * S, M * S, (M + 1) * S, (M + 1) * S, $bg);//左下边开口
+    foreach ($maze as $x => $xarr) {//生成格子
+        foreach ($xarr as $y => $unit) {
+            if ($unit[0]) ImageLine($im, $x * S, $y * S, ($x + 1) * S, $y * S, $borderColor);//上有线
+            if ($unit[1]) ImageLine($im, ($x + 1) * S, $y * S, ($x + 1) * S, ($y + 1) * S, $borderColor);//右有线
+            if ($unit[2]) ImageLine($im, $x * S, ($y + 1) * S, ($x + 1) * S, ($y + 1) * S, $borderColor);//下有线
+            if ($unit[3]) ImageLine($im, $x * S, $y * S, $x * S, ($y + 1) * S, $borderColor);//左有线
+            //if(in_array(array($x, $y), $pathArr)) ImageFilledEllipse($im, $x * S + S/2, $y * S + S/2, S, S, $pathColor);//寻址格
+            if (in_array(array($x, $y), $pathArr)) ImageString($im, 1, $x * S + S / 5, $y * S + S / 5, array_search(array($x, $y), $pathArr), $pathColor);//寻址格
+        }
+    }
+    ImagePNG($im, 'maze.png');
+    ImageDestroy($im);
+}*/
+
+//寻址函数 z@cot8.com
+function findPath($maze, $x, $y, $fromxy)
+{
+    global $_posArr;
+    if ($x == M && $y == M) {//到达出口
+        Return array(array($x, $y));
+    }
+    foreach ($_posArr as $key => $val) {
+        if ($maze[$x][$y][$key]) continue;//为1则不通
+        $nx = $x + $val[0];
+        $ny = $y + $val[1];
+        if (!isset($maze[$nx][$ny]) || $fromxy == array($nx, $ny)) continue;//边界超出或为来源点
+        if ($pathArr = findPath($maze, $nx, $ny, array($x, $y))) {
+            array_unshift($pathArr, array($x, $y));
+            Return $pathArr;//能到达出口
+        }
+    }
+    Return false;
+}
\ No newline at end of file

From 7e58e0aef15209ab6ee23f3accd3f9d050024c83 Mon Sep 17 00:00:00 2001
From: LXZ 
Date: Sun, 14 Jan 2018 11:26:31 +0800
Subject: [PATCH 074/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=BF=B7=E5=AE=AB?=
 =?UTF-8?q?=E5=AF=BB=E5=9D=80=E7=AE=97=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 README-EN.md           |   1 +
 README.md              |   1 +
 package/Other/Maze.php | 347 +++++++++++++++++++++++++++++------------
 3 files changed, 253 insertions(+), 96 deletions(-)

diff --git a/README-EN.md b/README-EN.md
index 5e1f88e..555bf99 100644
--- a/README-EN.md
+++ b/README-EN.md
@@ -48,6 +48,7 @@
     │         ├──  GetCattle.php          
     │         ├──  OnlyNumbers.php        
     │         ├──  Interval.php        
+    │         ├──  Maze.php        
     │         └──  BigSmallReplace.php    
     │     
     ├──LICENSE 
diff --git a/README.md b/README.md
index 53ee1ff..2072610 100644
--- a/README.md
+++ b/README.md
@@ -62,6 +62,7 @@
     │         ├──  OnlyNumbers.php        求唯一数
     │         ├──  PokerGames.php         洗扑克牌
     │         ├──  Interval.php           抽奖区间算法
+    │         ├──  Maze.php               迷宫寻址算法
     │         └──  BigSmallReplace.php    Hello World 输出 Olleh Dlrow
     │     
     ├──LICENSE
diff --git a/package/Other/Maze.php b/package/Other/Maze.php
index b33a0cb..e027755 100644
--- a/package/Other/Maze.php
+++ b/package/Other/Maze.php
@@ -1,108 +1,263 @@
 = 4))
+            $arr[$l][$m] = 0;
+        else
+            $arr[$l][$m] = 1;
+
+        echo $arr[$l][$m] . ' ';
     }
+    echo '
'; } -$maze2 = array();//破墙后的已访问格子 -$mazeOrder = array();//破墙顺序 -$x = $y = 0;//初始入口 -while (count($maze) > 0) { - $tmpArr = array(); - foreach ($_posArr as $val) { - $nx = $x + $val[0]; - $ny = $y + $val[1]; - if (isset($maze[$nx][$ny])) {//未破墙过的格子 - $tmpArr[] = array($nx, $ny); +echo '


寻地址算法的实现:
'; + +function findPath($i, $j, $dir, $arr, $iline, $jline, $dirline) +{ + + //判断是否结束 + if ($i == 4 && $j == 5) return 1; + $ifdirs = 0; + $newdir = $dir; + $lastdir = $dir; + + + //如果该点为0,则前进 + if ($arr[$i][$j] == 0) { + //判断方向增量 + switch ($dir) { + case 0: + $ii = 0; + $jj = 1; + break; + case 1: + $ii = 1; + $jj = 0; + break; + case 2: + $ii = 0; + $jj = -1; + break; + case 3: + $ii = -1; + $jj = 0; + break; } - } - if ($tmpArr) {//有未破墙的格子,随机出一个,破墙 - list($nx, $ny) = $tmpArr[array_rand($tmpArr)]; - $maze2[$nx][$ny] = $maze[$nx][$ny]; - if (empty($maze2[$x][$y])) $maze2[$x][$y] = $maze[$x][$y]; - $pos = array($nx - $x, $ny - $y); - foreach ($_posArr as $key => $val) {//循环四个方向,找出需要破的墙 - if ($pos == $val) { - $maze2[$x][$y][$key] = 0;//原格子破墙 - $maze2[$nx][$ny][($key + 2) % 4] = 0;//新格子破墙 + + //判断是否路口 + for ($n = 1; $n <= 4; $n++) { + switch ($newdir) { + case 0: + $aa = 0; + $bb = 1; + break; + case 1: + $aa = 1; + $bb = 0; + break; + case 2: + $aa = 0; + $bb = -1; + break; + case 3: + $aa = -1; + $bb = 0; + break; } + if ($arr[($i + $aa)][($j + $bb)] == 0) { + $ifdirs++; + } + $newdir = ($newdir + 1) % 4; } - //设置新的当前格后返回继续while循环 - $x = $nx; - $y = $ny; - $mazeOrder[] = array($x, $y); - unset($maze[$x][$y]);//去掉已破墙的格子 - if (empty($maze[$x])) unset($maze[$x]); - } else {//当前xy周围不存在未破墙的格子,返回上一个格子继续破墙 - array_pop($mazeOrder); - if ($mazeOrder) list($x, $y) = $mazeOrder[count($mazeOrder) - 1]; - } -} -//留出出口 -$maze = $maze2; -$maze[0][0][3] = 0; -$maze[M][M][1] = 0; - -//寻址 -$pathArr = findPath($maze, 0, 0, false); -var_dump($pathArr);exit; -/*printMaze($maze, $pathArr); -echo " 刷新"; + //判断是否路口,是则记录位置和方向 + if ($ifdirs > 2) { -//打印迷宫和寻址结果by z@cot8.com -function printMaze($maze, $pathArr) -{ - $im = ImageCreate((M + 1) * S + 1, (M + 1) * S + 1); - $bg = ImageColorAllocate($im, 236, 233, 216); - $pathColor = ImageColorAllocate($im, 255, 0, 0); - $exitColor = ImageColorAllocate($im, 134, 255, 0); - $borderColor = ImageColorAllocate($im, 0, 0, 0); - ImageRectangle($im, 0, 0, (M + 1) * S, (M + 1) * S, $borderColor);//包边 - ImageLine($im, 0, 0, 0, S, $bg);//右上边开口 - ImageLine($im, (M + 1) * S, M * S, (M + 1) * S, (M + 1) * S, $bg);//左下边开口 - foreach ($maze as $x => $xarr) {//生成格子 - foreach ($xarr as $y => $unit) { - if ($unit[0]) ImageLine($im, $x * S, $y * S, ($x + 1) * S, $y * S, $borderColor);//上有线 - if ($unit[1]) ImageLine($im, ($x + 1) * S, $y * S, ($x + 1) * S, ($y + 1) * S, $borderColor);//右有线 - if ($unit[2]) ImageLine($im, $x * S, ($y + 1) * S, ($x + 1) * S, ($y + 1) * S, $borderColor);//下有线 - if ($unit[3]) ImageLine($im, $x * S, $y * S, $x * S, ($y + 1) * S, $borderColor);//左有线 - //if(in_array(array($x, $y), $pathArr)) ImageFilledEllipse($im, $x * S + S/2, $y * S + S/2, S, S, $pathColor);//寻址格 - if (in_array(array($x, $y), $pathArr)) ImageString($im, 1, $x * S + S / 5, $y * S + S / 5, array_search(array($x, $y), $pathArr), $pathColor);//寻址格 + if (in_array($i, $iline) && in_array($j, $jline)) { + } else { + echo "该点是路口:|$i,$j,$dir|
"; + $iline[] = $i; + $jline[] = $j; + $dirline[] = $dir; + } } - } - ImagePNG($im, 'maze.png'); - ImageDestroy($im); -}*/ -//寻址函数 z@cot8.com -function findPath($maze, $x, $y, $fromxy) -{ - global $_posArr; - if ($x == M && $y == M) {//到达出口 - Return array(array($x, $y)); - } - foreach ($_posArr as $key => $val) { - if ($maze[$x][$y][$key]) continue;//为1则不通 - $nx = $x + $val[0]; - $ny = $y + $val[1]; - if (!isset($maze[$nx][$ny]) || $fromxy == array($nx, $ny)) continue;//边界超出或为来源点 - if ($pathArr = findPath($maze, $nx, $ny, array($x, $y))) { - array_unshift($pathArr, array($x, $y)); - Return $pathArr;//能到达出口 + if ($ifdirs > 1) { + //不是死路,前进 + if ($arr[($i + $ii)][($j + $jj)] == 0) { + //方向不变,可以前进 + $i += $ii; + $j += $jj; + echo "方向不变,可以前进:|$i,$j,$dir|
"; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } else { + //方向改变,试探 + if ($ifdirs > 2) { + //该点是路口,取来时方向为路口记录方向 + $lastdir = $dirline[(count($dirline) - 1)]; + } else { + //不是路口,则在改变方向前记录方向 + $lastdir = $dir; + } + + //判断来时方向,不能走回头路 + switch ($lastdir) { + case 0: + $errdir = 2; + break; + case 1: + $errdir = 3; + break; + case 2: + $errdir = 0; + break; + case 3: + $errdir = 1; + break; + } + //改变方向 + $dir = ($dir + 1) % 4; + + //判断改变后方向是否为来时方向 + echo "不能走回头路:err:$errdir,dir:$dir
"; + if ($dir != $errdir) { + echo "turn:($i,$j,$dir)
"; + switch ($dir) { + case 0: + $mm = 0; + $nn = 1; + break; + case 1: + $mm = 1; + $nn = 0; + break; + case 2: + $mm = 0; + $nn = -1; + break; + case 3: + $mm = -1; + $nn = 0; + break; + } + if ($arr[($i + $mm)][($j + $nn)] == 0) { + $i += $mm; + $j += $nn; + echo "可以前进:$i,$j,$dir
"; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } else { + $dir = ($dir + 1) % 4; + echo "再改变方向,试探:$i,$j,$dir
"; + if ($dir != $errdir) { + echo "turn:($i,$j,$dir)
"; + switch ($dir) { + case 0: + $ii = 0; + $jj = 1; + break; + case 1: + $ii = 1; + $jj = 0; + break; + case 2: + $ii = 0; + $jj = -1; + break; + case 3: + $ii = -1; + $jj = 0; + break; + } + if ($arr[($i + $ii)][($j + $jj)] == 0) { + $i += $ii; + $j += $jj; + echo "可以前进:$i,$j,$dir
"; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } + } else { + $dir = ($dir + 1) % 4; + echo "再改变方向,试探:$i,$j,$dir
"; + switch ($dir) { + case 0: + $ii = 0; + $jj = 1; + break; + case 1: + $ii = 1; + $jj = 0; + break; + case 2: + $ii = 0; + $jj = -1; + break; + case 3: + $ii = -1; + $jj = 0; + break; + } + if ($arr[($i + $ii)][($j + $jj)] == 0) { + $i += $ii; + $j += $jj; + echo "OK:$i,$j,$dir
"; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } + + } + } + + } else { + $dir = ($dir + 1) % 4; + echo "不能回头,再改变方向,试探:$i,$j,$dir
"; + switch ($dir) { + case 0: + $ii = 0; + $jj = 1; + break; + case 1: + $ii = 1; + $jj = 0; + break; + case 2: + $ii = 0; + $jj = -1; + break; + case 3: + $ii = -1; + $jj = 0; + break; + } + if ($arr[($i + $ii)][($j + $jj)] == 0) { + $i += $ii; + $j += $jj; + echo "可以前进:$i,$j,$dir
"; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } + } + } + } else { + //是死路,需要返回到上个路口,改变方向,试探 + $dir = $dirline[(count($dirline) - 1)]; + $i = $iline[(count($iline) - 1)]; + $j = $jline[(count($jline) - 1)]; + echo "是死路,返回到上个路口,记录为:#$i,$j,$dir#
"; + $dir = ($dir + 1) % 4; + findPath($i, $j, $dir, $arr, $iline, $jline, $dirline); + } + } - Return false; -} \ No newline at end of file +} + +$a[] = $b[] = $c[] = 0; + +echo '初始值=>节点:($i=1,$j=1),方向:($dir=0).

'; +findPath(1, 1, 0, $arr, $a, $b, $c); \ No newline at end of file From 6c3af0479e2d3518c3c66edcb470b50df5c9c752 Mon Sep 17 00:00:00 2001 From: LXZ Date: Fri, 19 Jan 2018 17:48:21 +0800 Subject: [PATCH 075/127] =?UTF-8?q?=E7=94=B5=E6=A2=AF=E8=B0=83=E5=BA=A6?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/ElevatorDispatch.php | 96 ++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 package/Other/ElevatorDispatch.php diff --git a/README-EN.md b/README-EN.md index 283b471..e9c5a82 100644 --- a/README-EN.md +++ b/README-EN.md @@ -51,6 +51,7 @@ │ ├── Maze.php │ ├── AntsClimb.php │ ├── Encryption.php + │ ├── ElevatorDispatch.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index 84848f9..b260883 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ │ ├── Maze.php 迷宫寻址算法 │ ├── AntsClimb.php 蚂蚁爬杆算法 │ ├── Encryption.php 对称加密算法 + │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/ElevatorDispatch.php b/package/Other/ElevatorDispatch.php new file mode 100644 index 0000000..6bbf763 --- /dev/null +++ b/package/Other/ElevatorDispatch.php @@ -0,0 +1,96 @@ + $first_layer + $first_layer_above的时候, 我们在第i-1层 选择电梯停止最好。 + * (2)若$first_layer_below + $first_layer < $first_layer_above的时候, 我们选择在第i+1层停止电梯最好。 + * + * 下面我们可以先计算出来当i=1时候的T ,然后判断是否需要在i+1层停止,若是i+1层的花费 + * 大于i层,则我们可以继续计算,否则退出。 + */ +class ElevatorDispatch +{ + protected $n = 10; + protected $person; + protected $time = 0; //先计算出在第一层停止的时候 所需要的花费 + protected $first_layer_below = 0; //在第一层以下下的人数 + protected $first_layer; + protected $first_layer_above = 0;//在第一层之上下电梯的人数 + public $floor = 1;//存储停靠的楼层 + + public function __construct($person = []) + { + if (empty($person)) { + $this->person = [0, 2, 5, 7, 3, 5, 2, 6, 2, 6, 3]; + } + $this->first_layer = $this->person[1]; //在第一层处下的人数 + + } + + public function compute() + { + + //先计算出第1层停止需要爬取的楼层数目 + for ($i = 2; $i <= $this->n; $i++) { + $this->time += $this->person[$i] * ($i - 1); + $this->first_layer_above += $this->person[$i]; + } + for ($j = 2; $j <= $this->n; $j++) { + if ($this->first_layer_below + $this->first_layer <= $this->first_layer_above) { //说明第i+1层的结果会大于第i层 + $this->time += $this->first_layer_below + $this->first_layer - $this->first_layer_above; + $this->first_layer_below += $this->first_layer; + $this->first_layer = $this->person[$j]; + $this->first_layer_above -= $this->person[$j]; + $this->floor = $j; + } else { + //否则第i层的结果已经最小,故不需要计算第i+1层 + break; + } + } + return $this->floor; + } + + public function computeTwo() + { + $min = 6553;//存储最小值 ; + for ($i = 1; $i <= $this->n; $i++) { //表示第i楼层电梯停靠 + $this->time = 0; + for ($j = 1; $j < $this->n; $j++) { + $this->time += abs(($i - $j)) * $this->person[$j]; + } + if ($min > $this->time) { + $min = $this->time; + $this->floor = $i; + } + } + return $this->floor; + } + +} + +$obj = new ElevatorDispatch(); + +var_dump($obj->compute()); +var_dump($obj->computeTwo()); \ No newline at end of file From 29ea0dcfe3661c2bcbc07ca4e99c130c4c42965a Mon Sep 17 00:00:00 2001 From: Openset Date: Tue, 23 Jan 2018 10:19:24 +0800 Subject: [PATCH 076/127] Add: TraversalOfBinaryTree --- .gitignore | 2 + .idea/vcs.xml | 6 -- package/Other/TraversalOfBinaryTree.php | 97 +++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 6 deletions(-) create mode 100644 .gitignore delete mode 100644 .idea/vcs.xml create mode 100644 package/Other/TraversalOfBinaryTree.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f32e31a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea/ +.DS_Store diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/package/Other/TraversalOfBinaryTree.php b/package/Other/TraversalOfBinaryTree.php new file mode 100644 index 0000000..6a29113 --- /dev/null +++ b/package/Other/TraversalOfBinaryTree.php @@ -0,0 +1,97 @@ + + * @link https://github.com/openset + * @date 2018/01/23 + */ +class Node +{ + public $value; + public $left; + public $right; +} + +//先序遍历 根节点 ---> 左子树 ---> 右子树 +function DLROrder($root) +{ + $stack = array(); + array_push($stack, $root); + while (!empty($stack)) { + $center_node = array_pop($stack); + echo $center_node->value . ' ';//先输出根节点 + if ($center_node->right != null) { + array_push($stack, $center_node->right);//压入左子树 + } + if ($center_node->left != null) { + array_push($stack, $center_node->left); + } + } +} + +//中序遍历,左子树---> 根节点 ---> 右子树 +function LDROrder($root) +{ + $stack = array(); + $center_node = $root; + while (!empty($stack) || $center_node != null) { + while ($center_node != null) { + array_push($stack, $center_node); + $center_node = $center_node->left; + } + + $center_node = array_pop($stack); + echo $center_node->value . " "; + + $center_node = $center_node->right; + } +} + +//后序遍历,左子树 ---> 右子树 ---> 根节点 +function LRDOrder($root) +{ + $stack = array(); + $outstack = array(); + array_push($stack, $root); + while (!empty($stack)) { + $center_node = array_pop($stack); + array_push($outstack, $center_node);//最先压入根节点,最后输出 + if ($center_node->left != null) { + array_push($stack, $center_node->left); + } + if ($center_node->right != null) { + array_push($stack, $center_node->right); + } + } + + while (!empty($outstack)) { + $center_node = array_pop($outstack); + echo $center_node->value . ' '; + } + +} + +$a = new Node(); +$b = new Node(); +$c = new Node(); +$d = new Node(); +$e = new Node(); +$f = new Node(); +$a->value = 'A'; +$b->value = 'B'; +$c->value = 'C'; +$d->value = 'D'; +$e->value = 'E'; +$f->value = 'F'; +$a->left = $b; +$a->right = $c; +$b->left = $d; +$c->left = $e; +$c->right = $f; + +DLROrder($a);//A B D C E F + +LDROrder($a);//D B A E C F + +LRDOrder($a);//D B E F C A \ No newline at end of file From 28f61237d6c42e481a8f70fbb2d637d0d3e73177 Mon Sep 17 00:00:00 2001 From: LXZ Date: Thu, 25 Jan 2018 11:11:46 +0800 Subject: [PATCH 077/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0KMP=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/kmp.php | 141 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 package/Other/kmp.php diff --git a/package/Other/kmp.php b/package/Other/kmp.php new file mode 100644 index 0000000..2dc0114 --- /dev/null +++ b/package/Other/kmp.php @@ -0,0 +1,141 @@ +haystack = $haystack; + $this->needle = $needle; + //初始化一些参数 + $this->_haystackLen = $this->getLen($this->haystack); + $this->_needleLen = $this->getLen($this->needle); + $this->_matchTable = $this->getMatchTable(); + $this->_isMatch = false; + } + + + //类似strpos函数功能 + public function strpos() + { + //haystack + $haystackIdx = $matchNum = 0; + while ($haystackIdx <= $this->_haystackLen - $this->_needleLen) { + //needle + $needIdx = 0; + for (; $needIdx < $this->_needleLen; $needIdx++) { + if (strcmp($this->haystack[$haystackIdx], $this->needle[$needIdx]) <> 0) { + if ($matchNum > 0) { + $lastMatchValue = $this->getLastMatchValue($needIdx - 1); + $haystackIdx += $this->getStep($matchNum, $lastMatchValue); + $matchNum = 0; + } else { + $haystackIdx++; + } + break; + } else { + $haystackIdx++; + $matchNum++; + if ($matchNum == $this->_needleLen) { + $this->_isMatch = true; + break; + } + } + } + if ($this->_isMatch == true) { + break; + } + } + return $this->_isMatch ? $haystackIdx - $this->_needleLen : false; + } + + //获取字符长度 + private function getLen($str) + { + return mb_strlen($str, 'utf-8'); + } + + //获取部分匹配表 + private function getMatchTable() + { + $matchTable = []; + for ($i = 0; $i < $this->_needleLen; $i++) { + $intersectLen = 0; + $nowStr = mb_substr($this->needle, 0, $i + 1, 'utf-8'); + $preFixArr = $this->getPreFix($nowStr); + $sufFixArr = $this->getSufFix($nowStr); + if ($preFixArr && $sufFixArr) { + $intersectArr = array_intersect($preFixArr, $sufFixArr); + if (!empty($intersectArr)) { + $intersect = array_pop($intersectArr); + $intersectLen = mb_strlen($intersect, 'utf-8'); + } + } + $matchTable[$i] = $intersectLen; + } + return $matchTable; + } + + //获取前缀数组 + private function getPreFix($str) + { + $outArr = []; + $strLen = $this->getLen($str); + if ($strLen > 1) { + for ($i = 1; $i < $strLen; $i++) { + $outArr[] = mb_substr($str, 0, $i, 'utf-8'); + } + } + return $outArr; + } + + //获取后缀数组 + private function getSufFix($str) + { + $outArr = []; + $strLen = $this->getLen($str); + if ($strLen > 1) { + for ($i = 1; $i < $strLen; $i++) { + $outArr[] = mb_substr($str, $i, null, 'utf-8'); + } + } + return $outArr; + } + + //计算步长 + private function getStep($matchNum, $lastMatchValue) + { + return $matchNum - $lastMatchValue; + } + + //获取最后匹配值 + private function getLastMatchValue($index) + { + return isset($this->_matchTable[$index]) ? $this->_matchTable[$index] : 0; + } +} + +$str = 'a b a c a a b a c a b a c a b a a b b'; +$subStr = 'a b a c a b'; +$kmp = new KMP($str, $subStr); +var_dump($kmp->strpos()); +$kmp->haystack = 'pull requests'; +$kmp->needle = 'sts'; +var_dump($kmp->strpos()); +$kmp->haystack = 'i love you'; +$kmp->needle = 'hate'; +var_dump($kmp->strpos()); \ No newline at end of file From 08a21cce0bc49bf3992277acf1d8e3d2391b85c9 Mon Sep 17 00:00:00 2001 From: LXZ Date: Thu, 25 Jan 2018 11:15:20 +0800 Subject: [PATCH 078/127] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86README?= =?UTF-8?q?=E4=B8=8A=E7=BC=BA=E5=B0=91=E7=9A=84=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 2 ++ README.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/README-EN.md b/README-EN.md index e9c5a82..bc72b3e 100644 --- a/README-EN.md +++ b/README-EN.md @@ -52,6 +52,8 @@ │ ├── AntsClimb.php │ ├── Encryption.php │ ├── ElevatorDispatch.php + │ ├── kmp.php + │ ├── TraversalOfBinary.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index b260883..090dfdf 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,8 @@ │ ├── AntsClimb.php 蚂蚁爬杆算法 │ ├── Encryption.php 对称加密算法 │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 + │ ├── kmp.php 算法导论-KMP算法 + │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE From 6736143903cee500c4c60dfe619fe18b8136fc0a Mon Sep 17 00:00:00 2001 From: lazyou <1394139539@qq.com> Date: Sat, 27 Jan 2018 16:21:24 +0800 Subject: [PATCH 079/127] =?UTF-8?q?fix=20=E9=94=99=E5=88=AB=E5=AD=97.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 090dfdf..cbe522c 100644 --- a/README.md +++ b/README.md @@ -117,8 +117,8 @@ left|right 10000个元素|10s|14ms 1 000 000 000 个元素|11天|30ms - - 大`O`表示发指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 - 使用大`O`表示发这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` +  - 大`O`表示法指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 +    使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` - 一些常见的大O运行时间 - O(log n) ,也叫对数时间,这样的算法包括二分算法 - O(n),也叫线性时间,这样的算法包括简单查找。 @@ -128,7 +128,7 @@ left|right - 这里是重点 - 算法的速度指的并非时间,而是操作数的增速 - 谈论算法的速度时间时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加 - - 算法的运行时间用大O表示发表示 +  - 算法的运行时间用大O表示法表示 - O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 ## 编写解决实际问题的程序过程 From 8061bbfab78a6329ab741cdaaa399e83befcb0e4 Mon Sep 17 00:00:00 2001 From: LXZ Date: Sun, 28 Jan 2018 15:06:40 +0800 Subject: [PATCH 080/127] =?UTF-8?q?=E5=88=A9=E7=94=A8=E5=90=91=E9=87=8F?= =?UTF-8?q?=E5=8F=89=E9=9B=86=E5=88=A4=E6=96=AD=E4=B8=80=E4=B8=AA=E7=82=B9?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E5=9C=A8=E4=B8=89=E8=A7=92=E5=BD=A2=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/PointInTriangle.php | 69 +++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+) create mode 100644 package/Other/PointInTriangle.php diff --git a/README-EN.md b/README-EN.md index bc72b3e..1b9e445 100644 --- a/README-EN.md +++ b/README-EN.md @@ -54,6 +54,7 @@ │ ├── ElevatorDispatch.php │ ├── kmp.php │ ├── TraversalOfBinary.php + │ ├── PointInTriangle.php │ └── BigSmallReplace.php │ ├──LICENSE diff --git a/README.md b/README.md index cbe522c..62e3948 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ │ ├── Encryption.php 对称加密算法 │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 │ ├── kmp.php 算法导论-KMP算法 + │ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ diff --git a/package/Other/PointInTriangle.php b/package/Other/PointInTriangle.php new file mode 100644 index 0000000..2794c3c --- /dev/null +++ b/package/Other/PointInTriangle.php @@ -0,0 +1,69 @@ +point = $point; + if (count($triangle) != 3) { + exit('这个不是三角形'); + } + $this->triangle = $triangle; + } + + //向量叉集计算 + private function cross($a, $b, $p) + { + return ($b['x'] - $a['x']) * ($p['y'] - $a['y']) - ($b['y'] - $a['y']) * ($p['x'] - $a['x']); + } + + //判断是否在左边 + private function toLeft($a, $b, $p) + { + return $this->cross($a, $b, $p) > 0; + } + + //开始构造三角形 + public function inTriangle() + { + $res = $this->toLeft($this->triangle[0], $this->triangle[1], $this->point); + + if ($res != $this->toLeft($this->triangle[1], $this->triangle[2], $this->point)) { + return '不在三角形中'; + } + if ($res != $this->toLeft($this->triangle[2], $this->triangle[0], $this->point)) { + return '不在三角形中'; + } + + if ($this->cross($this->triangle[0], $this->triangle[1], $this->triangle[2]) == 0) { + return '不在三角形中'; + } + return '点' . json_encode($this->point) . '在三角形中'; + } +} + +$point = [ + 'x' => 4, + 'y' => 1 +]; +$point1 = [ + 'x' => 4, + 'y' => 5 +]; +$triangle = [ + ['x' => 1, 'y' => 1], + ['x' => 6, 'y' => 3], + ['x' => 4, 'y' => 7], +]; + +$obj = new PointInTriangle($point1, $triangle); + +var_dump($obj->inTriangle()); +exit; \ No newline at end of file From 274c907310ea9d3f394235ba1bc123bc3ab10bb4 Mon Sep 17 00:00:00 2001 From: Openset Date: Tue, 6 Feb 2018 15:31:05 +0800 Subject: [PATCH 081/127] =?UTF-8?q?Update:=20GetCattle=20=E7=AE=97?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/GetCattle.php | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/package/Other/GetCattle.php b/package/Other/GetCattle.php index 9cc19dc..4f08a22 100644 --- a/package/Other/GetCattle.php +++ b/package/Other/GetCattle.php @@ -21,19 +21,18 @@ function getCattle($n) { static $num = 1; - for ($i =1; $i<=$n;$i++){ - if( $i == 20) break; - if($i >= 4 && $i <15){ - if($i % 4 == 0 ){ - getCattle($n - $i); - $num++; - } - $num++; + for ($i = 1; $i <= $n; $i++) { + if ($i == 20) { + $num--; //死亡需减一 + } else if ($i >= 4 && $i < 15) { + $num++; //生小母牛(这里有小母牛) + getCattle($n - $i); //小母牛生小母牛(这里不包含小母牛) } } return $num; } -echo '牛年共有:'.getCattle(10); + +echo '牛年共有:' . getCattle(10); /* 123456789 From 9daa560899dbacfd97ec902506db23e0b268df38 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 14 Feb 2018 13:43:53 +0800 Subject: [PATCH 082/127] :tada: Happy New Year! --- README.md | 2 - package/{Query => Features}/YieldExample.php | 0 package/Other/AntsClimb.php | 220 +++++++++++------- package/Other/BidirectionalQueue.php | 24 +- package/Other/BigSmallReplace.php | 63 ++--- package/Other/ColorBricks.php | 19 +- package/Other/DynamicProgramming.php | 26 ++- package/Other/ElevatorDispatch.php | 17 +- package/Other/Encryption.php | 45 +++- package/Other/Fibonacci.php | 39 +++- package/Other/GetCattle.php | 18 +- package/Other/HanoiGames.php | 17 +- package/Other/Interval.php | 28 ++- package/Other/Maze.php | 29 ++- package/Other/MonkeyKing.php | 66 ++++-- package/Other/OnlyNumbers.php | 21 +- package/Other/PointInTriangle.php | 54 ++++- package/Other/PokerGames.php | 61 ++++- package/Other/StealingApples.php | 12 +- package/Other/TraversalOfBinaryTree.php | 97 -------- package/Other/kmp.php | 48 ++-- package/Query/BinaryQuery.php | 78 ++++--- package/Query/BinaryTree.php | 6 +- package/Query/FibonacciQuery.php | 44 ++-- package/Query/InsertQuery.php | 11 +- .../Query/{QulickQuery.php => QuickQuery.php} | 15 +- package/Sort/BubbleSort.php | 14 +- package/Sort/HeapSort.php | 14 +- package/Sort/InsertSort.php | 14 +- package/Sort/MergeSort.php | 17 +- package/Sort/QuickSort.php | 25 +- package/Sort/SelectSort.php | 14 +- package/Sort/ShellSort.php | 17 +- package/Sort/ShuttleSort.php | 12 +- package/Structure/KitchenQueue.php | 3 +- package/Structure/LinearChain.php | 1 - package/Tools/SystemSwitch.php | 1 - 37 files changed, 811 insertions(+), 381 deletions(-) rename package/{Query => Features}/YieldExample.php (100%) delete mode 100644 package/Other/TraversalOfBinaryTree.php rename package/Query/{QulickQuery.php => QuickQuery.php} (77%) diff --git a/README.md b/README.md index 62e3948..752325c 100644 --- a/README.md +++ b/README.md @@ -98,8 +98,6 @@ left|right 24 = 16 | log216 = 4 25 = 32 | log232 = 5 -战斗吧!少年 - ## 运行时间 以二分查找为例,使用它可节省多少时间呢?简单查找逐个地检查数字,如果列表包含100个数字,最多需要猜100次。 换而言之最多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 diff --git a/package/Query/YieldExample.php b/package/Features/YieldExample.php similarity index 100% rename from package/Query/YieldExample.php rename to package/Features/YieldExample.php diff --git a/package/Other/AntsClimb.php b/package/Other/AntsClimb.php index 5900341..448c839 100644 --- a/package/Other/AntsClimb.php +++ b/package/Other/AntsClimb.php @@ -1,97 +1,159 @@ + * @date 2018/1/11 + * @license MIT + * ------------------------------------------------------------- + * 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。 + * 木杆很细,不能同时通过一只蚂蚁。开始 时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头, + * 但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。 + * ------------------------------------------------------------- + * 编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间 */ -function add2($directionArr, $count, $i) -{ - if (0 > $i) { - return $directionArr; - } - if (0 == $directionArr[$i]) { - $directionArr[$i] = 1; - return $directionArr; - } - $directionArr[$i] = 0; - return add2($directionArr, $count, $i - 1); -} +// +-------------------------------------------------------------------------- +// | 解题方式 +// +-------------------------------------------------------------------------- -function path($positionArr) +class AntsClimb { - // 生成测试路径 - $pathCalculate = array(); - $count = count($positionArr); - $directionArr = array_fill(0, $count, 0); - //print_r($directionArr);exit; + /** + * @var array 蚂蚁位置集合 + */ + protected $position; - // 朝向 - $end = str_repeat('1', $count); - while (true) { - $path = implode('', $directionArr); - //$pathArray = array_combine($positionArr, $directionArr); - $total = calculate($positionArr, $directionArr); - $pathCalculate['路径:' . $path] = $total; - if ($end == $path) { // 遍历完成 - break; + /** + * AntsClimb constructor. + * + * @param array $position + */ + public function __construct(array $position) + { + $this->position = $position; + } + + /** + * run + * + * @return void + */ + public function run() + { + $pathCalculate = $this->path($this->position); + echo '
计算-';
+        print_r($pathCalculate);
+        echo '排序-';
+        asort($pathCalculate);
+        print_r($pathCalculate);
+    }
+
+    /**
+     * add2
+     *
+     * @param $directionArr
+     * @param $count
+     * @param $i
+     * @return mixed
+     */
+    protected function add2($directionArr, $count, $i)
+    {
+        if (0 > $i) {
+            return $directionArr;
+        }
+        if (0 === $directionArr[$i]) {
+            $directionArr[$i] = 1;
+            return $directionArr;
         }
-        $directionArr = add2($directionArr, $count, $count - 1);
+        $directionArr[$i] = 0;
+        return $this->add2($directionArr, $count, $i - 1);
     }
-    return $pathCalculate;
-}
 
-function calculate($positionArr, $directionArr)
-{
-    //print_r($positionArr);
-    //print_r($directionArr);
-    $total = 0;
-    // 总用时
-    $length = 27;
-    // 木杆长度
-    while ($positionArr) {
-        $total++; // 步增耗时
-        $nextArr = array(); // 下一步位置
-        foreach ($positionArr as $key => $value) {
-            if (0 == $directionArr[$key]) {
-                $next = $value - 1; // 向0方向走一步
-            } else {
-                $next = $value + 1; // 向1方向走一步
-            }
-            if (0 == $next) { // 在0方向走出
-                continue;
-            }
-            if ($length == $next) { // 在1方向走出
-                continue;
+    /**
+     * path
+     *
+     * @param $positionArr
+     * @return array
+     */
+    protected function path($positionArr)
+    {
+        // 生成测试路径
+        $pathCalculate = array ();
+        $count         = count($positionArr);
+        $directionArr  = array_fill(0, $count, 0);
+
+        // 朝向
+        $end = str_repeat('1', $count);
+        while (true) {
+            $path                         = implode('', $directionArr);
+            $total                        = $this->calculate($positionArr, $directionArr);
+            $pathCalculate['路径:' . $path] = $total;
+            if ($end == $path) { // 遍历完成
+                break;
             }
-            $nextArr[$key] = $next;
+            $directionArr = $this->add2($directionArr, $count, $count - 1);
         }
-        $positionArr = $nextArr;// 将$positionArr置为临时被查找数组
+        return $pathCalculate;
+    }
 
-        foreach ($nextArr as $key => $value) {
-            $findArr = array_keys($positionArr, $value);
-            if (count($findArr) < 2) {
-                // 没有重合的位置
-                continue;
+    /**
+     * calculate
+     *
+     * @param $positionArr
+     * @param $directionArr
+     * @return int
+     */
+    protected function calculate($positionArr, $directionArr)
+    {
+        $total = 0;
+        // 总用时
+        $length = 27;
+        // 木杆长度
+        while ($positionArr) {
+            $total++; // 步增耗时
+            $nextArr = array (); // 下一步位置
+            foreach ($positionArr as $key => $value) {
+                if (0 == $directionArr[$key]) {
+                    $next = $value - 1; // 向0方向走一步
+                } else {
+                    $next = $value + 1; // 向1方向走一步
+                }
+                if (0 == $next) { // 在0方向走出
+                    continue;
+                }
+                if ($length == $next) { // 在1方向走出
+                    continue;
+                }
+                $nextArr[$key] = $next;
             }
-            foreach ($findArr as $findIndex) {
-                $directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1;
-                // 反向处理
-                unset($positionArr[$findIndex]);
-                // 防止重复查找计算
+            $positionArr = $nextArr;// 将$positionArr置为临时被查找数组
+
+            foreach ($nextArr as $key => $value) {
+                $findArr = array_keys($positionArr, $value);
+                if (count($findArr) < 2) {
+                    // 没有重合的位置
+                    continue;
+                }
+                foreach ($findArr as $findIndex) {
+                    $directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1;
+                    // 反向处理
+                    unset($positionArr[$findIndex]);
+                    // 防止重复查找计算
+                }
             }
+            $positionArr = $nextArr;
+            // 将$positionArr置为下一步结果数组
         }
-        $positionArr = $nextArr;
-        // 将$positionArr置为下一步结果数组
+        return $total;
     }
-    return $total;
 }
 
-$positionArr = array(3, 7, 11, 17, 23);
-$pathCalculate = path($positionArr);
-echo '
计算-';
-print_r($pathCalculate);
-echo '排序-';
-asort($pathCalculate);
-print_r($pathCalculate);
\ No newline at end of file
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
+// 蚂蚁位置
+$position = array (3, 7, 11, 17, 23);
+// 测试用例
+(new AntsClimb($position))->run();
\ No newline at end of file
diff --git a/package/Other/BidirectionalQueue.php b/package/Other/BidirectionalQueue.php
index b644ca2..099d705 100644
--- a/package/Other/BidirectionalQueue.php
+++ b/package/Other/BidirectionalQueue.php
@@ -1,18 +1,22 @@
 
- * @date     2017/9/13
+ * @date     2018/1/11
  * @license  MIT
  * -------------------------------------------------------------
- * 思路分析: 考察PHP几个内置数组的函数
+ * 双向队列的实现及应用
  * -------------------------------------------------------------
+ * 思路分析: 考察PHP几个内置数组的函数
  * 双向队列是一种双向开口的连续线性空间,可以高效的在头尾两端插入和删除元素
- * @param      $n
- * @return int
  */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
 class BidirectionalQueue
 {
     /**
@@ -34,8 +38,7 @@ class BidirectionalQueue
     /**
      * BidirectionalQueue 初始化.
      *
-     *  @param int $type
-
+     * @param int $type
      * @param int $maxLength
      */
     public function __construct($type = self::C_AT_BOTH_ENDS, $maxLength = 0)
@@ -127,7 +130,6 @@ public function getLength()
 
     /**
      * 获取配置常量
-     *
      */
     protected function getConfig()
     {
@@ -141,4 +143,10 @@ protected function getConfig()
         ];
     }
 }
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
+
 new BidirectionalQueue();
\ No newline at end of file
diff --git a/package/Other/BigSmallReplace.php b/package/Other/BigSmallReplace.php
index c5277ff..547a7b8 100644
--- a/package/Other/BigSmallReplace.php
+++ b/package/Other/BigSmallReplace.php
@@ -1,48 +1,55 @@
 
- * @date     2017/8/12
- * @license  Mozilla
- *
- * segmentFault: https://segmentfault.com/q/1010000010627229
+ * @date     2018/1/11
+ * @license  MIT
+ * -------------------------------------------------------------
+ * Hello World 输出 Olleh Dlrow
+ * -------------------------------------------------------------
+ * SWAT 输出 TAWS
+ * I am A sTudent 输出 I ma A tNeduts
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * BigSmallReplace
  *
- * @param    $str
- * @return   string
+ * @param $str
+ * @return string
  */
-function BigSmallReplace( $str )
+function BigSmallReplace($str)
 {
     // Cutting words
     $first  = preg_split("/[\s]+/", $str);
     $result = [];
 
     // Start
-    foreach ( $first as $f_value ) {
-        $str_len = strlen($f_value) - 1; $i = 0; $temp   = '';
-        while ( $str_len >= 0 ) {
-            if ( ord($f_value[$str_len]) > 64 && ord($f_value[$str_len]) < 91 ) {
-                $temp   .=  strtoupper($f_value[$i]);
-            }else if ( ord($f_value[$str_len]) > 96 && ord($f_value[$str_len]) < 123 ) {
-                $temp   .=  strtolower($f_value[$i]);
+    foreach ($first as $f_value) {
+        $str_len = strlen($f_value) - 1;
+        $i       = 0;
+        $temp    = '';
+        while ($str_len >= 0) {
+            if (ord($f_value[$str_len]) > 64 && ord($f_value[$str_len]) < 91) {
+                $temp .= strtoupper($f_value[$i]);
+            } else if (ord($f_value[$str_len]) > 96 && ord($f_value[$str_len]) < 123) {
+                $temp .= strtolower($f_value[$i]);
             }
-            $i++; $str_len--;
+            $i++;
+            $str_len--;
         }
         array_push($result, strrev($temp));
     }
-    return implode(' ',$result);
+    return implode(' ', $result);
 }
 
-var_dump(BigSmallReplace('Hello World'));
-// Olleh Dlrow
-
-
-/*
-Hello World 输出 Olleh Dlrow
-
-SWAT 输出 TAWS
-
-I am A sTudent 输出 I ma A tNeduts
-*/
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
 
+var_dump(BigSmallReplace('Hello World'));
diff --git a/package/Other/ColorBricks.php b/package/Other/ColorBricks.php
index 79fd236..d3a498d 100644
--- a/package/Other/ColorBricks.php
+++ b/package/Other/ColorBricks.php
@@ -1,6 +1,7 @@
 
  * @date     2017/9/1
@@ -36,8 +37,17 @@
  *           ABAB
  *  输出例子1:
  *           2
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * ColorBricks
+ *
  * @param $inputting
- * @return mixed
+ * @return bool|int
  */
 function ColorBricks($inputting)
 {
@@ -80,4 +90,9 @@ function ColorBricks($inputting)
     return $counter;
 }
 
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 echo ColorBricks("AABB");
\ No newline at end of file
diff --git a/package/Other/DynamicProgramming.php b/package/Other/DynamicProgramming.php
index 2e71008..53b6ad3 100644
--- a/package/Other/DynamicProgramming.php
+++ b/package/Other/DynamicProgramming.php
@@ -1,17 +1,29 @@
 
  * @date     2017/8/28
- * @license  Mozilla
+ * @license  MIT
  * -------------------------------------------------------------
  * 思路分析:动态规划原理思想,max(opt(i-1,w),wi+opt(i-1,w-wi)) 当中最大值,opt(i-1,w-wi)指上一个最优解
  * -------------------------------------------------------------
  * 一个承受最大重量为W的背包,现在有n个物品,每个物品重量为t, 每个物品的价值为v。
  * 要使得这个背包重量最大(但不能超过W),同时又需要背包的价值最大
- * @return int
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * DynamicProgramming
+ *
+ * @param $maxSize
+ * @param $goods
+ * @param $cost
+ * @return mixed
  */
 function DynamicProgramming($maxSize, $goods, $cost)
 {
@@ -42,7 +54,11 @@ function DynamicProgramming($maxSize, $goods, $cost)
             }
         }
     }
-    var_dump($container[$j - 1][$i - 1]);
+    return $container[$j - 1][$i - 1];
 }
 
-echo DynamicProgramming(15, [3, 4, 5, 6], [8, 7, 4, 9]);
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
+echo DynamicProgramming(15, array (3, 4, 5, 6), array (8, 7, 4, 9));
diff --git a/package/Other/ElevatorDispatch.php b/package/Other/ElevatorDispatch.php
index 6bbf763..d1811ba 100644
--- a/package/Other/ElevatorDispatch.php
+++ b/package/Other/ElevatorDispatch.php
@@ -2,6 +2,11 @@
 
 /**
  * 编程之美-电梯调度算法
+ *
+ * @author   Neroxiezi  
+ * @date     2018/1/11
+ * @license  MIT
+ * -------------------------------------------------------------
  * 解决方案:
  * (1)使用简单的方法,直接将楼层从1到n开始遍历
  *      sum(person[i] *  |i - j| ) 此表达式为一个双重循环,i与j均为1-n的循环。
@@ -30,6 +35,12 @@
  * 下面我们可以先计算出来当i=1时候的T ,然后判断是否需要在i+1层停止,若是i+1层的花费
  * 大于i层,则我们可以继续计算,否则退出。
  */
+
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
 class ElevatorDispatch
 {
     protected $n = 10;
@@ -90,7 +101,11 @@ public function computeTwo()
 
 }
 
-$obj = new ElevatorDispatch();
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 
+$obj = new ElevatorDispatch();
 var_dump($obj->compute());
 var_dump($obj->computeTwo());
\ No newline at end of file
diff --git a/package/Other/Encryption.php b/package/Other/Encryption.php
index c8e3200..22e5eee 100644
--- a/package/Other/Encryption.php
+++ b/package/Other/Encryption.php
@@ -1,11 +1,26 @@
 
+ * @date     2018/1/11
+ * @license  MIT
+ * -------------------------------------------------------------
+ * 位运算进行加密
  */
 
-//加密函数
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * 加密函数
+ *
+ * @param $txt
+ * @param $key
+ * @return string
+ */
 function passport_encrypt($txt, $key)
 {
     $encrypt_key = md5(rand(0, 32000));
@@ -15,11 +30,16 @@ function passport_encrypt($txt, $key)
         $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
         $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
     }
-    //var_dump(passport_key($tmp, $key));exit;
     return base64_encode(passport_key($tmp, $key));
 }
 
-//解密函数
+/**
+ * 解密函数
+ *
+ * @param $txt
+ * @param $key
+ * @return string
+ */
 function passport_decrypt($txt, $key)
 {
     $txt = passport_key(base64_decode($txt), $key);
@@ -32,6 +52,13 @@ function passport_decrypt($txt, $key)
     return $tmp;
 }
 
+/**
+ * passport_key
+ *
+ * @param $txt
+ * @param $encrypt_key
+ * @return string
+ */
 function passport_key($txt, $encrypt_key)
 {
     $encrypt_key = md5($encrypt_key);
@@ -42,4 +69,10 @@ function passport_key($txt, $encrypt_key)
         $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
     }
     return $tmp;
-}
\ No newline at end of file
+}
+
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
diff --git a/package/Other/Fibonacci.php b/package/Other/Fibonacci.php
index 6cec949..047f970 100644
--- a/package/Other/Fibonacci.php
+++ b/package/Other/Fibonacci.php
@@ -1,34 +1,45 @@
 
  * @date     2017/8/25
- * @license  Mozilla
+ * @license  MIT
  * -------------------------------------------------------------
  * 思路分析:
  * -------------------------------------------------------------
  * 斐波那契数列(Fibonacci Sequence)又称黄金分割数列 兔子数列
  * 指的是这样一个数列:1、1、2、3、5、8、13、21
  * 在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)。
+ */
+
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+
+/**
+ * 递归方式
  *
  * @param $n
- * @return int
+ * @return mixed
  */
-
-// recursion
-/*
-function Fibonacci($n)
+function FibonacciRecursive($n)
 {
-    if ($n <= 1 ) {
+    if ($n <= 1) {
         return $n;
     }
     return Fibonacci($n - 1) + Fibonacci($n - 2);
 }
-*/
-// 55
 
-// not recursion
+/**
+ * 非递归方式
+ *
+ * @param $n
+ * @return mixed
+ */
 function Fibonacci($n)
 {
     if ($n <= 1) {
@@ -40,5 +51,11 @@ function Fibonacci($n)
     return $fib[$n];
 }
 
+
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 echo Fibonacci(10);
-// 55
+echo FibonacciRecursive(10);
diff --git a/package/Other/GetCattle.php b/package/Other/GetCattle.php
index 4f08a22..0997ac0 100644
--- a/package/Other/GetCattle.php
+++ b/package/Other/GetCattle.php
@@ -5,7 +5,7 @@
  *
  * @author   Pu ShaoWei 
  * @date     2017/8/24
- * @license  Mozilla
+ * @license  MIT
  * -------------------------------------------------------------
  * 思路分析:见下方注释 
  * -------------------------------------------------------------
@@ -15,7 +15,16 @@
  *          15岁绝育,不再能生,
  *          20岁死亡,问n年后有多少头牛。
  *
- * @param      $n
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * getCattle
+ *
+ * @param $n
  * @return int
  */
 function getCattle($n)
@@ -32,6 +41,11 @@ function getCattle($n)
     return $num;
 }
 
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 echo '牛年共有:' . getCattle(10);
 
 /*
diff --git a/package/Other/HanoiGames.php b/package/Other/HanoiGames.php
index 10e54e1..83b1b51 100644
--- a/package/Other/HanoiGames.php
+++ b/package/Other/HanoiGames.php
@@ -5,7 +5,7 @@
  *
  * @author   Pu ShaoWei 
  * @date     2017/8/26
- * @license  Mozilla
+ * @license  MIT
  * -------------------------------------------------------------
  * 思路分析:
  * -------------------------------------------------------------
@@ -14,9 +14,7 @@
  * 第一根上面套着64个圆的金片,最大的一个在底下,其余一个比一个小,依次叠上去,
  * 庙里的众僧不倦地把它们一个个地从这根棒搬到另一根棒上,规定可利用中间的一根棒作为帮助,
  * 但每次只能搬一个,而且大的不能放在小的上面。
- *
  * 面对庞大的数字(移动圆片的次数)18446744073709551615,看来,众僧们耗尽毕生精力也不可能完成金片的移动。
- *
  * 后来,这个传说就演变为汉诺塔游戏:
  * 1.有三根杆子A,B,C。A杆上有若干碟子
  * 2.每次移动一块碟子,小的只能叠在大的上面
@@ -24,6 +22,14 @@
  * 经过研究发现,汉诺塔的破解很简单,就是按照移动规则向一个方向移动金片:
  * 如3阶汉诺塔的移动:A→C,A→B,C→B,A→C,B→A,B→C,A→C
  * 此外,汉诺塔问题也是程序设计中的经典递归问题。
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * HanoiGames
  *
  * @param $n
  * @param $x
@@ -41,6 +47,11 @@ function HanoiGames($n, $x, $y, $z)
     }
 }
 
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 HanoiGames(3, 'A', 'B', 'C');
 
 //  move disk 1 from A to C
diff --git a/package/Other/Interval.php b/package/Other/Interval.php
index 497f3e4..0b840c2 100644
--- a/package/Other/Interval.php
+++ b/package/Other/Interval.php
@@ -1,11 +1,29 @@
 
+ * @date     2018/1/11
+ * @license  MIT
+ * -------------------------------------------------------------
+ *
  * 不同概率的抽奖原理就是把0到*(比重总数)的区间分块
  * 分块的依据是物品占整个的比重,再根据随机数种子来产生0-* 中的某个数
  * 判断这个数是落在哪个区间上,区间对应的就是抽到的那个物品。
  * 随机数理论上是概率均等的,那么相应的区间所含数的多少就体现了抽奖物品概率的不同。
  */
+
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
+/**
+ * get_rand
+ *
+ * @param $proArr
+ * @return array
+ */
 function get_rand($proArr)
 {
     $result = array();
@@ -33,6 +51,9 @@ function get_rand($proArr)
 
 /**
  * 使用较多的为这个方法
+ *
+ * @param $proArr
+ * @return array
  */
 function get_rand1($proArr)
 {
@@ -56,6 +77,11 @@ function get_rand1($proArr)
     return $result;
 }
 
+
+// +--------------------------------------------------------------------------
+// | 方案测试    | php `this.php` || PHPStorm -> 右键 -> Run `this.php`
+// +--------------------------------------------------------------------------
+
 $arr = array(
     array('id' => 1, 'name' => '特等奖', 'v' => 1),
     array('id' => 2, 'name' => '一等奖', 'v' => 5),
diff --git a/package/Other/Maze.php b/package/Other/Maze.php
index e027755..1efd0a0 100644
--- a/package/Other/Maze.php
+++ b/package/Other/Maze.php
@@ -1,5 +1,19 @@
 
+ * @date     2018/1/11
+ * @license  MIT
+ * -------------------------------------------------------------
+ *   构造迷宫二维数组
+ */
+
+// +--------------------------------------------------------------------------
+// | 解题方式    | 这儿,可能有用的解决方案
+// +--------------------------------------------------------------------------
+
 
 //迷宫一
 for ($l = 0; $l <= 5; $l++) {
@@ -21,6 +35,18 @@
 }
 echo '


寻地址算法的实现:
'; +/** + * findPath + * + * @param $i + * @param $j + * @param $dir + * @param $arr + * @param $iline + * @param $jline + * @param $dirline + * @return int + */ function findPath($i, $j, $dir, $arr, $iline, $jline, $dirline) { @@ -258,6 +284,5 @@ function findPath($i, $j, $dir, $arr, $iline, $jline, $dirline) } $a[] = $b[] = $c[] = 0; - echo '初始值=>节点:($i=1,$j=1),方向:($dir=0).

'; findPath(1, 1, 0, $arr, $a, $b, $c); \ No newline at end of file diff --git a/package/Other/MonkeyKing.php b/package/Other/MonkeyKing.php index c1fca9f..8e25abd 100644 --- a/package/Other/MonkeyKing.php +++ b/package/Other/MonkeyKing.php @@ -5,12 +5,18 @@ * * @author Pu ShaoWei * @date 2017/8/23 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:约瑟夫环问题 * ------------------------------------------------------------- * 有M个monkey ,转成一圈,第一个开始数数,数到第N个出圈,下一个再从1开始数,再数到第N个出圈,直到圈里只剩最后一个就是大王 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + + class MonkeyKing { protected $next; @@ -38,7 +44,7 @@ public static function whoIsKing($count, $num) { // 构造单向循环链表 $current = $first = new MonkeyKing(1); - for ($i = 2; $i <= $count; $i++){ + for ($i = 2; $i <= $count; $i++) { $current->next = new MonkeyKing($i); $current = $current->next; } @@ -48,7 +54,7 @@ public static function whoIsKing($count, $num) $current = $first; // 定义一个数字 $cn = 1; - while ($current !== $current->next){ + while ($current !== $current->next) { $cn++; if ($cn == $num) { $current->next = $current->next->next; @@ -61,33 +67,59 @@ public static function whoIsKing($count, $num) } } -// 共10个猴子每3个出圈 -var_dump(MonkeyKing::whoIsKing(10, 3)); - -function whoIsKing($n,$m){ +/** + * whoIsKing + * + * @param $n + * @param $m + * @return int + */ +function whoIsKing($n, $m) +{ $r = 0; - for ($i=2; $i <= $n ; $i++) { + for ($i = 2; $i <= $n; $i++) { $r = ($r + $m) % $i; } - return $r+1; + return $r + 1; } -var_dump(whoIsKing(10,3)); - -function king($n, $m){ +/** + * king + * + * @param $n + * @param $m + * @return mixed + */ +function king($n, $m) +{ $monkeys = range(1, $n); - $i=0; - $k=$n; - while (count($monkeys)>1) { - if(($i+1)%$m==0) { + $i = 0; + $k = $n; + while (count($monkeys) > 1) { + if (($i + 1) % $m == 0) { unset($monkeys[$i]); } else { - array_push($monkeys,$monkeys[$i]); + array_push($monkeys, $monkeys[$i]); unset($monkeys[$i]); } $i++; } return current($monkeys); } + + + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + + +// 共10个猴子每3个出圈 +var_dump(MonkeyKing::whoIsKing(10, 3)); + + +var_dump(whoIsKing(10, 3)); + + $a = king(10, 3); var_dump($a); \ No newline at end of file diff --git a/package/Other/OnlyNumbers.php b/package/Other/OnlyNumbers.php index e211a4a..a406139 100644 --- a/package/Other/OnlyNumbers.php +++ b/package/Other/OnlyNumbers.php @@ -5,14 +5,23 @@ * * @author Pu ShaoWei * @date 2017/8/30 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:快排同时做唯一标示 * ------------------------------------------------------------- * 一个数组里只有唯一一个元素是不同于别的元素,其余元素是两两相等如何得到这个元素 * + */ + +// +-------------------------------------------------------------------------- +// | 解题方式 +// +-------------------------------------------------------------------------- + +/** + * OnlyNumbers + * * @param array $container - * @return mixed + * @return array|bool */ function OnlyNumbers(array $container) { @@ -31,9 +40,6 @@ function OnlyNumbers(array $container) return !empty($exist) ? array_keys($exist)[0] : false; } -var_dump(OnlyNumbers([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); - - // +---------------------------------------------------------------------- // | 方法二 // +---------------------------------------------------------------------- @@ -51,4 +57,9 @@ function OnlyNumbersV2(array $container) return isset($res[1]) ? $res[1] : null; } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + +var_dump(OnlyNumbers([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); var_dump(OnlyNumbersV2([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); diff --git a/package/Other/PointInTriangle.php b/package/Other/PointInTriangle.php index 2794c3c..60b1452 100644 --- a/package/Other/PointInTriangle.php +++ b/package/Other/PointInTriangle.php @@ -1,14 +1,36 @@ + * @date 2018/1/11 + * @license MIT + * ------------------------------------------------------------- + * 利用向量叉集判断一个点是否在三角形中 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + class PointInTriangle { + /** + * @var array + */ protected $point; + /** + * @var array + */ protected $triangle; + /** + * PointInTriangle constructor. + * + * @param array $point + * @param array $triangle + */ public function __construct(array $point, array $triangle) { $this->point = $point; @@ -18,19 +40,37 @@ public function __construct(array $point, array $triangle) $this->triangle = $triangle; } - //向量叉集计算 + /** + * 向量叉集计算 + * + * @param $a + * @param $b + * @param $p + * @return mixed + */ private function cross($a, $b, $p) { return ($b['x'] - $a['x']) * ($p['y'] - $a['y']) - ($b['y'] - $a['y']) * ($p['x'] - $a['x']); } - //判断是否在左边 + /** + * 判断是否在左边 + * + * @param $a + * @param $b + * @param $p + * @return bool + */ private function toLeft($a, $b, $p) { return $this->cross($a, $b, $p) > 0; } - //开始构造三角形 + /** + * 开始构造三角形 + * + * @return string + */ public function inTriangle() { $res = $this->toLeft($this->triangle[0], $this->triangle[1], $this->point); @@ -49,6 +89,11 @@ public function inTriangle() } } + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + $point = [ 'x' => 4, 'y' => 1 @@ -64,6 +109,5 @@ public function inTriangle() ]; $obj = new PointInTriangle($point1, $triangle); - var_dump($obj->inTriangle()); exit; \ No newline at end of file diff --git a/package/Other/PokerGames.php b/package/Other/PokerGames.php index 4daa248..da0aa9b 100644 --- a/package/Other/PokerGames.php +++ b/package/Other/PokerGames.php @@ -6,41 +6,74 @@ * @author Pu ShaoWei * @date 2017/9/18 * @license MIT + * ------------------------------------------------------------- + * 随机玩法 */ -$card_num = 54;//牌数 + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + +/** + * washCard + * + * @param $card_num + * @return array + */ function washCard($card_num) { $cards = range(1, $card_num); for ($i = $card_num - 1; $i > 0; $i--) { - $rnd = rand(0,$i - 1); - list($cards[$rnd],$cards[$i]) = array($cards[$i],$cards[$rnd]); + $rnd = rand(0, $i - 1); + list($cards[$rnd], $cards[$i]) = array ($cards[$i], $cards[$rnd]); } return $cards; } -// 测试: -//var_dump(washCard($card_num));die; /** * PokerGames 纯属娱乐,有空再优化, 这样够随机吧 - * - * @uses description - * @version 1.0 - * @author Pu ShaoWei */ class PokerGames { + /** + * + */ const RANDOM = "https://www.random.org/integers/?num=%d&min=1&max=%d&col=1&base=10&format=plain&rnd=new"; - const LIMIT = 10; + /** + * + */ + const LIMIT = 10; + /** + * @var + */ protected $resources; + /** + * @var + */ protected $tally; + /** + * @var float + */ protected $i; + /** + * @var + */ protected $count; + /** + * @var bool + */ protected $clear; + /** + * @var array + */ protected $container = array (); - protected $poker = array (); + /** + * @var array + */ + protected $poker = array (); /** * PokerGames constructor. @@ -164,4 +197,10 @@ public function makeRand($max) } } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + +$card_num = 54;//牌数 +var_dump(washCard($card_num)); new PokerGames(); diff --git a/package/Other/StealingApples.php b/package/Other/StealingApples.php index 3bd223d..5d821a3 100644 --- a/package/Other/StealingApples.php +++ b/package/Other/StealingApples.php @@ -5,7 +5,7 @@ * * @author Pu ShaoWei * @date 2017/8/26 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析: * ------------------------------------------------------------- @@ -14,8 +14,13 @@ * 没想到其他四人也都是这么想的,都如第一个人一样分成5份把多的那一个扔给了猴,偷走了1/5。 * 第二天,大家分赃,也是分成5份多一个扔给猴了。最后一人分了一份。 * 问:共有多少苹果?N 个人呢? + * ------------------------------------------------------------- */ +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + $i = 1; while (true) { if ($i % 5 == 1) { @@ -69,3 +74,8 @@ } //15621 + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + diff --git a/package/Other/TraversalOfBinaryTree.php b/package/Other/TraversalOfBinaryTree.php deleted file mode 100644 index 6a29113..0000000 --- a/package/Other/TraversalOfBinaryTree.php +++ /dev/null @@ -1,97 +0,0 @@ - - * @link https://github.com/openset - * @date 2018/01/23 - */ -class Node -{ - public $value; - public $left; - public $right; -} - -//先序遍历 根节点 ---> 左子树 ---> 右子树 -function DLROrder($root) -{ - $stack = array(); - array_push($stack, $root); - while (!empty($stack)) { - $center_node = array_pop($stack); - echo $center_node->value . ' ';//先输出根节点 - if ($center_node->right != null) { - array_push($stack, $center_node->right);//压入左子树 - } - if ($center_node->left != null) { - array_push($stack, $center_node->left); - } - } -} - -//中序遍历,左子树---> 根节点 ---> 右子树 -function LDROrder($root) -{ - $stack = array(); - $center_node = $root; - while (!empty($stack) || $center_node != null) { - while ($center_node != null) { - array_push($stack, $center_node); - $center_node = $center_node->left; - } - - $center_node = array_pop($stack); - echo $center_node->value . " "; - - $center_node = $center_node->right; - } -} - -//后序遍历,左子树 ---> 右子树 ---> 根节点 -function LRDOrder($root) -{ - $stack = array(); - $outstack = array(); - array_push($stack, $root); - while (!empty($stack)) { - $center_node = array_pop($stack); - array_push($outstack, $center_node);//最先压入根节点,最后输出 - if ($center_node->left != null) { - array_push($stack, $center_node->left); - } - if ($center_node->right != null) { - array_push($stack, $center_node->right); - } - } - - while (!empty($outstack)) { - $center_node = array_pop($outstack); - echo $center_node->value . ' '; - } - -} - -$a = new Node(); -$b = new Node(); -$c = new Node(); -$d = new Node(); -$e = new Node(); -$f = new Node(); -$a->value = 'A'; -$b->value = 'B'; -$c->value = 'C'; -$d->value = 'D'; -$e->value = 'E'; -$f->value = 'F'; -$a->left = $b; -$a->right = $c; -$b->left = $d; -$c->left = $e; -$c->right = $f; - -DLROrder($a);//A B D C E F - -LDROrder($a);//D B A E C F - -LRDOrder($a);//D B E F C A \ No newline at end of file diff --git a/package/Other/kmp.php b/package/Other/kmp.php index 2dc0114..09238ae 100644 --- a/package/Other/kmp.php +++ b/package/Other/kmp.php @@ -1,16 +1,27 @@ + * @date 2018/1/11 + * @license MIT + * ------------------------------------------------------------- * KMP算法是一种改进的字符串匹配算法 * KMP精要:KMP在进行朴素匹配时,如果发现不匹配字符时,通过对已经匹配的那部分字符串的最大前缀来快速找到下一个模式串需要匹配的位置。 * KMP对模式进行预处理时间复杂度O(m),匹配时间复杂度O(n),总的KMP时间复杂度为O(m+n)。 * 参考 字符串匹配的KMP算法 — 阮一峰 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + class KMP { - public $haystack; - public $needle; + public $haystack; + public $needle; private $_haystackLen; private $_needleLen; private $_matchTable; @@ -20,12 +31,12 @@ class KMP function __construct($haystack, $needle) { $this->haystack = $haystack; - $this->needle = $needle; + $this->needle = $needle; //初始化一些参数 $this->_haystackLen = $this->getLen($this->haystack); - $this->_needleLen = $this->getLen($this->needle); - $this->_matchTable = $this->getMatchTable(); - $this->_isMatch = false; + $this->_needleLen = $this->getLen($this->needle); + $this->_matchTable = $this->getMatchTable(); + $this->_isMatch = false; } @@ -41,8 +52,8 @@ public function strpos() if (strcmp($this->haystack[$haystackIdx], $this->needle[$needIdx]) <> 0) { if ($matchNum > 0) { $lastMatchValue = $this->getLastMatchValue($needIdx - 1); - $haystackIdx += $this->getStep($matchNum, $lastMatchValue); - $matchNum = 0; + $haystackIdx += $this->getStep($matchNum, $lastMatchValue); + $matchNum = 0; } else { $haystackIdx++; } @@ -75,13 +86,13 @@ private function getMatchTable() $matchTable = []; for ($i = 0; $i < $this->_needleLen; $i++) { $intersectLen = 0; - $nowStr = mb_substr($this->needle, 0, $i + 1, 'utf-8'); - $preFixArr = $this->getPreFix($nowStr); - $sufFixArr = $this->getSufFix($nowStr); + $nowStr = mb_substr($this->needle, 0, $i + 1, 'utf-8'); + $preFixArr = $this->getPreFix($nowStr); + $sufFixArr = $this->getSufFix($nowStr); if ($preFixArr && $sufFixArr) { $intersectArr = array_intersect($preFixArr, $sufFixArr); if (!empty($intersectArr)) { - $intersect = array_pop($intersectArr); + $intersect = array_pop($intersectArr); $intersectLen = mb_strlen($intersect, 'utf-8'); } } @@ -127,15 +138,20 @@ private function getLastMatchValue($index) { return isset($this->_matchTable[$index]) ? $this->_matchTable[$index] : 0; } + } -$str = 'a b a c a a b a c a b a c a b a a b b'; +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + +$str = 'a b a c a a b a c a b a c a b a a b b'; $subStr = 'a b a c a b'; -$kmp = new KMP($str, $subStr); +$kmp = new KMP($str, $subStr); var_dump($kmp->strpos()); $kmp->haystack = 'pull requests'; -$kmp->needle = 'sts'; +$kmp->needle = 'sts'; var_dump($kmp->strpos()); $kmp->haystack = 'i love you'; -$kmp->needle = 'hate'; +$kmp->needle = 'hate'; var_dump($kmp->strpos()); \ No newline at end of file diff --git a/package/Query/BinaryQuery.php b/package/Query/BinaryQuery.php index 5b5051c..f8d0560 100644 --- a/package/Query/BinaryQuery.php +++ b/package/Query/BinaryQuery.php @@ -1,9 +1,11 @@ * @date 2017/6/17 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:数组中间的值floor((low+top)/2)  * ------------------------------------------------------------- @@ -13,6 +15,10 @@ * 重复第二步操作直至找出目标数字 */ +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + /** * 非递归版 二分查找 * @@ -20,45 +26,61 @@ * @param $search * @return int|string */ -function BinaryQuery( array $container,$search){ - $top = count($container); - $low = 0; - while ( $low <= $top){ - $mid = intval( floor( ($low + $top ) / 2) ); - if( !isset($container[$mid]) ) return '没找着哦'; - if( $container[$mid] == $search) return $mid; - $container[$mid] < $search && $low = $mid+1; - $container[$mid] > $search && $top = $mid-1; +function BinaryQuery(array $container, $search) +{ + $top = count($container); + $low = 0; + while ($low <= $top) { + $mid = intval(floor(($low + $top) / 2)); + if (!isset($container[$mid])) { + return '没找着哦'; + } + if ($container[$mid] == $search) { + return $mid; + } + $container[$mid] < $search && $low = $mid + 1; + $container[$mid] > $search && $top = $mid - 1; } } -// var_dump( BinaryQuery([0,1,2,3,4,5,6,7,8,9],9) ); -/* - * double(8) - */ + /** * 递归版 二分查找 + * * @param array $container * @param $search * @param int $low * @param string $top * @return int|string */ -function BinaryQueryRecursive(array $container,$search,$low = 0,$top = 'default'){ - $top == 'default' && $top = count($container ); - if( $low <= $top ){ - $mid = intval( floor( $low + $top ) /2 ); - if( !isset($container[$mid]) ) return '没找着哦'; - if( $container[$mid] == $search) return $mid; - if( $container[$mid] < $search ){ - return BinaryQueryRecursive($container,$search,$mid+1,$top); - }else{ - return BinaryQueryRecursive($container,$search,$low,$mid-1); - } - } +function BinaryQueryRecursive(array $container, $search, $low = 0, $top = 'default') +{ + $top == 'default' && $top = count($container); + if ($low <= $top) { + $mid = intval(floor($low + $top) / 2); + if (!isset($container[$mid])) { + return '没找着哦'; + } + if ($container[$mid] == $search) { + return $mid; + } + if ($container[$mid] < $search) { + return BinaryQueryRecursive($container, $search, $mid + 1, $top); + } else { + return BinaryQueryRecursive($container, $search, $low, $mid - 1); + } + } } - var_dump( BinaryQueryRecursive([0,1,2,3,4,5,6,7,8,9],9) ); +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + +var_dump(BinaryQuery([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)); +/* + * double(8) + */ +var_dump(BinaryQueryRecursive([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)); /* array(7) { [0] => diff --git a/package/Query/BinaryTree.php b/package/Query/BinaryTree.php index 05ac1ba..38cb234 100644 --- a/package/Query/BinaryTree.php +++ b/package/Query/BinaryTree.php @@ -1,13 +1,13 @@ * @date 2017/8/25 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析: * ------------------------------------------------------------- - * */ +#TODO 2018-2-14 这儿没写完 \ No newline at end of file diff --git a/package/Query/FibonacciQuery.php b/package/Query/FibonacciQuery.php index 4e1b3d0..a58d630 100644 --- a/package/Query/FibonacciQuery.php +++ b/package/Query/FibonacciQuery.php @@ -1,27 +1,33 @@ * @date 2017/8/23 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:斐波那契查找 利用黄金分割原理 * ------------------------------------------------------------- - * * $num == $container[$mid],直接返回 * $num < $container[$mid],新范围是第 $low 个到 $mid-1 个,此时范围个数为 produced($key-1)-1 个 * $num > $container[$mid],新范围是第 $mid+1 个到 $high 个,此时范围个数为 produced($key-2)-1 个 */ -class FibonacciQuery{ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + +class FibonacciQuery +{ /** * FibonacciQuery constructor. * * @param array $container * @param $num */ - public function __construct(array $container,$num) + public function __construct(array $container, $num) { $count = count($container); $lower = $key = $result = 0; @@ -32,26 +38,28 @@ public function __construct(array $container,$num) } //将不满的数值补全,补的数值为数组的最后一位 for ($j = $count; $j < $this->produced($key) - 1; $j++) { - $container[ $j ] = $container[ $count - 1 ]; + $container[$j] = $container[$count - 1]; } //查找开始 while ($lower <= $high) { //计算当前分隔的下标 $mid = $lower + $this->produced($key - 1) - 1; - if ($num < $container[ $mid ]) { - $high = $mid - 1; - $key -= 1; //斐波那契数列数列下标减一位 - }else if ($num > $container[ $mid ]) { - $lower = $mid + 1; - $key -= 2; //斐波那契数列数列下标减两位 + if ($num < $container[$mid]) { + $high = $mid - 1; + $key -= 1; //斐波那契数列数列下标减一位 + } else if ($num > $container[$mid]) { + $lower = $mid + 1; + $key -= 2; //斐波那契数列数列下标减两位 } if ($mid <= $count - 1) { - $result = $mid; break; + $result = $mid; + break; } else { //这里$mid大于$count-1说明是补全数值,返回$count-1 - $result = $count - 1; break; + $result = $count - 1; + break; } } - var_dump( $result ); + var_dump($result); } /** @@ -62,11 +70,15 @@ public function __construct(array $container,$num) */ public function produced($length) { - if($length < 2){ + if ($length < 2) { return ($length == 0 ? 0 : 1); } return $this->produced($length - 1) + $this->produced($length - 2); } } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file diff --git a/package/Query/InsertQuery.php b/package/Query/InsertQuery.php index f244fd8..27c0800 100644 --- a/package/Query/InsertQuery.php +++ b/package/Query/InsertQuery.php @@ -1,10 +1,10 @@ * @date 2017/8/25 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:对于数组长度比较大,关键字分布又是比较均匀的来说,插值查找的效率比折半查找的效率高 * ------------------------------------------------------------- @@ -14,6 +14,9 @@ * */ +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- /** * insertQuery * @@ -51,5 +54,9 @@ function insertQuery(array $container, $num) return false; } + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- echo insertQuery([4, 5, 7, 8, 9, 10, 8], 8); // 6 \ No newline at end of file diff --git a/package/Query/QulickQuery.php b/package/Query/QuickQuery.php similarity index 77% rename from package/Query/QulickQuery.php rename to package/Query/QuickQuery.php index cbbde35..54b3a0d 100644 --- a/package/Query/QulickQuery.php +++ b/package/Query/QuickQuery.php @@ -1,20 +1,19 @@ * @date 2017/8/23 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:数组中间的值floor((low+top)/2)  * ------------------------------------------------------------- * 重复第二步操作直至找出目标数字 - * */ /** - * QulickQuery + * QuickQuery * * @param $array * @param $k @@ -22,7 +21,7 @@ * @param int $high * @return int */ -function QulickQuery($array, $k, $low = 0, $high = 0) +function QuickQuery($array, $k, $low = 0, $high = 0) { //判断是否为第一次调用 if (count($array) != 0 and $high == 0) { @@ -33,9 +32,9 @@ function QulickQuery($array, $k, $low = 0, $high = 0) //取$low和$high的中间值 $mid = intval(($low + $high) / 2); //如果找到则返回 - if ($array[ $mid ] == $k) { + if ($array[$mid] == $k) { return $mid; - }else if ($k < $array[ $mid ]) {//如果没有找到,则继续查找 + } else if ($k < $array[$mid]) {//如果没有找到,则继续查找 return QulickQuery($array, $k, $low, $mid - 1); } else { return QulickQuery($array, $k, $mid + 1, $high); @@ -44,4 +43,4 @@ function QulickQuery($array, $k, $low = 0, $high = 0) return -1; } -echo QulickQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file +echo QuickQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file diff --git a/package/Sort/BubbleSort.php b/package/Sort/BubbleSort.php index d382668..b93a0ca 100644 --- a/package/Sort/BubbleSort.php +++ b/package/Sort/BubbleSort.php @@ -1,9 +1,11 @@ * @date 2017/6/16 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:就是像冒泡一样,每次从数组当中 冒一个最大的数出来。  * ------------------------------------------------------------- @@ -14,6 +16,10 @@ * */ +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + /** * BubbleSort * @@ -35,6 +41,10 @@ function BubbleSort(array $container) return $container; } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + var_dump(BubbleSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); /* diff --git a/package/Sort/HeapSort.php b/package/Sort/HeapSort.php index 0523a70..0dd9488 100644 --- a/package/Sort/HeapSort.php +++ b/package/Sort/HeapSort.php @@ -1,7 +1,8 @@ * @date 2017/10/9 * @license MIT @@ -13,6 +14,13 @@ * 大根堆的要求是每个节点的值都不大于其父节点的值,即A[PARENT[i]] >= A[i]。在数组的非降序排序中,需要使用的就是大根堆, * 因为根据大根堆的要求可知,最大的值一定在堆顶。 */ + + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + + class HeapSort { /** @@ -106,6 +114,10 @@ public function swap(&$left, &$right) } } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + $array = array (4, 21, 41, 2, 53, 1, 213, 31, 21, 423, 56); $result = (new HeapSort($array))->run(); var_dump($result); diff --git a/package/Sort/InsertSort.php b/package/Sort/InsertSort.php index 01b03da..aa3a0c5 100644 --- a/package/Sort/InsertSort.php +++ b/package/Sort/InsertSort.php @@ -1,10 +1,10 @@ * @date 2017/6/17 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。 * ------------------------------------------------------------- @@ -16,6 +16,11 @@ * */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + /** * InsertSort * @@ -38,6 +43,11 @@ function InsertSort(array $container) } return $container; } + + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- var_dump(InsertSort([3, 12, 42, 1, 24, 5, 346, 7])); /* diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 88beb0c..6e8fbc1 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -1,10 +1,11 @@ * @date 2017/7/22 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析: * ------------------------------------------------------------- @@ -14,6 +15,12 @@ * 归并排序的算法我们通常用递归实现,先把待排序区间[s,t]以中点二分,接着把左边子区间排序,再把右边子区间排序, * 最后把左区间和右区间用一次归并操作合并成有序的区间[s,t] */ + + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + class MergeSort { /** @@ -90,6 +97,12 @@ public function mergeArray(&$arr, $left, $center, $right) } } + + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + //do some test: new mergeSort([4, 7, 6, 3, 9, 5, 8]); diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index ff38a68..6976133 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -1,9 +1,10 @@ * @date 2017/6/17 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:从数列中挑出一个元素,称为 “基准”(pivot)  * ------------------------------------------------------------- @@ -12,13 +13,18 @@ * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + /** - * QulickSort + * QuickSort * * @param array $container * @return array */ -function QulickSort(array $container) +function QuickSort(array $container) { $count = count($container); if ($count <= 1) { @@ -32,12 +38,17 @@ function QulickSort(array $container) $right[] = $container[$i]; } } - $left = QulickSort($left); - $right = QulickSort($right); + $left = QuickSort($left); + $right = QuickSort($right); return array_merge($left, [$container[0]], $right); } -var_dump(QulickSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + + +var_dump(QuickSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); /** * array(10) { [0] => diff --git a/package/Sort/SelectSort.php b/package/Sort/SelectSort.php index f218293..fd9e8ad 100644 --- a/package/Sort/SelectSort.php +++ b/package/Sort/SelectSort.php @@ -1,10 +1,11 @@ * @date 2017/6/17 - * @license Mozilla + * @license MIT * ------------------------------------------------------------- * 思路分析:选择排序是不稳定的排序方法 * ------------------------------------------------------------- @@ -12,6 +13,10 @@ * 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- /** * SelectSort * @@ -37,6 +42,11 @@ function SelectSort(array $container) return $container; } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + + var_dump(SelectSort([3, 12, 42, 1, 24, 5, 346, 7])); /* diff --git a/package/Sort/ShellSort.php b/package/Sort/ShellSort.php index 4fc7db0..7b7aad5 100644 --- a/package/Sort/ShellSort.php +++ b/package/Sort/ShellSort.php @@ -1,6 +1,7 @@ * @date 2017/7/22 * @license Mozilla @@ -11,6 +12,12 @@ * 当然每次循环的时候,h也是递减的(h=h/n)。第一次循环就是从下标为h开始。希尔排序的一个思想就是,分成小组去排序。 */ + +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + + /** * ShellSort * @@ -36,6 +43,12 @@ function ShellSort(array $container) return $container; } -//var_dump(ShellSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + + +var_dump(ShellSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); diff --git a/package/Sort/ShuttleSort.php b/package/Sort/ShuttleSort.php index b4200ac..3afdf47 100644 --- a/package/Sort/ShuttleSort.php +++ b/package/Sort/ShuttleSort.php @@ -1,7 +1,7 @@ * @date 2017/12/19 @@ -15,6 +15,11 @@ */ +// +-------------------------------------------------------------------------- +// | 解题方式 | 这儿,可能有用的解决方案 +// +-------------------------------------------------------------------------- + + /** * ShuttleSort * @@ -65,4 +70,9 @@ function ShuttleSort(array $data) return $data; } +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- + + var_dump(ShuttleSort([6, 13, 21, 99, 18, 2, 25, 33, 19, 84])); diff --git a/package/Structure/KitchenQueue.php b/package/Structure/KitchenQueue.php index 27a4a73..80e87fd 100644 --- a/package/Structure/KitchenQueue.php +++ b/package/Structure/KitchenQueue.php @@ -11,8 +11,9 @@ * @author Pu ShaoWei * @date 2017/12/3 * @version 1.0 - * @license QiHoo + * @license MIT */ + class KitchenQueue { /** diff --git a/package/Structure/LinearChain.php b/package/Structure/LinearChain.php index 909d335..ef6b237 100644 --- a/package/Structure/LinearChain.php +++ b/package/Structure/LinearChain.php @@ -35,7 +35,6 @@ * - 存储链表中结点的一组任意的存储单元可以是连续的,也可以是不连续的,甚至是零散分布在内存中的任意位置上 * - 链表中结点的逻辑顺序和物理顺序不一定相同 * ------------------------------------------------------------- - * @param array */ class LinearChain { diff --git a/package/Tools/SystemSwitch.php b/package/Tools/SystemSwitch.php index 135419e..598983b 100644 --- a/package/Tools/SystemSwitch.php +++ b/package/Tools/SystemSwitch.php @@ -9,7 +9,6 @@ * ------------------------------------------------------------- * 十进制整数转换为二、八、十六进制整数 n = (n div d) * d + n mod d * ------------------------------------------------------------- - * @param array */ class SystemSwitch { From e3a961e723d22f62bf31457b05b2c6160c282196 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Wed, 14 Feb 2018 13:50:49 +0800 Subject: [PATCH 083/127] :tada: Happy New Year! --- README.md | 4 ++-- package/{Tools => Features}/SystemSwitch.php | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename package/{Tools => Features}/SystemSwitch.php (100%) diff --git a/README.md b/README.md index 752325c..9847919 100644 --- a/README.md +++ b/README.md @@ -215,11 +215,11 @@ left|right ## 致谢 感谢以下朋友的issue或pull request: - - [hailwood ](https://github.com/hailwood) - [zhangxuanru](https://github.com/zhangxuanru) - [ifreesec](https://github.com/ifreesec) - [openset](https://github.com/openset) - +- [openset](https://github.com/openset) +- [Neroxiezi](https://github.com/Neroxiezi) ## License MIT diff --git a/package/Tools/SystemSwitch.php b/package/Features/SystemSwitch.php similarity index 100% rename from package/Tools/SystemSwitch.php rename to package/Features/SystemSwitch.php From 85e1aa12038163527d216be1f9366ce8aa15c182 Mon Sep 17 00:00:00 2001 From: Openset Date: Sat, 24 Feb 2018 14:41:50 +0800 Subject: [PATCH 084/127] Add: OnlyNumbersV3 --- package/Other/OnlyNumbers.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/package/Other/OnlyNumbers.php b/package/Other/OnlyNumbers.php index a406139..4c88b2b 100644 --- a/package/Other/OnlyNumbers.php +++ b/package/Other/OnlyNumbers.php @@ -57,9 +57,30 @@ function OnlyNumbersV2(array $container) return isset($res[1]) ? $res[1] : null; } +// +---------------------------------------------------------------------- +// | 方法三 +// +---------------------------------------------------------------------- +/** + * @author Openset + * @link https://github.com/openset + * @date 2018/2/24 + * @param array $container + * @return null + */ +function OnlyNumbersV3(array $container) +{ + $num = $container[0]; + foreach ($container as $k => $v) { + if ($k > 0) $num ^= $v; + } + + return $num; +} + // +-------------------------------------------------------------------------- // | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` // +-------------------------------------------------------------------------- var_dump(OnlyNumbers([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); var_dump(OnlyNumbersV2([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); +var_dump(OnlyNumbersV3([11, 22, 22, 11, 5, 63, 13, 5, 63, 18, 89, 13, 89])); From 4aa7481003578f1236ec423347a88bb4c018e7de Mon Sep 17 00:00:00 2001 From: Openset Date: Sat, 24 Feb 2018 15:37:32 +0800 Subject: [PATCH 085/127] Update: OnlyNumbersV3 --- package/Other/OnlyNumbers.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package/Other/OnlyNumbers.php b/package/Other/OnlyNumbers.php index 4c88b2b..f076a9d 100644 --- a/package/Other/OnlyNumbers.php +++ b/package/Other/OnlyNumbers.php @@ -69,9 +69,9 @@ function OnlyNumbersV2(array $container) */ function OnlyNumbersV3(array $container) { - $num = $container[0]; - foreach ($container as $k => $v) { - if ($k > 0) $num ^= $v; + $num = 0; + foreach ($container as $v) { + $num ^= $v; } return $num; From 8e0ed60eb47e773e58a1a79de229aa33ffd00733 Mon Sep 17 00:00:00 2001 From: LXZ Date: Mon, 12 Mar 2018 10:39:56 +0800 Subject: [PATCH 086/127] =?UTF-8?q?=E6=9B=B4=E6=96=B0READM.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 9847919..5e3f308 100644 --- a/README.md +++ b/README.md @@ -219,7 +219,6 @@ left|right - [zhangxuanru](https://github.com/zhangxuanru) - [ifreesec](https://github.com/ifreesec) - [openset](https://github.com/openset) -- [openset](https://github.com/openset) - [Neroxiezi](https://github.com/Neroxiezi) ## License MIT From aa129adf4ca40d7b4caa4513613c4d2897fb5e4f Mon Sep 17 00:00:00 2001 From: LXZ Date: Mon, 12 Mar 2018 10:42:03 +0800 Subject: [PATCH 087/127] =?UTF-8?q?=E6=9B=B4=E6=96=B0READM.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README-EN.md b/README-EN.md index 1b9e445..965118e 100644 --- a/README-EN.md +++ b/README-EN.md @@ -133,6 +133,6 @@ Thanks for the issue or pull request of the following friends: - [zhangxuanru](https://github.com/zhangxuanru) - [ifreesec](https://github.com/ifreesec) - [openset](https://github.com/openset) - +- [Neroxiezi](https://github.com/Neroxiezi) ## License MIT \ No newline at end of file From 2803ee8c097abba1264117299b5fe07e95b501e4 Mon Sep 17 00:00:00 2001 From: LXZ Date: Tue, 13 Mar 2018 15:09:12 +0800 Subject: [PATCH 088/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=B4=AA=E5=BF=83?= =?UTF-8?q?=E7=AE=97=E6=B3=95=E4=B9=8B=E8=83=8C=E5=8C=85=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/Knapsack.php | 83 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 package/Other/Knapsack.php diff --git a/README-EN.md b/README-EN.md index 965118e..f20bd1d 100644 --- a/README-EN.md +++ b/README-EN.md @@ -56,6 +56,7 @@ │ ├── TraversalOfBinary.php │ ├── PointInTriangle.php │ └── BigSmallReplace.php + │ └── Knapsack.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index 5e3f308..583e2ba 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ │ ├── kmp.php 算法导论-KMP算法 │ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 + │ ├── Knapsack.php 贪心算法之背包问题实现 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ ├──LICENSE diff --git a/package/Other/Knapsack.php b/package/Other/Knapsack.php new file mode 100644 index 0000000..879f844 --- /dev/null +++ b/package/Other/Knapsack.php @@ -0,0 +1,83 @@ +weight = $weight; + $this->value = $value; + $this->total_weight = $total_weight; + } + + # 贪心算法去算最佳的物品 + public function bag() + { + $product = []; + foreach ($this->weight as $k => $v) { + $product[] = ['weight' => $v, 'value' => $this->value[$k], 'pj_value' => ($this->value[$k] / $v)]; + } + + $total_value = 0; + //按价值比去排序 + $sorted_product = $this->sortByPj_value($product); + //print_r($sorted_product); + $total = 0; + foreach ($sorted_product as $k => $v) { + if ($total + $v['weight'] <= $this->total_weight) { + + $total_value += $v['value']; + + $total += $v['weight']; + } elseif ($total < $this->total_weight) { + + for ($j = $k + 1; $j < count($sorted_product); $j++) { + if (($sorted_product[$j]['weight'] + $total) <= 150) { + $total_value += $sorted_product[$j]['value']; + $total += $sorted_product[$j]['weight']; + } + } + + break; + + }else{ + + break; + } + } + + return [$total ,$total_value ]; + + } + + private function sortByPj_value($product) + { + for ($i = 0; $i < count($product); $i++) { + for ($j = $i + 1; $j < count($product); $j++) { + if ($product[$i]['pj_value'] < $product[$j]['pj_value']) { + $temp = $product[$i]; + $product[$i] = $product[$j]; + $product[$j] = $temp; + } + } + + } + return $product; + } +} + +$obj = new Knapsack([35, 30, 60, 50, 40, 15, 10],[10, 40, 30, 50, 35, 40, 30],150); +var_dump($obj->bag()); + + + From 9741095706a735ff51ee6e336343835da590415d Mon Sep 17 00:00:00 2001 From: LXZ Date: Wed, 14 Mar 2018 10:35:53 +0800 Subject: [PATCH 089/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Facebook=E9=9D=A2?= =?UTF-8?q?=E8=AF=95=E7=AE=97=E6=B3=95=E4=B9=8B=E5=B2=9B=E5=B1=BF=E5=91=A8?= =?UTF-8?q?=E9=95=BF=E7=AE=97=E6=B3=95php=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/Solution.php | 63 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 package/Other/Solution.php diff --git a/README-EN.md b/README-EN.md index f20bd1d..42a71f7 100644 --- a/README-EN.md +++ b/README-EN.md @@ -57,6 +57,7 @@ │ ├── PointInTriangle.php │ └── BigSmallReplace.php │ └── Knapsack.php + │ └── Solution.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index 583e2ba..0fdd9a7 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 │ ├── Knapsack.php 贪心算法之背包问题实现 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow + │ └── Solution.php Facebook面试题之岛屿周长算法 │ ├──LICENSE └──README.md diff --git a/package/Other/Solution.php b/package/Other/Solution.php new file mode 100644 index 0000000..27aca0c --- /dev/null +++ b/package/Other/Solution.php @@ -0,0 +1,63 @@ +grid = $grid; + $this->islandPerimeter(); + } + + public function islandPerimeter() + { + if (empty($this->grid) || empty($this->grid[0])) return 0; + + foreach ($this->grid as $key => $val) { + + foreach ($this->grid[0] as $k => $v) { + if ($this->grid[$key][$k] == 0) continue; + $this->result += 4; + + if ($key > 0 && $this->grid[$key - 1][$k] == 1) { + $this->result -= 2; + } + if ($k > 0 && $this->grid[$key][$k - 1] == 1) { + $this->result -= 2; + } + } + } + } +} + +$arr = [ + [0,1,0,0], + [1,1,1,0], + [0,1,0,0], + [1,1,0,0] +]; + +$result = new Solution($arr); +var_dump($result->result); \ No newline at end of file From 8dd980bede51650a83b4ec184f9379ad657d5d57 Mon Sep 17 00:00:00 2001 From: LXZ Date: Thu, 15 Mar 2018 18:00:23 +0800 Subject: [PATCH 090/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=A1=BA=E6=97=B6?= =?UTF-8?q?=E9=92=88=E5=9B=9E=E6=97=8B=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/RotationSort.php | 76 ++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 package/Other/RotationSort.php diff --git a/README-EN.md b/README-EN.md index 42a71f7..e6ba835 100644 --- a/README-EN.md +++ b/README-EN.md @@ -58,6 +58,7 @@ │ └── BigSmallReplace.php │ └── Knapsack.php │ └── Solution.php + │ └── RotationSort.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index 0fdd9a7..4ee73c1 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ │ ├── Knapsack.php 贪心算法之背包问题实现 │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ └── Solution.php Facebook面试题之岛屿周长算法 + │ └── RotationSort.php Facebook面试题之顺时针回旋算法 │ ├──LICENSE └──README.md diff --git a/package/Other/RotationSort.php b/package/Other/RotationSort.php new file mode 100644 index 0000000..48d538a --- /dev/null +++ b/package/Other/RotationSort.php @@ -0,0 +1,76 @@ +row = $row; + $this->col =$col; + $this->start = $start; + $this->print_matrix(); + } + + private function print_matrix() + { + //当前遍历层数 + $small =$this->col < $this->row ?$this->col : $this->row; + + $count = ceil($small / 2); + + for($i=0; $i < $count; $i++) + { + $maxRight = $this->col -1 - $i; //右边最大坐标 + $maxBottom = $this->row -1 - $i; //下面最大坐标 + + for($j=$i; $j<=$maxRight; $j++) + { + $this->res[$i][$j] = $this->start++; + } + for($j=$i; $j<$maxBottom; $j++) + { + $this->res[$j+1][$maxRight] = $this->start++; + } + for($j=$maxRight-1;$j>=$i; $j--) + { + if(isset($this->res[$maxBottom][$j])) break; + $this->res[$maxBottom][$j] = $this->start++; + } + for($j=$maxBottom-1;$j>$i;$j--) + { + if(isset($this->res[$j][$i])) break; + $this->res[$j][$i] = $this->start++; + } + } + } + + /** + * @return string + * 输出回旋形状 + */ + public function print_table() + { + $str = ''; + for ($i = 0; $i < $this->row; $i++) { + $str .=''; + for ($j = 0; $j < $this->col; $j++) { + $str .='"; + } + $str .=""; + } + $str .='
'.$this->res[$i][$j] . "
'; + return $str; + } +} + +$obj = new RotationSort(7, 8); +echo $obj->print_table(); \ No newline at end of file From 8c272a2838e74e4f41a8b9066c41156560072b10 Mon Sep 17 00:00:00 2001 From: LXZ Date: Mon, 19 Mar 2018 15:45:39 +0800 Subject: [PATCH 091/127] =?UTF-8?q?Facebook=E9=9D=A2=E8=AF=95=E9=A2=98?= =?UTF-8?q?=E4=B9=8B=E5=88=A4=E6=96=AD=E5=9B=9B=E4=B8=AA=E7=82=B9=E8=83=BD?= =?UTF-8?q?=E5=90=A6=E7=BB=84=E6=88=90=E6=AD=A3=E6=96=B9=E5=BD=A2=E7=AE=97?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/Square.php | 43 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 package/Other/Square.php diff --git a/README-EN.md b/README-EN.md index e6ba835..daa0eae 100644 --- a/README-EN.md +++ b/README-EN.md @@ -59,6 +59,7 @@ │ └── Knapsack.php │ └── Solution.php │ └── RotationSort.php + │ └── Square.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index 4ee73c1..de7fea7 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,7 @@ │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow │ └── Solution.php Facebook面试题之岛屿周长算法 │ └── RotationSort.php Facebook面试题之顺时针回旋算法 + │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 │ ├──LICENSE └──README.md diff --git a/package/Other/Square.php b/package/Other/Square.php new file mode 100644 index 0000000..c0b7614 --- /dev/null +++ b/package/Other/Square.php @@ -0,0 +1,43 @@ +point = $point; + } + + public function check() + { + $result = []; + if (count($this->point) != 4) return false; + for ($i = 0; $i < count($this->point); $i++) { + for ($j = $i + 1; $j < count($this->point); $j++) { + $result[]=$this->_calculation($i,$j); + } + } + sort($result); + if ($result[0] == $result[1] && $result[4] == $result[5] && $result[4] > $result[1]) { + return true; + } + return false; + + } + + private function _calculation($i, $j) + { + return ($this->point[$i][0] - $this->point[$j][0]) * ($this->point[$i][0] - $this->point[$j][0]) + ($this->point[$i][1] - $this->point[$j][1]) * ($this->point[$i][1] - $this->point[$j][1]); + } +} + +$obj = new Square([[0, 0], [1, 0], [1, 1], [0, 1]]); +var_dump($obj->check()); \ No newline at end of file From 0b2fa3f02de9743135446adb250e7d9bcd5870bb Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sun, 25 Mar 2018 16:57:23 +0800 Subject: [PATCH 092/127] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E7=AE=97=E6=B3=95=E5=AF=B9=E5=A4=A7O=E8=A1=A8?= =?UTF-8?q?=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .travis.yml | 6 --- package/Query/BinarySearchTree.php | 31 ++++++++++++++ package/Query/BinaryTree.php | 13 ------ package/Query/QuickQuery.php | 4 +- package/Sort/MergeSort.php | 5 ++- package/Sort/QuickSort.php | 66 +++++++++++++++++------------- package/Sort/SelectSort.php | 5 ++- 7 files changed, 76 insertions(+), 54 deletions(-) delete mode 100644 .travis.yml create mode 100644 package/Query/BinarySearchTree.php delete mode 100644 package/Query/BinaryTree.php diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index c85eb70..0000000 --- a/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: php -sudo: false -php: - - 5.5 - - 5.6 - - 7.0 \ No newline at end of file diff --git a/package/Query/BinarySearchTree.php b/package/Query/BinarySearchTree.php new file mode 100644 index 0000000..eb9b975 --- /dev/null +++ b/package/Query/BinarySearchTree.php @@ -0,0 +1,31 @@ + + * @date 2017/8/25 + * @license MIT + * ------------------------------------------------------------- + * 思路分析:x为二叉查找树中的一个结点,x节点包含关键字key,节点x的key值记为key[x] + * 如果y是x的左子树中的一个结点,则key[y] <= key[x]; + * 如果y是x的右子树的一个结点, 则key[y] >= key[x]。 + * ------------------------------------------------------------- + * 在二叉查找树中: + * (01) 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值; + * (02) 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值; + * (03) 任意节点的左、右子树也分别为二叉查找树。 + * (04) 没有键值相等的节点(no duplicate nodes)。 + */ + +// +-------------------------------------------------------------------------- +// | 解题方式 +// +-------------------------------------------------------------------------- +class BinarySearchTree +{ + +} + +// +-------------------------------------------------------------------------- +// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// +-------------------------------------------------------------------------- diff --git a/package/Query/BinaryTree.php b/package/Query/BinaryTree.php deleted file mode 100644 index 38cb234..0000000 --- a/package/Query/BinaryTree.php +++ /dev/null @@ -1,13 +0,0 @@ - - * @date 2017/8/25 - * @license MIT - * ------------------------------------------------------------- - * 思路分析: - * ------------------------------------------------------------- - */ -#TODO 2018-2-14 这儿没写完 \ No newline at end of file diff --git a/package/Query/QuickQuery.php b/package/Query/QuickQuery.php index 54b3a0d..05e3fcf 100644 --- a/package/Query/QuickQuery.php +++ b/package/Query/QuickQuery.php @@ -35,9 +35,9 @@ function QuickQuery($array, $k, $low = 0, $high = 0) if ($array[$mid] == $k) { return $mid; } else if ($k < $array[$mid]) {//如果没有找到,则继续查找 - return QulickQuery($array, $k, $low, $mid - 1); + return QuickQuery($array, $k, $low, $mid - 1); } else { - return QulickQuery($array, $k, $mid + 1, $high); + return QuickQuery($array, $k, $mid + 1, $high); } } return -1; diff --git a/package/Sort/MergeSort.php b/package/Sort/MergeSort.php index 6e8fbc1..86bf647 100644 --- a/package/Sort/MergeSort.php +++ b/package/Sort/MergeSort.php @@ -8,6 +8,7 @@ * @license MIT * ------------------------------------------------------------- * 思路分析: + * 大O表示: O(n log n) * ------------------------------------------------------------- * 比较a[i]和b[j]的大小,若a[i]≤b[j],则将第一个有序表中的元素a[i]复制到r[k]中, * 并令i和k分别加上1;否则将第二个有序表中的元素b[j]复制到r[k]中,并令j和k分别加上1, @@ -18,7 +19,7 @@ // +-------------------------------------------------------------------------- -// | 解题方式 | 这儿,可能有用的解决方案 +// | 解题方式 // +-------------------------------------------------------------------------- class MergeSort @@ -100,7 +101,7 @@ public function mergeArray(&$arr, $left, $center, $right) // +-------------------------------------------------------------------------- -// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// | 方案测试 // +-------------------------------------------------------------------------- //do some test: diff --git a/package/Sort/QuickSort.php b/package/Sort/QuickSort.php index 6976133..f2a6688 100644 --- a/package/Sort/QuickSort.php +++ b/package/Sort/QuickSort.php @@ -7,15 +7,15 @@ * @license MIT * ------------------------------------------------------------- * 思路分析:从数列中挑出一个元素,称为 “基准”(pivot)  + * 大O表示: O(n log n) 最糟 O(n 2) * ------------------------------------------------------------- - * 重新排序数列,所有元素比基准值小的摆放在基准前面 + * 重新排序数列,所有元素比基准值小的摆放在基准前面,C 语言中的 qsort就是快速排序 * 所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。 * 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序 */ - // +-------------------------------------------------------------------------- -// | 解题方式 | 这儿,可能有用的解决方案 +// | 解题方式 // +-------------------------------------------------------------------------- /** @@ -27,12 +27,14 @@ function QuickSort(array $container) { $count = count($container); - if ($count <= 1) { + if ($count <= 1) { // 基线条件为空或者只包含一个元素,只需要原样返回数组 return $container; } - $left = $right = []; + $pivot = $container[0]; // 基准值 pivot + $left = $right = []; + for ($i = 1; $i < $count; $i++) { - if ($container[$i] < $container[0]) { + if ($container[$i] < $pivot) { $left[] = $container[$i]; } else { $right[] = $container[$i]; @@ -44,33 +46,39 @@ function QuickSort(array $container) } // +-------------------------------------------------------------------------- -// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// | 方案测试 // +-------------------------------------------------------------------------- var_dump(QuickSort([4, 21, 41, 2, 53, 1, 213, 31, 21, 423])); /** * array(10) { -[0] => -int(1) -[1] => -int(2) -[2] => -int(4) -[3] => -int(21) -[4] => -int(21) -[5] => -int(31) -[6] => -int(41) -[7] => -int(53) -[8] => -int(213) -[9] => -int(423) -} - + * [0] => + * int(1) + * [1] => + * int(2) + * [2] => + * int(4) + * [3] => + * int(21) + * [4] => + * int(21) + * [5] => + * int(31) + * [6] => + * int(41) + * [7] => + * int(53) + * [8] => + * int(213) + * [9] => + * int(423) + * } + */ +/** + * PS & EX: + * 快速排序使用分而治之【 divide and conquer,D&C 】的策略,D&C 解决问题的过程包括两个步骤 + * 1. 找出基线条件,这种条件必须尽可能简单 + * 2. 不断将问题分解(或者说缩小规模),直到符合基线条件 + * (D&C 并非解决问题的算法,而是一种解决问题的思路) */ \ No newline at end of file diff --git a/package/Sort/SelectSort.php b/package/Sort/SelectSort.php index fd9e8ad..832861c 100644 --- a/package/Sort/SelectSort.php +++ b/package/Sort/SelectSort.php @@ -8,6 +8,7 @@ * @license MIT * ------------------------------------------------------------- * 思路分析:选择排序是不稳定的排序方法 + * 大O表示: O(n 2) * ------------------------------------------------------------- * 它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 * 选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面)。 @@ -15,7 +16,7 @@ // +-------------------------------------------------------------------------- -// | 解题方式 | 这儿,可能有用的解决方案 +// | 解题方式 // +-------------------------------------------------------------------------- /** * SelectSort @@ -43,7 +44,7 @@ function SelectSort(array $container) } // +-------------------------------------------------------------------------- -// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// | 方案测试 // +-------------------------------------------------------------------------- From 16c0826ccfe199d0b34670200e14362b3de32f2a Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sun, 25 Mar 2018 17:03:06 +0800 Subject: [PATCH 093/127] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E5=8F=96?= =?UTF-8?q?=E8=88=8D=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Sort/HeapSort.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package/Sort/HeapSort.php b/package/Sort/HeapSort.php index 0dd9488..acafa03 100644 --- a/package/Sort/HeapSort.php +++ b/package/Sort/HeapSort.php @@ -67,7 +67,7 @@ public function run() */ public function createHeap() { - $i = ceil($this->count / 2) + 1; + $i = floor($this->count / 2) + 1; while ($i--) { $this->buildHeap($this->data, $i, $this->count); } From 78c6195202ed031e2a143a21b47b0af97355b580 Mon Sep 17 00:00:00 2001 From: xaboy <309058341@qq.com> Date: Mon, 26 Mar 2018 15:17:31 +0800 Subject: [PATCH 094/127] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Sort/InsertSort.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/package/Sort/InsertSort.php b/package/Sort/InsertSort.php index aa3a0c5..e0a3489 100644 --- a/package/Sort/InsertSort.php +++ b/package/Sort/InsertSort.php @@ -34,12 +34,12 @@ function InsertSort(array $container) $temp = $container[$i]; $j = $i - 1; // Init - while ($container[$j] > $temp){ + while($j >= 0 && $container[$j] > $temp){ $container[$j+1] = $container[$j]; - $container[$j] = $temp; $j--; - if ($j < 0) break; } + if($i != $j+1) + $container[$j+1] = $temp; } return $container; } @@ -60,4 +60,4 @@ function InsertSort(array $container) 5 => int 24 6 => int 42 7 => int 346 - */ \ No newline at end of file + */ From 1fc2a56aa6cbb1a81c51625ac6c65401788835ec Mon Sep 17 00:00:00 2001 From: LXZ Date: Mon, 2 Apr 2018 10:50:29 +0800 Subject: [PATCH 095/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0Prim=E7=AE=97?= =?UTF-8?q?=E6=B3=95(=E6=99=AE=E5=88=A9=E5=A7=86=E7=AE=97=E6=B3=95)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/Prim.php | 78 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 package/Other/Prim.php diff --git a/README-EN.md b/README-EN.md index daa0eae..029bdb7 100644 --- a/README-EN.md +++ b/README-EN.md @@ -60,6 +60,7 @@ │ └── Solution.php │ └── RotationSort.php │ └── Square.php + │ └── Prim.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index de7fea7..cda10ce 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,7 @@ │ └── Solution.php Facebook面试题之岛屿周长算法 │ └── RotationSort.php Facebook面试题之顺时针回旋算法 │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 + │ └── Prim.php Prim算法(最小生成树算法) │ ├──LICENSE └──README.md diff --git a/package/Other/Prim.php b/package/Other/Prim.php new file mode 100644 index 0000000..0640ae9 --- /dev/null +++ b/package/Other/Prim.php @@ -0,0 +1,78 @@ +lowcost[$i] = $graph[0][$i]; + $mst[$i] = 0; + } + for ($i = 1; $i < $n; $i++) { + $min = 65535; + $minid = 0; + for ($j = 1; $j < $n; $j++) { + if ($this->lowcost[$j] < $min && $this->lowcost[$j] != 0) { + $min = $this->lowcost[$j]; + $minid = $j; + } + } + echo '
';
+                print_r($this->c[$mst[$minid]] ."到" . $this->c[$minid] . " 权值:" . $min);
+            echo '
'; + + $sum += $min; + $this->lowcost[$minid] = 0; + + for ($j = 1; $j < $n; $j++) { + if ($graph[$minid][$j] < $this->lowcost[$j]) { + $this->lowcost[$j] = $graph[$minid][$j]; + $mst[$j] = $minid; + } + } + } + print_r("sum:" . $sum); + } + + public function main() + { + $map = [ + [0, 10, 65535, 65535, 65535, 11, 65535, 65535, 65535], + [10, 0, 18, 65535, 65535, 65535, 16, 65535, 12], + [65535, 65535, 0, 22, 65535, 65535, 65535, 65535, 8], + [65535, 65535, 22, 0, 20, 65535, 65535, 16, 21], + [65535, 65535, 65535, 20, 0, 26, 65535, 7, 65535], + [11, 65535, 65535, 65535, 26, 0, 17, 65535, 65535], + [65535, 16, 65535, 65535, 65535, 17, 0, 19, 65535], + [65535, 65535, 65535, 16, 7, 65535, 19, 0, 65535], + [65535, 12, 8, 21, 65535, 65535, 65535, 65535, 0] + ]; + $this->prim_main($map, count($map)); + } +} + +$obj = new Prim(); +$obj->main(); From 070ba3fccd87ce87d9b894dcd7ae41b181768901 Mon Sep 17 00:00:00 2001 From: LXZ Date: Tue, 3 Apr 2018 10:28:11 +0800 Subject: [PATCH 096/127] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=AC=9B=E5=8D=A1?= =?UTF-8?q?=E5=B0=94=E7=A7=AF=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Other/CartesianProduct.php | 61 ++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) create mode 100644 package/Other/CartesianProduct.php diff --git a/README-EN.md b/README-EN.md index 029bdb7..610971c 100644 --- a/README-EN.md +++ b/README-EN.md @@ -61,6 +61,7 @@ │ └── RotationSort.php │ └── Square.php │ └── Prim.php + │ └── CartesianProduct.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index cda10ce..3e55e9e 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ │ └── RotationSort.php Facebook面试题之顺时针回旋算法 │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 │ └── Prim.php Prim算法(最小生成树算法) + │ └── CartesianProduct.php 笛卡尔积算法 │ ├──LICENSE └──README.md diff --git a/package/Other/CartesianProduct.php b/package/Other/CartesianProduct.php new file mode 100644 index 0000000..63f027d --- /dev/null +++ b/package/Other/CartesianProduct.php @@ -0,0 +1,61 @@ +params = func_get_args(); + } + public function combineDika() + { + $result = []; + if(count($this->params[0])!=count($this->params[0], 1)){ + $this->params = $this->params[0]; + } + $cnt = count($this->params); + foreach($this->params[0] as $item) { + $result[] = [$item]; + } + for($i = 1; $i < $cnt; $i++) { + $result = $this->combineArray($result,$this->params[$i]); + } + return $result; + } + + private function combineArray($arr_a, $arr_b) + { + $result = []; + foreach ($arr_a as $item) { + foreach ($arr_b as $item2) { + $temp = $item; + $temp[] = $item2; + $result[] = $temp; + } + } + return $result; + } +} + +$color = array('白色','黑色','红色'); +$size = array('透气','防滑'); +$local = array('37码','38码','39码'); + +$obj = new CartesianProduct($color,$size,$local); +print_r($obj->combineDika()); + +$sets = array( + array('白色','黑色','红色'), + array('透气','防滑'), + array('37码','38码','39码'), + array('男款','女款') +); + +$obj1 = new CartesianProduct($sets); +print_r($obj1->combineDika()); \ No newline at end of file From a3acd9a710746857c64f8f6503c88e471ea3b27c Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 7 Apr 2018 18:17:32 +0800 Subject: [PATCH 097/127] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=B9=BF?= =?UTF-8?q?=E5=BA=A6=E4=BC=98=E5=85=88=E6=90=9C=E7=B4=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + package/Query/BFSQuery.php | 174 +++++++++++++++++++++++++++++++ package/Query/FibonacciQuery.php | 4 +- 4 files changed, 178 insertions(+), 2 deletions(-) create mode 100644 package/Query/BFSQuery.php diff --git a/README-EN.md b/README-EN.md index 610971c..b298520 100644 --- a/README-EN.md +++ b/README-EN.md @@ -35,6 +35,7 @@ │ │ ├── BinaryQuery.php │ │ ├── InseertQuery.php │ │ ├── FibonacciQuery.php + │ │ ├── BFSQuery.php │ │ └── QulickQuery.php │ │ │ └── Other 其他 diff --git a/README.md b/README.md index 3e55e9e..a2c3018 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ │ │ ├── BinaryQuery.php 二分查找 │ │ ├── InseertQuery.php 插入查找 │ │ ├── FibonacciQuery.php 斐波那契查找 + │ │ ├── BFSQuery.php 广度优先查找 │ │ └── QulickQuery.php 快速查找 │ │ │ ├── Structure 数据结构 diff --git a/package/Query/BFSQuery.php b/package/Query/BFSQuery.php new file mode 100644 index 0000000..cd7c142 --- /dev/null +++ b/package/Query/BFSQuery.php @@ -0,0 +1,174 @@ + + * @date 2017/6/17 + * @license MIT + * ------------------------------------------------------------- + * 思路分析: BFS并不使用经验法则算法。从算法的观点,所有因为展开节点而得到的子节点都会被加进一个先进先出的队列中 + * 时间复杂度:O(n) + * ------------------------------------------------------------- + * 宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型。 + * Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思想。 + * 其别名又叫BFS,属于一种盲目搜寻法,目的是系统地展开并检查图中的所有节点,以找寻结果。 + * 换句话说,它并不考虑结果的可能位置,彻底地搜索整张图,直到找到结果为止。 + */ +class BFSQuery +{ + /** + * @var array 关系网络 + */ + protected $relationship; + /** + * @var \SplQueue 处理队列 + */ + protected $queue; + + /** + * @var string 搜索结果 + */ + protected $target; + + /** + * BFSQuery constructor. + * + * @param array $relationship + * @param string $target + */ + public function __construct(array $relationship, $target) + { + + $this->relationship = $relationship; + $this->queue = new SplQueue(); + $this->target = $target; + $this->generator($this->relationship); + } + + /** + * 开始入列 + * + * @param array $relation + * @return \Generator + */ + public function generator($relation) + { + foreach ($relation as $value) { + $this->schedule($value); + } + } + + + /** + * 队列入队 + * + * @param $item + * @return int + */ + public function schedule($item) + { + $this->queue->enqueue($item); + } + + /** + * 队列中查找符合条件 + * + * @return string + */ + public function run() + { + $result = $this->target . '没有人有~!'; + while (!$this->queue->isEmpty()) { + // 出队列 + $item = $this->queue->dequeue(); + if (!isset($item['friend'])) { + continue; + } + if (!isset($item['fruit'])) { + continue; + } + $totalFruit = count($item['fruit']); + $mark = 0; + while ($totalFruit > $mark) { + if ($item['fruit'][$mark] === $this->target) { + $result = '找到了~!'; + break 2; + } + $mark++; + } + $this->generator($item['friend']); + } + return $result; + } +} + + +// +-------------------------------------------------------------------------- +// | 方案测试 +// +-------------------------------------------------------------------------- +// 你现在需要一个 `mango` ,所以你需要在你的朋友圈里搜刮,你可以先从Jack 与 tom 身上找, +// 然后再从他们的朋友身上找,然后再从他们朋友的朋友哪里找 + +$me = array ( + 'jack' => array ( + 'fruit' => array ('apple', 'banana', 'dragon'), + 'friend' => array ( + 'lucy' => array ( + 'fruit' => array ('bear', 'watermelon'), + 'friend' => array ( + 'marco' => array ( + 'fruit' => array ('mango', 'cherry'), // Mango 在这儿 + 'friend' => array ( + '...', + ) + ), + ), + ), + 'bob' => array ( + 'fruit' => array ('orange', 'mangosteen', 'peach'), + 'friend' => array ( + '', + ), + ), + + ), + ), + 'tom' => array ( + 'fruit' => array ( + 'apple', + 'banana', + ), + 'friend' => array ( + 'lucy' => array ( + 'fruit' => array (), + 'friend' => array ( + 'lucy' => array ( + 'fruit' => array ('bear', 'watermelon'), + 'friend' => array ( + 'marco' => array ( + 'fruit' => array ('mango', 'cherry'), // Mango 在这儿也有 + 'friend' => array ( + '...', + ) + ), + ), + ), + ), + ), + 'bob' => array ( + 'fruit' => array ('apple', 'peach'), + 'friend' => array ( + 'marco' => array ( + 'fruit' => array ('mango', 'cherry'), // Mango 在这儿也有 + 'friend' => array ( + 'Marco 有无数多的盆友...', + ) + ), + ) + ), + ), + ) +); + +echo (new BFSQuery($me, 'mango'))->run(); \ No newline at end of file diff --git a/package/Query/FibonacciQuery.php b/package/Query/FibonacciQuery.php index a58d630..1c57fc2 100644 --- a/package/Query/FibonacciQuery.php +++ b/package/Query/FibonacciQuery.php @@ -16,7 +16,7 @@ // +-------------------------------------------------------------------------- -// | 解题方式 | 这儿,可能有用的解决方案 +// | 解题方式 // +-------------------------------------------------------------------------- class FibonacciQuery @@ -78,7 +78,7 @@ public function produced($length) } // +-------------------------------------------------------------------------- -// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` +// | 方案测试 // +-------------------------------------------------------------------------- new FibonacciQuery([4, 5, 7, 8, 9, 10, 8], 8); \ No newline at end of file From e911d40150538a972c4d64dfd2ba58714accb758 Mon Sep 17 00:00:00 2001 From: pushaowei <542684913@qq.com> Date: Sat, 21 Apr 2018 18:48:46 +0800 Subject: [PATCH 098/127] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E8=BF=AA?= =?UTF-8?q?=E5=85=8B=E6=96=AF=E7=89=B9=E6=8B=89=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 2 + README.md | 3 +- package/Query/DijkstraQuery.php | 134 +++++++++++++++++++++++ package/{Other/kmp.php => Query/Kmp.php} | 0 4 files changed, 138 insertions(+), 1 deletion(-) create mode 100644 package/Query/DijkstraQuery.php rename package/{Other/kmp.php => Query/Kmp.php} (100%) diff --git a/README-EN.md b/README-EN.md index b298520..8edfa97 100644 --- a/README-EN.md +++ b/README-EN.md @@ -36,6 +36,8 @@ │ │ ├── InseertQuery.php │ │ ├── FibonacciQuery.php │ │ ├── BFSQuery.php + │ │ ├── Kmp.php + │ │ ├── DijkstraQuery.php │ │ └── QulickQuery.php │ │ │ └── Other 其他 diff --git a/README.md b/README.md index a2c3018..dbe41a5 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ │ │ ├── InseertQuery.php 插入查找 │ │ ├── FibonacciQuery.php 斐波那契查找 │ │ ├── BFSQuery.php 广度优先查找 + │ ├── Kmp.php 算法导论-KMP算法 + │ ├── DijkstraQuery.php 迪克斯特拉算法 │ │ └── QulickQuery.php 快速查找 │ │ │ ├── Structure 数据结构 @@ -67,7 +69,6 @@ │ ├── AntsClimb.php 蚂蚁爬杆算法 │ ├── Encryption.php 对称加密算法 │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 - │ ├── kmp.php 算法导论-KMP算法 │ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 │ ├── Knapsack.php 贪心算法之背包问题实现 diff --git a/package/Query/DijkstraQuery.php b/package/Query/DijkstraQuery.php new file mode 100644 index 0000000..cf54ce9 --- /dev/null +++ b/package/Query/DijkstraQuery.php @@ -0,0 +1,134 @@ + + * @date 2017/8/23 + * @license MIT + * ------------------------------------------------------------- + * 思路分析:单源最短路径问题 + * ------------------------------------------------------------- + * Dijkstra 算法一般的表述通常有两种方式,一种用永久和临时标号方式,一种是用OPEN, CLOSE表的方式, + * 这里均采用永久和临时标号的方式。注意该算法要求图中不存在负权边。 + * 因此,在包含负边全的图中要找出最短路径,可以使用另一种算法 -- 贝克曼-福德算法 + */ + +// +-------------------------------------------------------------------------- +// | 解题方式 +// +-------------------------------------------------------------------------- + +/** + * DijkstraQuery + * + * @uses PHPStorm + * @version 1.0 + * @author Pu ShaoWei + */ +class DijkstraQuery +{ + /** + * @var array + */ + protected $graph; + /** + * @var array + */ + protected $processed; + /** + * @var int + */ + protected $infinity; + /** + * @var string + */ + protected $start; + /** + * @var string + */ + protected $end; + + /** + * DijkstraQuery constructor. + * + * @param array $graph + * @param $start + * @param $end + */ + public function __construct(array $graph, $start, $end) + { + $this->graph = $graph; + $this->start = $start; + $this->end = $end; + $this->processed = array (); + $this->infinity = mt_getrandmax(); + } + + /** + * 最短路径 + * + * @return string + */ + public function calculate() + { + $costs = $this->graph[$this->start]; + $costs[$this->end] = $this->infinity; + $node = $this->findLowestCostNode($costs); + + while (null !== $node) { + $cost = $costs[$node]; + $neighbors = $this->graph[$node] ?? array (); + foreach ($neighbors as $neighbor => $distance) { + $newCost = $cost + $distance; + if ($costs[$neighbor] > $newCost) { + $costs[$neighbor] = $newCost; + } + } + array_push($this->processed, $node); + $node = $this->findLowestCostNode($costs); + } + + return 'The shortest distance for:' . $costs[$this->end]; + } + + /** + * findLowestCostNode + * + * @param $costs + * @return null + */ + protected function findLowestCostNode($costs) + { + $lowestCost = $this->infinity; + $lowestCostNode = null; + foreach ($costs as $node => $cost) { + if ($cost < $lowestCost && !in_array($node, $this->processed)) { + $lowestCost = $cost; + $lowestCostNode = $node; + } + } + return $lowestCostNode; + } +} + +// +-------------------------------------------------------------------------- +// | 验证 me --> claire +// +-------------------------------------------------------------------------- +// ∞ +$graph = array ( + 'me' => array ( + 'alice' => 6, + 'bob' => 2, + ), + 'alice' => array ( + 'claire' => 1, + ), + 'bob' => array ( + 'alice' => 3, + 'claire' => 5, + ), + 'claire' => array (// 没有任何邻居 + + ), +); +echo (new DijkstraQuery($graph, 'me', 'claire'))->calculate(); \ No newline at end of file diff --git a/package/Other/kmp.php b/package/Query/Kmp.php similarity index 100% rename from package/Other/kmp.php rename to package/Query/Kmp.php From 347d9d0633c0f5b2f5e1178010c262d93eb1fbf0 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Wed, 25 Apr 2018 15:13:14 +0800 Subject: [PATCH 099/127] =?UTF-8?q?'=E6=96=B0=E5=A2=9E=E5=9B=9B=E7=82=B9?= =?UTF-8?q?=E8=83=BD=E5=90=A6=E6=88=90=E7=9F=A9=E5=BD=A2=E7=9A=84=E7=AE=97?= =?UTF-8?q?=E6=B3=95=E9=A2=98'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/Rectangle.php | 89 +++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 package/Other/Rectangle.php diff --git a/package/Other/Rectangle.php b/package/Other/Rectangle.php new file mode 100644 index 0000000..b2ff943 --- /dev/null +++ b/package/Other/Rectangle.php @@ -0,0 +1,89 @@ +$value) { + $x = abs($value[0]-$a[0]); + $y = abs($value[1]-$a[1]); + $data[$key] = sqrt(pow($x,2)+pow($y,2)); + } + + asort($data); + $keys = array_keys($data); + $maxKey = array_pop($keys);//对焦点 + $length0 = $data[$maxKey];//对角线长度 + + //左右两点 key + $left = $keys[0]; + $right = $keys[1]; + + //算第二条对角线长度 + $x = abs($array[$left][0]-$array[$right][0]); + $y = abs($array[$left][1]-$array[$right][1]); + $length = sqrt(pow($x,2)+pow($y,2)); + + if(!floatEq($length,$length0)) { + return false; + } + + //算直角 + $vertical = sqrt(pow($data[$left],2)+pow($data[$right],2)); + + if(!floatEq($length,$vertical)) { + return false; + } + + return true; + +} + +var_dump(rectangle([0,0],[0,1],[1,1],[1,0])); //true +var_dump(rectangle([1,2],[0,1],[1,1],[1,0])); //false + +/** + * 判断两个浮点数是不是相等 + * + * @param $a float + * @param $b float + * @return bool + */ +function floatEq($a,$b) +{ + if(!$a || !$b) { + return false; + } + //精度 + $epsilon = 0.00001; + + if(abs($a-$b) < $epsilon) { + return true; + } + return false; +} From ea7a3c435e67eb5e62a9a00bcc5d9b34763cd5b5 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Wed, 25 Apr 2018 15:27:21 +0800 Subject: [PATCH 100/127] =?UTF-8?q?Fixed:=E4=BF=AE=E6=AD=A3=E5=8F=82?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/Rectangle.php | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/package/Other/Rectangle.php b/package/Other/Rectangle.php index b2ff943..725a951 100644 --- a/package/Other/Rectangle.php +++ b/package/Other/Rectangle.php @@ -17,21 +17,20 @@ * */ -function rectangle($a=[],$b=[],$c=[],$d=[]) +function rectangle($one=[],$two=[],$three=[],$four=[]) { - if(empty($a) || empty($b) || empty($c) || empty($d)) { + if(empty($one) || empty($two) || empty($three) || empty($four)) { return false; } - $base = $a; - $array['b'] = $b; - $array['c'] = $c; - $array['d'] = $d; + $array['b'] = $two; + $array['c'] = $three; + $array['d'] = $four; $data = []; - $max = ""; + foreach ($array as $key=>$value) { - $x = abs($value[0]-$a[0]); - $y = abs($value[1]-$a[1]); + $x = abs($value[0]-$one[0]); + $y = abs($value[1]-$one[1]); $data[$key] = sqrt(pow($x,2)+pow($y,2)); } @@ -74,15 +73,15 @@ function rectangle($a=[],$b=[],$c=[],$d=[]) * @param $b float * @return bool */ -function floatEq($a,$b) +function floatEq($floatNumber1,$floatNumber2) { - if(!$a || !$b) { + if(!$floatNumber1 || !$floatNumber2) { return false; } //精度 $epsilon = 0.00001; - if(abs($a-$b) < $epsilon) { + if(abs($floatNumber1-$floatNumber2) < $epsilon) { return true; } return false; From 41ee4e215b7c9bc599b1d7939e88f7c319e5a576 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Wed, 25 Apr 2018 16:03:18 +0800 Subject: [PATCH 101/127] style: modifyied README modified: README-EN.md modified: README.md --- README-EN.md | 167 ++++++++++++++++++++------------------ README.md | 220 +++++++++++++++++++++++++++++---------------------- 2 files changed, 214 insertions(+), 173 deletions(-) diff --git a/README-EN.md b/README-EN.md index 8edfa97..5c8b915 100644 --- a/README-EN.md +++ b/README-EN.md @@ -17,105 +17,113 @@

-

中文版 

+

中文版 

## Simple structure, - - ├──Package - │ ├── Sort - │ │ ├── BubbleSort.php - │ │ ├── QuickSort.php - │ │ ├── ShellSort.php - │ │ ├── MergeSort.php - │ │ ├── InsertSort.php - │ │ └── SelectSort.php - │ │ - │ ├── Query 查找篇 - │ │ ├── BinaryQuery.php - │ │ ├── InseertQuery.php - │ │ ├── FibonacciQuery.php - │ │ ├── BFSQuery.php - │ │ ├── Kmp.php - │ │ ├── DijkstraQuery.php - │ │ └── QulickQuery.php - │ │ - │ └── Other 其他 - │ ├── MonkeyKing.php - │ ├── DynamicProgramming.php - │ ├── Fibonacci.php - │ ├── StealingApples.php - │ ├── HanoiGames.php - │ ├── BidirectionalQueue.php - │ ├── ColorBricks.php - │ ├── GetCattle.php - │ ├── OnlyNumbers.php - │ ├── Interval.php - │ ├── Maze.php - │ ├── AntsClimb.php - │ ├── Encryption.php - │ ├── ElevatorDispatch.php - │ ├── kmp.php - │ ├── TraversalOfBinary.php - │ ├── PointInTriangle.php - │ └── BigSmallReplace.php - │ └── Knapsack.php - │ └── Solution.php - │ └── RotationSort.php - │ └── Square.php - │ └── Prim.php - │ └── CartesianProduct.php - │ - ├──LICENSE - └──README.md + +``` +├──Package +│ ├── Sort +│ │ ├── BubbleSort.php +│ │ ├── QuickSort.php +│ │ ├── ShellSort.php +│ │ ├── MergeSort.php +│ │ ├── InsertSort.php +│ │ └── SelectSort.php +│ │ +│ ├── Query 查找篇 +│ │ ├── BinaryQuery.php +│ │ ├── InseertQuery.php +│ │ ├── FibonacciQuery.php +│ │ ├── BFSQuery.php +│ │ ├── Kmp.php +│ │ ├── DijkstraQuery.php +│ │ └── QulickQuery.php +│ │ +│ └── Other 其他 +│ ├── MonkeyKing.php +│ ├── DynamicProgramming.php +│ ├── Fibonacci.php +│ ├── StealingApples.php +│ ├── HanoiGames.php +│ ├── BidirectionalQueue.php +│ ├── ColorBricks.php +│ ├── GetCattle.php +│ ├── OnlyNumbers.php +│ ├── Interval.php +│ ├── Maze.php +│ ├── AntsClimb.php +│ ├── Encryption.php +│ ├── ElevatorDispatch.php +│ ├── kmp.php +│ ├── TraversalOfBinary.php +│ ├── PointInTriangle.php +│ └── BigSmallReplace.php +│ └── Knapsack.php +│ └── Solution.php +│ └── RotationSort.php +│ └── Square.php +│ └── Prim.php +│ └── CartesianProduct.php +│ └── RotationSort.php +│ +├──LICENSE +└──README.md +``` ## What to do? - To record their understanding algorithms, data structure, the process of simple comprehensive and detailed as possible, let the learning algorithm using flexible, refueling(ง •̀_•́)ง + +``` +To record their understanding algorithms, data structure, the process of simple comprehensive and detailed as possible, let the learning algorithm using flexible, refueling(ง •̀_•́)ง +``` ## logarithmic + log10100 It's equivalent to saying, "how many tens do you multiply?" the answer is, of course, two so log10100=2,The logarithmic operation is the inverse of the power operation -left|right ----|--- -23 = 8 | log28 = 3 -24 = 16 | log216 = 4 -25 = 32 | log232 = 5 +| left | right | +| ------------------ | --------------------- | +| 23 = 8 | log28 = 3 | +| 24 = 16 | log216 = 4 | +| 25 = 32 | log232 = 5 | If you don't, we won't wait for you ## The elapsed time + 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. 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 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)` ## Big O notation + 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. In this case, you know how fast these algorithms are - The running time of the algorithm increases at different speeds - For example, the difference between a simple find and a binary search - -element|Easy to find|Binary search ----|---|--- -100|100ms|7ms -10000|10s|14ms -1 000 000 000 |11day|30ms - - - ` 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 - Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` -- Some common big O runtime - - O(log n) ,It's also called log time, and this algorithm includes binary algorithms - - O(n),Also known as linear time, this algorithm includes simple lookups. - - O(n * log n) Quick sort - - O(n2),Selection sort - - O(n!) Factorial time -- Here is the point - - The speed of the algorithm is not the time, but the growth of operands - - When we talk about the speed of the algorithm, what we're talking about is how fast will it run as the input increases - - The running time of the algorithm is expressed in large O notation - - 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 +| element | Easy to find | Binary search | +| ------------- | ------------ | ------------- | +| 100 | 100ms | 7ms | +| 10000 | 10s | 14ms | +| 1 000 000 000 | 11day | 30ms | + +- ` 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 +Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` + - Some common big O runtime +- O(log n) ,It's also called log time, and this algorithm includes binary algorithms +- O(n),Also known as linear time, this algorithm includes simple lookups. +- O(n * log n) Quick sort +- O(n2),Selection sort +- O(n!) Factorial time + - Here is the point +- The speed of the algorithm is not the time, but the growth of operands +- When we talk about the speed of the algorithm, what we're talking about is how fast will it run as the input increases +- The running time of the algorithm is expressed in large O notation +- 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 ## A simple comparison of recursion and loops: @@ -125,11 +133,13 @@ element|Easy to find|Binary search 4.In general, non-recursive efficiency is higher than recursion. And recursive function calls are expensive and recursive times are limited by stack size. ## Progressive learning + 1. Fork 我的项目并提交你的 `idea` 2. Pull Request 3. Merge -## 纠错 +## 纠错 + 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 > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) @@ -143,5 +153,8 @@ Thanks for the issue or pull request of the following friends: - [ifreesec](https://github.com/ifreesec) - [openset](https://github.com/openset) - [Neroxiezi](https://github.com/Neroxiezi) -## License -MIT \ No newline at end of file + + ## License + + +MIT diff --git a/README.md b/README.md index dbe41a5..49745f8 100644 --- a/README.md +++ b/README.md @@ -17,126 +17,142 @@

+

English 

> 每周最少一更,求出题,求虐待 At least once a week, ask for problems and abuse ## 简易结构 - ├──Package - │ ├── Sort 排序篇 - │ │ ├── BubbleSort.php 冒泡排序 - │ │ ├── HeapSort.php 堆排序 大根堆 - │ │ ├── MBaseSort.php 基数排序 MSD - │ │ ├── LBaseSort.php 基数排序 LSD - │ │ ├── QuickSort.php 快速排序 - │ │ ├── ShuttleSort.php 飞梭排序 - │ │ ├── ShellSort.php 希尔排序 - │ │ ├── MergeSort.php 归并排序 - │ │ ├── InsertSort.php 插入排序 - │ │ └── SelectSort.php 选择排序 - │ │ - │ ├── Query 查找篇 - │ │ ├── BinaryQuery.php 二分查找 - │ │ ├── InseertQuery.php 插入查找 - │ │ ├── FibonacciQuery.php 斐波那契查找 - │ │ ├── BFSQuery.php 广度优先查找 - │ ├── Kmp.php 算法导论-KMP算法 - │ ├── DijkstraQuery.php 迪克斯特拉算法 - │ │ └── QulickQuery.php 快速查找 - │ │ - │ ├── Structure 数据结构 - │ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) - │ │ ├── LinearChain.php 线性表 单链存储 - │ │ └── LinearOrder.php 线性表 顺序存储 - │ │ - │ ├── Tools 小工具集 - │ │ └── SystemSwitch.php 堆栈实现进制转换 - │ │ - │ └── Other 其他 - │ ├── MonkeyKing.php 约瑟夫环 - │ ├── DynamicProgramming.php 动态规划 - │ ├── Fibonacci.php 斐波那契数列 - │ ├── StealingApples.php 偷苹果求余 - │ ├── HanoiGames.php 汉诺塔游戏 - │ ├── BidirectionalQueue.php 双向队列 - │ ├── ColorBricks.php 彩色砖块 - │ ├── GetCattle.php 牛年求牛 - │ ├── OnlyNumbers.php 求唯一数 - │ ├── PokerGames.php 洗扑克牌 - │ ├── Interval.php 抽奖区间算法 - │ ├── Maze.php 迷宫寻址算法 - │ ├── AntsClimb.php 蚂蚁爬杆算法 - │ ├── Encryption.php 对称加密算法 - │ ├── ElevatorDispatch.php 编程之美-电梯调度算法 - │ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 - │ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 - │ ├── Knapsack.php 贪心算法之背包问题实现 - │ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow - │ └── Solution.php Facebook面试题之岛屿周长算法 - │ └── RotationSort.php Facebook面试题之顺时针回旋算法 - │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 - │ └── Prim.php Prim算法(最小生成树算法) - │ └── CartesianProduct.php 笛卡尔积算法 - │ - ├──LICENSE - └──README.md +``` +├──Package +│ ├── Sort 排序篇 +│ │ ├── BubbleSort.php 冒泡排序 +│ │ ├── HeapSort.php 堆排序 大根堆 +│ │ ├── MBaseSort.php 基数排序 MSD +│ │ ├── LBaseSort.php 基数排序 LSD +│ │ ├── QuickSort.php 快速排序 +│ │ ├── ShuttleSort.php 飞梭排序 +│ │ ├── ShellSort.php 希尔排序 +│ │ ├── MergeSort.php 归并排序 +│ │ ├── InsertSort.php 插入排序 +│ │ └── SelectSort.php 选择排序 +│ │ +│ ├── Query 查找篇 +│ │ ├── BinaryQuery.php 二分查找 +│ │ ├── InseertQuery.php 插入查找 +│ │ ├── FibonacciQuery.php 斐波那契查找 +│ │ ├── BFSQuery.php 广度优先查找 +│ ├── Kmp.php 算法导论-KMP算法 +│ ├── DijkstraQuery.php 迪克斯特拉算法 +│ │ └── QulickQuery.php 快速查找 +│ │ +│ ├── Structure 数据结构 +│ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) +│ │ ├── LinearChain.php 线性表 单链存储 +│ │ └── LinearOrder.php 线性表 顺序存储 +│ │ +│ ├── Tools 小工具集 +│ │ └── SystemSwitch.php 堆栈实现进制转换 +│ │ +│ └── Other 其他 +│ ├── MonkeyKing.php 约瑟夫环 +│ ├── DynamicProgramming.php 动态规划 +│ ├── Fibonacci.php 斐波那契数列 +│ ├── StealingApples.php 偷苹果求余 +│ ├── HanoiGames.php 汉诺塔游戏 +│ ├── BidirectionalQueue.php 双向队列 +│ ├── ColorBricks.php 彩色砖块 +│ ├── GetCattle.php 牛年求牛 +│ ├── OnlyNumbers.php 求唯一数 +│ ├── PokerGames.php 洗扑克牌 +│ ├── Interval.php 抽奖区间算法 +│ ├── Maze.php 迷宫寻址算法 +│ ├── AntsClimb.php 蚂蚁爬杆算法 +│ ├── Encryption.php 对称加密算法 +│ ├── ElevatorDispatch.php 编程之美-电梯调度算法 +│ ├── PointInTriangle.php 向量叉集计算点是否在三角形中 +│ ├── TraversalOfBinary.php 二叉树非递归遍历算法实现 +│ ├── Knapsack.php 贪心算法之背包问题实现 +│ └── BigSmallReplace.php Hello World 输出 Olleh Dlrow +│ └── Solution.php Facebook面试题之岛屿周长算法 +│ └── RotationSort.php Facebook面试题之顺时针回旋算法 +│ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 +│ └── Prim.php Prim算法(最小生成树算法) +│ └── CartesianProduct.php 笛卡尔积算法 +│ └── RotationSort.php 面试题之平面任意四点能否组成一个矩形 +│ +│ +├──LICENSE +└──README.md +``` ## 要做什么? - 记录自己理解算法,数据结构的过程,尽可能的简单全面以及详细,让算法学习运用灵活自如,加油(ง •̀_•́)ง - + +``` +记录自己理解算法,数据结构的过程,尽可能的简单全面以及详细,让算法学习运用灵活自如,加油(ง •̀_•́)ง +``` + ## 当然 - 用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这觉不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 - + +``` +用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这觉不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 +``` + ## 什么是算法? + 直白地说,算法就是任何明确定义的计算过程,它接收一些值或集合作为输入,并产生一些值或集合作为输出。这样,算法就是将输入转换为输出的一系列计算过程。来源:Thomas H. Cormen, Chales E. Leiserson (2009), 《算法导论第三版》。 简而言之,我们可以说算法就是用来解决一个特定任务的一系列步骤(是的,不止计算机在使用算法,人类也同样如此)。目前,一个有效的算法应该含有三个重要特性: + - 它必须是有限的:如果你设计的算法永无休止地尝试解决问题,那么它是无用的。 - 它必须具备明确定义的指令:算法的每一步都必须准确定义,在任何场景下指令都应当没有歧义。 - 它必须是有效的:一个算法被设计用以解决某个问题,那么它就应当能解决这个问题,并且仅仅使用纸和笔就能证明该算法是收敛的。 ## 对数 + log10100 相当于问"将多少个10相乘的结果为100",答案当然是2个了 因此log10100=2,即对数运算是幂运算的逆运算 -left|right ----|--- -23 = 8 | log28 = 3 -24 = 16 | log216 = 4 -25 = 32 | log232 = 5 +| left | right | +| ------------------ | --------------------- | +| 23 = 8 | log28 = 3 | +| 24 = 16 | log216 = 4 | +| 25 = 32 | log232 = 5 | ## 运行时间 + 以二分查找为例,使用它可节省多少时间呢?简单查找逐个地检查数字,如果列表包含100个数字,最多需要猜100次。 换而言之最多需要猜测的次数与列表长度相同,这被称为线性时间(linear time),而二分查找则不同,如果列表包含100个元素 最多需要7次,如果列表包含40亿个数字,最多需猜32次,而分查找的运行时间为对数时间 `O(log)` ## 大O表示法 + 大O表示法是一种特殊的表示法 ,指出了算法的速度有多快。有个屌用啊,实际上,你经常要去复制别人的代码。 在这种情况下,知道这些算法的速度有快有慢 - 算法的运行时间以不同的速度增加 - 例如简单查找与二分查找的区别 -元素|简单查找|二分查找 ----|---|--- -100个元素|100ms|7ms -10000个元素|10s|14ms -1 000 000 000 个元素|11天|30ms - -  - 大`O`表示法指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 -    使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` -- 一些常见的大O运行时间 - - O(log n) ,也叫对数时间,这样的算法包括二分算法 - - O(n),也叫线性时间,这样的算法包括简单查找。 - - O(n * log n) 快速排序 - - O(n2),选择排序 - - O(n!) 即阶乘时间 -- 这里是重点 - - 算法的速度指的并非时间,而是操作数的增速 - - 谈论算法的速度时间时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加 -  - 算法的运行时间用大O表示法表示 - - O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 +| 元素 | 简单查找 | 二分查找 | +| ----------------- | ----- | ---- | +| 100个元素 | 100ms | 7ms | +| 10000个元素 | 10s | 14ms | +| 1 000 000 000 个元素 | 11天 | 30ms | + +- 大`O`表示法指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 +使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` + - 一些常见的大O运行时间 +- O(log n) ,也叫对数时间,这样的算法包括二分算法 +- O(n),也叫线性时间,这样的算法包括简单查找。 +- O(n * log n) 快速排序 +- O(n2),选择排序 +- O(n!) 即阶乘时间 + - 这里是重点 +- 算法的速度指的并非时间,而是操作数的增速 +- 谈论算法的速度时间时,我们说的是随着输入的增加,其运行时间将以什么样的速度增加 +- 算法的运行时间用大O表示法表示 +- O(log n)比O(n)快,当需要搜索的元素越多时,前者比后者快的越多 ## 编写解决实际问题的程序过程 @@ -148,14 +164,14 @@ left|right ## 数据(Data) -- 是客观事物的符号表示,在计算机科学中指的是所有能输入到计算机中并被计算机程序处理的符号的总称。 -- 数据元素(Data Element) :是数据的基本单位,在程序中通常作为一个整体来进行考虑和处理。一个数据元素可由若干个数据项(Data Item)组成。 -- 数据项(Data Item) : 是数据的不可分割的最小单位。数据项是对客观事物某一方面特性的数据描述。 -- 数据对象(Data Object) :是性质相同的数据元素的集合,是数据的一个子集。如字符集合C={‘A’,’B’,’C,…} 。 -- 数据结构 :相互之间具有一定联系的数据元素的集合。 -- 数据的逻辑结构 : 数据元素之间的相互关系称为逻辑结构。 -- 数据操作 : 对数据要进行的运算 -- 数据类型(Data Type):指的是一个值的集合和定义在该值集上的一组操作的总称。 +- 是客观事物的符号表示,在计算机科学中指的是所有能输入到计算机中并被计算机程序处理的符号的总称。 +- 数据元素(Data Element) :是数据的基本单位,在程序中通常作为一个整体来进行考虑和处理。一个数据元素可由若干个数据项(Data Item)组成。 +- 数据项(Data Item) : 是数据的不可分割的最小单位。数据项是对客观事物某一方面特性的数据描述。 +- 数据对象(Data Object) :是性质相同的数据元素的集合,是数据的一个子集。如字符集合C={‘A’,’B’,’C,…} 。 +- 数据结构 :相互之间具有一定联系的数据元素的集合。 +- 数据的逻辑结构 : 数据元素之间的相互关系称为逻辑结构。 +- 数据操作 : 对数据要进行的运算 +- 数据类型(Data Type):指的是一个值的集合和定义在该值集上的一组操作的总称。 ## 数据的逻辑结构有四种基本类型 @@ -173,10 +189,10 @@ left|right 数据的逻辑结构和物理结构是密不可分的两个方面,一个算法的设计取决于所选定的逻辑结构,而算法的实现依赖于所采用的存储结构 - ## 算法(Algorithm) 是对特定问题求解方法(步骤)的一种描述,是指令的有限序列,其中每一条指令表示一个或多个操作。 + > 算法具有以下五个特性 - 有穷性: 一个算法必须总是在执行有穷步之后结束,且每一步都在有穷时间内完成 @@ -199,9 +215,11 @@ left|right > 效率与存储量需求: 效率指的是算法执行的时间;存储量需求指算法执行过程中所需要的最大存储空间,一般地,这两者与问题的规模有关 ## 算法的时间复杂度 + 算法中基本操作重复执行的次数是问题规模n的某个函数,其时间量度记作T(n)=O(f(n)),称作算法的渐近时间复杂度(Asymptotic Time complexity),简称时间复杂度 ## 算法的空间复杂度 + 是指算法编写成程序后,在计算机中运行时所需存储空间大小的度量,记作:S(n)=O(f(n)),其中n为问题规模 ## 递归和循环的简单比较: @@ -212,6 +230,7 @@ left|right 4. 一般来说,非递归的效率高于递归。而且递归函数调用是有开销的,递归的次数受堆栈大小的限制。 ## 一起进步学习 + 1. Fork 我的项目并提交你的 `idea` 2. Pull Request 3. Merge @@ -219,14 +238,23 @@ left|right ## 纠错 如果大家发现有什么不对的地方,可以发起一个[issue](https://github.com/PuShaoWei/arithmetic-php/issues)或者[pull request](https://github.com/PuShaoWei/arithmetic-php/pulls),我会及时纠正 + > 补充:发起pull request的commit message请参考文章[Commit message 和 Change log 编写指南](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html) ## 致谢 + 感谢以下朋友的issue或pull request: + - [hailwood ](https://github.com/hailwood) + - [zhangxuanru](https://github.com/zhangxuanru) + - [ifreesec](https://github.com/ifreesec) + - [openset](https://github.com/openset) + - [Neroxiezi](https://github.com/Neroxiezi) -## License + + ## License + MIT From be4c6ff3175aa234985e2269716ede77ccac55c9 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Wed, 25 Apr 2018 16:07:22 +0800 Subject: [PATCH 102/127] =?UTF-8?q?style:=20=E4=BF=AE=E6=AD=A3readme?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 7 +++++-- README.md | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/README-EN.md b/README-EN.md index 5c8b915..73e1d11 100644 --- a/README-EN.md +++ b/README-EN.md @@ -66,7 +66,7 @@ │ └── Square.php │ └── Prim.php │ └── CartesianProduct.php -│ └── RotationSort.php +│ └── RotationSort.php │ ├──LICENSE └──README.md @@ -149,12 +149,15 @@ If you find something wrong, you can initiate a [issue](https://github.com/PuSha Thanks for the issue or pull request of the following friends: - [hailwood ](https://github.com/hailwood) + - [zhangxuanru](https://github.com/zhangxuanru) + - [ifreesec](https://github.com/ifreesec) + - [openset](https://github.com/openset) + - [Neroxiezi](https://github.com/Neroxiezi) ## License - MIT diff --git a/README.md b/README.md index 49745f8..8e4c786 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 │ └── Prim.php Prim算法(最小生成树算法) │ └── CartesianProduct.php 笛卡尔积算法 -│ └── RotationSort.php 面试题之平面任意四点能否组成一个矩形 +│ └── RotationSort.php 面试题之平面任意四点能否组成一个矩形 │ │ ├──LICENSE From 83a8787f6bfe29d6cdfee6de1505ef91e9725548 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Sat, 28 Apr 2018 18:44:53 +0800 Subject: [PATCH 103/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E4=BA=94=E5=BC=A0=E7=89=8C=E6=98=AF=E4=B8=8D=E6=98=AF=E9=A1=BA?= =?UTF-8?q?=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/Judge.php | 68 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 package/Other/Judge.php diff --git a/package/Other/Judge.php b/package/Other/Judge.php new file mode 100644 index 0000000..40fc35d --- /dev/null +++ b/package/Other/Judge.php @@ -0,0 +1,68 @@ + Date: Mon, 30 Apr 2018 19:48:16 +0800 Subject: [PATCH 104/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=9D=A2=E8=AF=95?= =?UTF-8?q?=E9=A2=98=E4=BB=BB=E9=80=89=E4=BA=94=E5=BC=A0=E7=89=8C=EF=BC=8C?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=98=AF=E4=B8=8D=E6=98=AF=E9=A1=BA=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 9 +++++---- package/Other/Judge.php | 9 +++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/README-EN.md b/README-EN.md index 73e1d11..a03df5a 100644 --- a/README-EN.md +++ b/README-EN.md @@ -1,4 +1,4 @@ -

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

+​

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

@@ -66,7 +66,8 @@ │ └── Square.php │ └── Prim.php │ └── CartesianProduct.php -│ └── RotationSort.php +│ └── Square.php +│ └── Judge.php │ ├──LICENSE └──README.md @@ -112,7 +113,7 @@ In this case, you know how fast these algorithms are | 1 000 000 000 | 11day | 30ms | - ` 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 -Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` + Using large ` O ` said ` O (n) to make this operation `, binary search need to perform logn using large ` O ` said to`O(log n)` - Some common big O runtime - O(log n) ,It's also called log time, and this algorithm includes binary algorithms - O(n),Also known as linear time, this algorithm includes simple lookups. @@ -130,7 +131,7 @@ Using large ` O ` said ` O (n) to make this operation `, binary search need to p 1. From a procedural point of view, the recursion manifests itself as calling itself, and the loop does not have this form. 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. 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. -4.In general, non-recursive efficiency is higher than recursion. And recursive function calls are expensive and recursive times are limited by stack size. + 4.In general, non-recursive efficiency is higher than recursion. And recursive function calls are expensive and recursive times are limited by stack size. ## Progressive learning diff --git a/package/Other/Judge.php b/package/Other/Judge.php index 40fc35d..a69ef43 100644 --- a/package/Other/Judge.php +++ b/package/Other/Judge.php @@ -62,7 +62,8 @@ function judge(array $array) return false; } -$res = judge([1,2,3,4,5]); -$res = judge([1,2,0,3,5]); -$res = judge([1,5,0,3,0]); -var_dump($res); \ No newline at end of file +$res1 = judge([1,2,3,4,5]); //没有王 +$res2 = judge([1,2,0,3,5]);// 一张王 +$res3 = judge([1,5,0,3,0]); // 两张王牌 +$res4 = judge([1,5,8,3,7]); +var_dump($res1,$res2,$res3,$res4); \ No newline at end of file From 4c941d37c95312e476fee8fd4fa24b1e63373a6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=97=B2=E4=BA=91=E9=87=8E=E9=B9=A4?= Date: Mon, 30 Apr 2018 19:52:29 +0800 Subject: [PATCH 105/127] =?UTF-8?q?=E5=A2=9E=E5=8A=A0readme?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8e4c786..61b0c40 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -

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

+​

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

@@ -80,7 +80,8 @@ │ └── Square.php Facebook面试题之判断四个点能否组成正方形算法 │ └── Prim.php Prim算法(最小生成树算法) │ └── CartesianProduct.php 笛卡尔积算法 -│ └── RotationSort.php 面试题之平面任意四点能否组成一个矩形 +│ └── Square.php 面试题之平面任意四点能否组成一个矩形 +│ └── Judge.php 面试题之扑克牌中任选五张判断是不是顺子 │ │ ├──LICENSE @@ -141,7 +142,7 @@ log10100 相当于问"将多少个10相乘的结果为100",答案 | 1 000 000 000 个元素 | 11天 | 30ms | - 大`O`表示法指出了算法有多快,例如列表包含`n`个元素,简单查找需要检查每个元素,因此需要执行`n`次操作 -使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` + 使用大`O`表示法这个运行时间为`O(n)`,二分查找需要执行logn次操作,使用大`O`表示为`O(log n)` - 一些常见的大O运行时间 - O(log n) ,也叫对数时间,这样的算法包括二分算法 - O(n),也叫线性时间,这样的算法包括简单查找。 From 3c9240bdfa48c0d784e10e60d3d1d9bbf33f6e5b Mon Sep 17 00:00:00 2001 From: xianyun Date: Fri, 4 May 2018 14:11:22 +0800 Subject: [PATCH 106/127] =?UTF-8?q?Add:=E6=B1=82=E8=A7=A3N=E7=9A=84?= =?UTF-8?q?=E9=98=B6=E4=B9=98=E6=9C=80=E5=90=8E=E6=9C=89=E5=A4=9A=E5=B0=91?= =?UTF-8?q?=E4=B8=AA0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/Other/Factorial.php | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 package/Other/Factorial.php diff --git a/package/Other/Factorial.php b/package/Other/Factorial.php new file mode 100644 index 0000000..ccd2869 --- /dev/null +++ b/package/Other/Factorial.php @@ -0,0 +1,44 @@ + Date: Fri, 4 May 2018 14:15:48 +0800 Subject: [PATCH 107/127] =?UTF-8?q?'=E5=A2=9E=E5=8A=A0readme'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + 2 files changed, 2 insertions(+) diff --git a/README-EN.md b/README-EN.md index a03df5a..1983fc5 100644 --- a/README-EN.md +++ b/README-EN.md @@ -68,6 +68,7 @@ │ └── CartesianProduct.php │ └── Square.php │ └── Judge.php +│ └── Factorial.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index 61b0c40..bd8692e 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ │ └── CartesianProduct.php 笛卡尔积算法 │ └── Square.php 面试题之平面任意四点能否组成一个矩形 │ └── Judge.php 面试题之扑克牌中任选五张判断是不是顺子 +│ └── Factorial.php 面试题之N的阶乘末尾有多少个0 │ │ ├──LICENSE From ecb8fcf4419a5abb20ee6483cc67cc2844981e29 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Mon, 7 May 2018 18:10:54 +0800 Subject: [PATCH 108/127] Add:BinarySearchTree --- package/Structure/BinarySearchTree.php | 129 +++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 package/Structure/BinarySearchTree.php diff --git a/package/Structure/BinarySearchTree.php b/package/Structure/BinarySearchTree.php new file mode 100644 index 0000000..cc3fea2 --- /dev/null +++ b/package/Structure/BinarySearchTree.php @@ -0,0 +1,129 @@ +value = $data; + $node->left = null; + $node->right = null; + return $node; + } + + + /** + * 插入节点 + * @param $node 根节点 + * @param $value 关键值 + */ + public function insert(&$node, $value) + { + if(empty($value) && $value !== 0) { + return ; + } + + if ($node == null) { + $node = $this->createNode($value); + } else if ($value < $node->value) { + $this->insert($node->left, $value); + } else { + $this->insert($node->right, $value); + } + } + + /** + * 先序遍历 + * @param $node 根节点 + */ + public function preOrder(&$node) + { + if ($node != null) { + echo $node->value . PHP_EOL ; + $this->preOrder($node->left); + $this->preOrder($node->right); + } + + } + /** + * 中序遍历 + * @param $node 根节点 + */ + public function middleOrder(&$node) + { + if ($node != null) { + $this->middleOrder($node->left); + echo $node->value . PHP_EOL ; + $this->middleOrder($node->right); + } + + } + + /** + * 后序遍历 + * @param $node 根节点 + */ + public function afterOrder(&$node) + { + if ($node != null) { + $this->afterOrder($node->left); + $this->afterOrder($node->right); + echo $node->value . PHP_EOL; + } + } + + /** + * 获取最大值 + * @param $node 根节点 + */ + public function findMax(&$node) + { + while($node->right != null) { + $node = $node->right; + } + return $node->value; + } + +} + +$tree = new BinarySearchTree(); +$tree->insert($tree->root, 3); +$tree->insert($tree->root, 9); +$tree->insert($tree->root, 2); +$tree->insert($tree->root, 20); + +echo "先序遍历".PHP_EOL; +$tree->preOrder($tree->root); //324 +echo "中序遍历" . PHP_EOL; + +$tree->middleOrder($tree->root); //324 +echo "后序遍历" . PHP_EOL; + +$tree->afterOrder($tree->root); //234 + +$max = $tree->findMax($tree->root); + +var_dump($max); \ No newline at end of file From f4ca788aacabc347309b26855ff66493c5a923a8 Mon Sep 17 00:00:00 2001 From: xianyunyh Date: Mon, 7 May 2018 18:14:35 +0800 Subject: [PATCH 109/127] =?UTF-8?q?=E4=BF=AE=E6=94=B9README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bd8692e..ec92cd9 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,8 @@ │ ├── Structure 数据结构 │ │ ├── StackExample.php 堆栈 先进后出 LIFO (Last In First Out) │ │ ├── LinearChain.php 线性表 单链存储 -│ │ └── LinearOrder.php 线性表 顺序存储 +│ │ └── LinearOrder.php 线性表 顺序存储 +│ │ └── BinarySearchTree.php 二叉搜索树 │ │ │ ├── Tools 小工具集 │ │ └── SystemSwitch.php 堆栈实现进制转换 From c42091198cf81e8a2363b3a72fe984a255a095b9 Mon Sep 17 00:00:00 2001 From: Riverside Date: Wed, 22 Aug 2018 16:52:58 +0800 Subject: [PATCH 110/127] Update Square.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit for 循环不需要`count($this->point)`,因为确定为4;使用 `pow()`平方函数 --- package/Other/Square.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/package/Other/Square.php b/package/Other/Square.php index c0b7614..0566953 100644 --- a/package/Other/Square.php +++ b/package/Other/Square.php @@ -20,8 +20,8 @@ public function check() { $result = []; if (count($this->point) != 4) return false; - for ($i = 0; $i < count($this->point); $i++) { - for ($j = $i + 1; $j < count($this->point); $j++) { + for ($i = 0; $i < 4; $i++) { + for ($j = $i + 1; $j < 4; $j++) { $result[]=$this->_calculation($i,$j); } } @@ -35,9 +35,9 @@ public function check() private function _calculation($i, $j) { - return ($this->point[$i][0] - $this->point[$j][0]) * ($this->point[$i][0] - $this->point[$j][0]) + ($this->point[$i][1] - $this->point[$j][1]) * ($this->point[$i][1] - $this->point[$j][1]); + return pow($this->point[$i][0] - $this->point[$j][0],2) + pow($this->point[$i][1] - $this->point[$j][1] ,2); } } $obj = new Square([[0, 0], [1, 0], [1, 1], [0, 1]]); -var_dump($obj->check()); \ No newline at end of file +var_dump($obj->check()); From 93f021cd06dcba73654664d6bb9e1ce253c059a8 Mon Sep 17 00:00:00 2001 From: Marco Date: Wed, 5 Dec 2018 09:38:50 +0800 Subject: [PATCH 111/127] Update BinaryQuery.php --- package/Query/BinaryQuery.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package/Query/BinaryQuery.php b/package/Query/BinaryQuery.php index f8d0560..167da6b 100644 --- a/package/Query/BinaryQuery.php +++ b/package/Query/BinaryQuery.php @@ -55,7 +55,7 @@ function BinaryQuery(array $container, $search) */ function BinaryQueryRecursive(array $container, $search, $low = 0, $top = 'default') { - $top == 'default' && $top = count($container); + $top === 'default' && $top = count($container); if ($low <= $top) { $mid = intval(floor($low + $top) / 2); if (!isset($container[$mid])) { @@ -98,4 +98,4 @@ function BinaryQueryRecursive(array $container, $search, $low = 0, $top = 'defau [6] => int(9) } -*/ \ No newline at end of file +*/ From 2186427238aeb134d866b71ddb2b2270c26771e7 Mon Sep 17 00:00:00 2001 From: xingwangliu Date: Tue, 22 Jan 2019 10:12:51 +0800 Subject: [PATCH 112/127] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=94=99=E5=88=AB?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec92cd9..35a9026 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ ## 当然 ``` -用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这觉不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 +用 PHP 实现算法并替代官方提供的函数是愚蠢的事情 .但这决不代表斟酌算法就是件无意义的事 , 每个算法都是一种思想的结晶 , 学习优秀的思想 , 开拓思维 ``` ## 什么是算法? From 26b7879be2319f3a9c23ea72b3fba5c367ffb868 Mon Sep 17 00:00:00 2001 From: wxxiong6 <601115211@qq.com> Date: Thu, 9 May 2019 09:19:58 +0800 Subject: [PATCH 113/127] HashTable HashTable --- package/Other/HashTable.php | 130 ++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 package/Other/HashTable.php diff --git a/package/Other/HashTable.php b/package/Other/HashTable.php new file mode 100644 index 0000000..cdd6b10 --- /dev/null +++ b/package/Other/HashTable.php @@ -0,0 +1,130 @@ + + * @date 2019/5/9 + * @license MIT + * ------------------------------------------------------------- + * HashTable + */ + + +define('TABLE_SIZE', 100); + +class KeyValue +{ + public $key; + public $value; + + public function __construct($key, $value) + { + $this->key = $key; + $this->value = $value; + } +} + +class HashTable +{ + public $size = 0; + public $data = []; +} + +function create_table($size = TABLE_SIZE) +{ + $table = new HashTable(); + for ($i = 0; $i < $size; ++$i) { + $table->data[$i] = null; + } + $table->size = 100; + + return $table; +} + +function destroy_table(&$table) +{ + unset($table); +} + +function hash_key($key, $size = TABLE_SIZE) +{ + $len = strlen($key); + $hash = 0; + for ($i = 0; $i < $len; ++$i) { + $hash = $hash * 31 + ord($key[$i]); + } + + return abs($hash % $size); +} + +function print_debug($table) +{ + for ($i = 0; $i < $table->size; ++$i) { + if (null === $table->data[$i]) { + echo $i, "\n"; + } else { + echo $i, ' key=', $table->data[$i]->key, ', value=', $table->data[$i]->value , "\n"; + } + } +} + +function exists(&$table, $key) +{ + $index = hash_key($key); + if (null === $table->data[$index]) { + return false; + } + + if (0 === strcmp($key, $table->data[$index]->key)) { + return true; + } + + return false; +} + +function add(&$table, $key, KeyValue $object) +{ + $index = hash_key($key); + $table->data[$index] = $object; +} + +function get(&$table, $key) +{ + $index = hash_key($key); + if (0 === strcmp($key, $table->data[$index]->key)) { + return $table->data[$index]->value; + } +} + +function delete(&$table, $key) +{ + $index = hash_key($key); + if (null === $table->data[$index]) { + return; + } + if (0 === strcmp($key, $table->data[$index]->key)) { + return $table->data[$index] = null; + } +} + +$hash_table = create_table(); +print_debug($hash_table); + +add($hash_table, 'Wang', new KeyValue('Wang', '50')); +add($hash_table, 'Li', new KeyValue('Li', '20')); +add($hash_table, 'Chow', new KeyValue('Chow', '23')); +print_debug($hash_table); + +//get +echo "----------get-------------- \n"; +var_dump(get($hash_table, 'Wang')); + +//delete +echo "----------delete-------------- \n"; +delete($hash_table, 'Wang'); +var_dump(delete($hash_table, 'Wang')); + +//exists +echo "----------exists-------------- \n"; +var_dump(exists($hash_table, 'Wang')); +var_dump(exists($hash_table, 'Li')); \ No newline at end of file From 9d55e933ad80bcf0db8e09a399fd9fb159ff7bd2 Mon Sep 17 00:00:00 2001 From: wxxiong6 <601115211@qq.com> Date: Thu, 9 May 2019 09:21:12 +0800 Subject: [PATCH 114/127] Update README-EN.md --- README-EN.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README-EN.md b/README-EN.md index 1983fc5..c1998e4 100644 --- a/README-EN.md +++ b/README-EN.md @@ -69,6 +69,7 @@ │ └── Square.php │ └── Judge.php │ └── Factorial.php +| └── HashTable.php │ ├──LICENSE └──README.md From 697ddd37068e281031e1377773f9be9f95a881c7 Mon Sep 17 00:00:00 2001 From: wxxiong6 <601115211@qq.com> Date: Thu, 9 May 2019 09:21:52 +0800 Subject: [PATCH 115/127] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec92cd9..e77d2c0 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ │ └── Square.php 面试题之平面任意四点能否组成一个矩形 │ └── Judge.php 面试题之扑克牌中任选五张判断是不是顺子 │ └── Factorial.php 面试题之N的阶乘末尾有多少个0 -│ +| └── HashTable.php HashTable │ ├──LICENSE └──README.md From 5798cd4615e375c1f680b39016be3fd52d17fdf7 Mon Sep 17 00:00:00 2001 From: pushaowei Date: Fri, 17 May 2019 10:30:00 +0800 Subject: [PATCH 116/127] fix: Update the directory structure --- .gitignore | 2 + composer.json | 38 +++++++++++++++++++ docker-compose.yml | 9 +++++ phpunit.xml | 20 ++++++++++ {package => src}/Features/SystemSwitch.php | 0 {package => src}/Features/YieldExample.php | 0 {package => src}/Other/AntsClimb.php | 0 {package => src}/Other/BidirectionalQueue.php | 0 {package => src}/Other/BigSmallReplace.php | 0 {package => src}/Other/CartesianProduct.php | 0 {package => src}/Other/ColorBricks.php | 0 {package => src}/Other/DynamicProgramming.php | 0 {package => src}/Other/ElevatorDispatch.php | 0 {package => src}/Other/Encryption.php | 0 {package => src}/Other/Factorial.php | 0 {package => src}/Other/Fibonacci.php | 0 {package => src}/Other/GetCattle.php | 0 {package => src}/Other/HanoiGames.php | 0 {package => src}/Other/Interval.php | 0 {package => src}/Other/Judge.php | 0 {package => src}/Other/Knapsack.php | 0 {package => src}/Other/Maze.php | 0 {package => src}/Other/MonkeyKing.php | 0 {package => src}/Other/OnlyNumbers.php | 0 {package => src}/Other/PointInTriangle.php | 0 {package => src}/Other/PokerGames.php | 0 {package => src}/Other/Prim.php | 0 {package => src}/Other/Rectangle.php | 0 {package => src}/Other/RotationSort.php | 0 {package => src}/Other/Solution.php | 0 {package => src}/Other/Square.php | 0 {package => src}/Other/StealingApples.php | 0 {package => src}/Query/BFSQuery.php | 0 {package => src}/Query/BinaryQuery.php | 0 {package => src}/Query/BinarySearchTree.php | 0 {package => src}/Query/DijkstraQuery.php | 0 {package => src}/Query/FibonacciQuery.php | 0 {package => src}/Query/InsertQuery.php | 0 {package => src}/Query/Kmp.php | 0 {package => src}/Query/QuickQuery.php | 0 {package => src}/Sort/BubbleSort.php | 0 {package => src}/Sort/HeapSort.php | 0 {package => src}/Sort/InsertSort.php | 0 {package => src}/Sort/MergeSort.php | 0 {package => src}/Sort/QuickSort.php | 0 {package => src}/Sort/SelectSort.php | 0 {package => src}/Sort/ShellSort.php | 0 {package => src}/Sort/ShuttleSort.php | 0 .../Structure/BinarySearchTree.php | 0 {package => src}/Structure/KitchenQueue.php | 0 {package => src}/Structure/LinearChain.php | 0 {package => src}/Structure/LinearOrder.php | 0 {package => src}/Structure/StackExample.php | 0 tests/BootStrapTest.php | 4 ++ tests/Sort/ChineseTextNumberSortTest.php | 24 ++++++++++++ 55 files changed, 97 insertions(+) create mode 100644 composer.json create mode 100644 docker-compose.yml create mode 100644 phpunit.xml rename {package => src}/Features/SystemSwitch.php (100%) rename {package => src}/Features/YieldExample.php (100%) rename {package => src}/Other/AntsClimb.php (100%) rename {package => src}/Other/BidirectionalQueue.php (100%) rename {package => src}/Other/BigSmallReplace.php (100%) rename {package => src}/Other/CartesianProduct.php (100%) rename {package => src}/Other/ColorBricks.php (100%) rename {package => src}/Other/DynamicProgramming.php (100%) rename {package => src}/Other/ElevatorDispatch.php (100%) rename {package => src}/Other/Encryption.php (100%) rename {package => src}/Other/Factorial.php (100%) rename {package => src}/Other/Fibonacci.php (100%) rename {package => src}/Other/GetCattle.php (100%) rename {package => src}/Other/HanoiGames.php (100%) rename {package => src}/Other/Interval.php (100%) rename {package => src}/Other/Judge.php (100%) rename {package => src}/Other/Knapsack.php (100%) rename {package => src}/Other/Maze.php (100%) rename {package => src}/Other/MonkeyKing.php (100%) rename {package => src}/Other/OnlyNumbers.php (100%) rename {package => src}/Other/PointInTriangle.php (100%) rename {package => src}/Other/PokerGames.php (100%) rename {package => src}/Other/Prim.php (100%) rename {package => src}/Other/Rectangle.php (100%) rename {package => src}/Other/RotationSort.php (100%) rename {package => src}/Other/Solution.php (100%) rename {package => src}/Other/Square.php (100%) rename {package => src}/Other/StealingApples.php (100%) rename {package => src}/Query/BFSQuery.php (100%) rename {package => src}/Query/BinaryQuery.php (100%) rename {package => src}/Query/BinarySearchTree.php (100%) rename {package => src}/Query/DijkstraQuery.php (100%) rename {package => src}/Query/FibonacciQuery.php (100%) rename {package => src}/Query/InsertQuery.php (100%) rename {package => src}/Query/Kmp.php (100%) rename {package => src}/Query/QuickQuery.php (100%) rename {package => src}/Sort/BubbleSort.php (100%) rename {package => src}/Sort/HeapSort.php (100%) rename {package => src}/Sort/InsertSort.php (100%) rename {package => src}/Sort/MergeSort.php (100%) rename {package => src}/Sort/QuickSort.php (100%) rename {package => src}/Sort/SelectSort.php (100%) rename {package => src}/Sort/ShellSort.php (100%) rename {package => src}/Sort/ShuttleSort.php (100%) rename {package => src}/Structure/BinarySearchTree.php (100%) rename {package => src}/Structure/KitchenQueue.php (100%) rename {package => src}/Structure/LinearChain.php (100%) rename {package => src}/Structure/LinearOrder.php (100%) rename {package => src}/Structure/StackExample.php (100%) create mode 100644 tests/BootStrapTest.php create mode 100644 tests/Sort/ChineseTextNumberSortTest.php diff --git a/.gitignore b/.gitignore index f32e31a..8d6193c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea/ .DS_Store +composer.lock +vendor \ No newline at end of file diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..25a5d5a --- /dev/null +++ b/composer.json @@ -0,0 +1,38 @@ +{ + "name": "algorithm-php", + "description": "algorithm-php", + "minimum-stability": "stable", + "license": "MIT", + "authors": [ + { + "name": "pushaowei" + } + ], + "require-dev": { + "phpunit/phpunit": "~6.0", + "mockery/mockery": "~0.9" + }, + "autoload-dev": { + "classmap": [ + "tests/" + ] + }, + "prefer-stable": true, + "config": { + "optimize-autoloader": true + }, + "repositories": { + "packagist": { + "type": "composer", + "url": "https://packagist.phpcomposer.com" + } + }, + "require": { + "ext-json": "*", + "ext-ctype": "*", + "ext-openssl": "*", + "php": ">=5.6.4", + "ext-curl": "*", + "stojg/recommend": "^1.0" + } +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..4cf0e34 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,9 @@ +version: '2.0' +services: + php71-dev: + image: "m9rco/php:7.1-dev" + ports: + - "2222:22" + - "29000:9000" + volumes: + - $PWD:/app:rw \ No newline at end of file diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..5dd071d --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,20 @@ + + + + + + + + + ./tests + + + \ No newline at end of file diff --git a/package/Features/SystemSwitch.php b/src/Features/SystemSwitch.php similarity index 100% rename from package/Features/SystemSwitch.php rename to src/Features/SystemSwitch.php diff --git a/package/Features/YieldExample.php b/src/Features/YieldExample.php similarity index 100% rename from package/Features/YieldExample.php rename to src/Features/YieldExample.php diff --git a/package/Other/AntsClimb.php b/src/Other/AntsClimb.php similarity index 100% rename from package/Other/AntsClimb.php rename to src/Other/AntsClimb.php diff --git a/package/Other/BidirectionalQueue.php b/src/Other/BidirectionalQueue.php similarity index 100% rename from package/Other/BidirectionalQueue.php rename to src/Other/BidirectionalQueue.php diff --git a/package/Other/BigSmallReplace.php b/src/Other/BigSmallReplace.php similarity index 100% rename from package/Other/BigSmallReplace.php rename to src/Other/BigSmallReplace.php diff --git a/package/Other/CartesianProduct.php b/src/Other/CartesianProduct.php similarity index 100% rename from package/Other/CartesianProduct.php rename to src/Other/CartesianProduct.php diff --git a/package/Other/ColorBricks.php b/src/Other/ColorBricks.php similarity index 100% rename from package/Other/ColorBricks.php rename to src/Other/ColorBricks.php diff --git a/package/Other/DynamicProgramming.php b/src/Other/DynamicProgramming.php similarity index 100% rename from package/Other/DynamicProgramming.php rename to src/Other/DynamicProgramming.php diff --git a/package/Other/ElevatorDispatch.php b/src/Other/ElevatorDispatch.php similarity index 100% rename from package/Other/ElevatorDispatch.php rename to src/Other/ElevatorDispatch.php diff --git a/package/Other/Encryption.php b/src/Other/Encryption.php similarity index 100% rename from package/Other/Encryption.php rename to src/Other/Encryption.php diff --git a/package/Other/Factorial.php b/src/Other/Factorial.php similarity index 100% rename from package/Other/Factorial.php rename to src/Other/Factorial.php diff --git a/package/Other/Fibonacci.php b/src/Other/Fibonacci.php similarity index 100% rename from package/Other/Fibonacci.php rename to src/Other/Fibonacci.php diff --git a/package/Other/GetCattle.php b/src/Other/GetCattle.php similarity index 100% rename from package/Other/GetCattle.php rename to src/Other/GetCattle.php diff --git a/package/Other/HanoiGames.php b/src/Other/HanoiGames.php similarity index 100% rename from package/Other/HanoiGames.php rename to src/Other/HanoiGames.php diff --git a/package/Other/Interval.php b/src/Other/Interval.php similarity index 100% rename from package/Other/Interval.php rename to src/Other/Interval.php diff --git a/package/Other/Judge.php b/src/Other/Judge.php similarity index 100% rename from package/Other/Judge.php rename to src/Other/Judge.php diff --git a/package/Other/Knapsack.php b/src/Other/Knapsack.php similarity index 100% rename from package/Other/Knapsack.php rename to src/Other/Knapsack.php diff --git a/package/Other/Maze.php b/src/Other/Maze.php similarity index 100% rename from package/Other/Maze.php rename to src/Other/Maze.php diff --git a/package/Other/MonkeyKing.php b/src/Other/MonkeyKing.php similarity index 100% rename from package/Other/MonkeyKing.php rename to src/Other/MonkeyKing.php diff --git a/package/Other/OnlyNumbers.php b/src/Other/OnlyNumbers.php similarity index 100% rename from package/Other/OnlyNumbers.php rename to src/Other/OnlyNumbers.php diff --git a/package/Other/PointInTriangle.php b/src/Other/PointInTriangle.php similarity index 100% rename from package/Other/PointInTriangle.php rename to src/Other/PointInTriangle.php diff --git a/package/Other/PokerGames.php b/src/Other/PokerGames.php similarity index 100% rename from package/Other/PokerGames.php rename to src/Other/PokerGames.php diff --git a/package/Other/Prim.php b/src/Other/Prim.php similarity index 100% rename from package/Other/Prim.php rename to src/Other/Prim.php diff --git a/package/Other/Rectangle.php b/src/Other/Rectangle.php similarity index 100% rename from package/Other/Rectangle.php rename to src/Other/Rectangle.php diff --git a/package/Other/RotationSort.php b/src/Other/RotationSort.php similarity index 100% rename from package/Other/RotationSort.php rename to src/Other/RotationSort.php diff --git a/package/Other/Solution.php b/src/Other/Solution.php similarity index 100% rename from package/Other/Solution.php rename to src/Other/Solution.php diff --git a/package/Other/Square.php b/src/Other/Square.php similarity index 100% rename from package/Other/Square.php rename to src/Other/Square.php diff --git a/package/Other/StealingApples.php b/src/Other/StealingApples.php similarity index 100% rename from package/Other/StealingApples.php rename to src/Other/StealingApples.php diff --git a/package/Query/BFSQuery.php b/src/Query/BFSQuery.php similarity index 100% rename from package/Query/BFSQuery.php rename to src/Query/BFSQuery.php diff --git a/package/Query/BinaryQuery.php b/src/Query/BinaryQuery.php similarity index 100% rename from package/Query/BinaryQuery.php rename to src/Query/BinaryQuery.php diff --git a/package/Query/BinarySearchTree.php b/src/Query/BinarySearchTree.php similarity index 100% rename from package/Query/BinarySearchTree.php rename to src/Query/BinarySearchTree.php diff --git a/package/Query/DijkstraQuery.php b/src/Query/DijkstraQuery.php similarity index 100% rename from package/Query/DijkstraQuery.php rename to src/Query/DijkstraQuery.php diff --git a/package/Query/FibonacciQuery.php b/src/Query/FibonacciQuery.php similarity index 100% rename from package/Query/FibonacciQuery.php rename to src/Query/FibonacciQuery.php diff --git a/package/Query/InsertQuery.php b/src/Query/InsertQuery.php similarity index 100% rename from package/Query/InsertQuery.php rename to src/Query/InsertQuery.php diff --git a/package/Query/Kmp.php b/src/Query/Kmp.php similarity index 100% rename from package/Query/Kmp.php rename to src/Query/Kmp.php diff --git a/package/Query/QuickQuery.php b/src/Query/QuickQuery.php similarity index 100% rename from package/Query/QuickQuery.php rename to src/Query/QuickQuery.php diff --git a/package/Sort/BubbleSort.php b/src/Sort/BubbleSort.php similarity index 100% rename from package/Sort/BubbleSort.php rename to src/Sort/BubbleSort.php diff --git a/package/Sort/HeapSort.php b/src/Sort/HeapSort.php similarity index 100% rename from package/Sort/HeapSort.php rename to src/Sort/HeapSort.php diff --git a/package/Sort/InsertSort.php b/src/Sort/InsertSort.php similarity index 100% rename from package/Sort/InsertSort.php rename to src/Sort/InsertSort.php diff --git a/package/Sort/MergeSort.php b/src/Sort/MergeSort.php similarity index 100% rename from package/Sort/MergeSort.php rename to src/Sort/MergeSort.php diff --git a/package/Sort/QuickSort.php b/src/Sort/QuickSort.php similarity index 100% rename from package/Sort/QuickSort.php rename to src/Sort/QuickSort.php diff --git a/package/Sort/SelectSort.php b/src/Sort/SelectSort.php similarity index 100% rename from package/Sort/SelectSort.php rename to src/Sort/SelectSort.php diff --git a/package/Sort/ShellSort.php b/src/Sort/ShellSort.php similarity index 100% rename from package/Sort/ShellSort.php rename to src/Sort/ShellSort.php diff --git a/package/Sort/ShuttleSort.php b/src/Sort/ShuttleSort.php similarity index 100% rename from package/Sort/ShuttleSort.php rename to src/Sort/ShuttleSort.php diff --git a/package/Structure/BinarySearchTree.php b/src/Structure/BinarySearchTree.php similarity index 100% rename from package/Structure/BinarySearchTree.php rename to src/Structure/BinarySearchTree.php diff --git a/package/Structure/KitchenQueue.php b/src/Structure/KitchenQueue.php similarity index 100% rename from package/Structure/KitchenQueue.php rename to src/Structure/KitchenQueue.php diff --git a/package/Structure/LinearChain.php b/src/Structure/LinearChain.php similarity index 100% rename from package/Structure/LinearChain.php rename to src/Structure/LinearChain.php diff --git a/package/Structure/LinearOrder.php b/src/Structure/LinearOrder.php similarity index 100% rename from package/Structure/LinearOrder.php rename to src/Structure/LinearOrder.php diff --git a/package/Structure/StackExample.php b/src/Structure/StackExample.php similarity index 100% rename from package/Structure/StackExample.php rename to src/Structure/StackExample.php diff --git a/tests/BootStrapTest.php b/tests/BootStrapTest.php new file mode 100644 index 0000000..7c8ef73 --- /dev/null +++ b/tests/BootStrapTest.php @@ -0,0 +1,4 @@ + + * @date 2019-05-17 + * @version 1.0 + */ + + +class ChineseTextNumberSortTest extends PHPUnit\Framework\TestCase +{ + + /** + * description + * + * @test + */ + public function testAnalysisText() + { + var_dump(1); + die; + } +} From 371997c698479fa1a6bf1b525f83004edfef242e Mon Sep 17 00:00:00 2001 From: pushaowei Date: Fri, 17 May 2019 10:30:27 +0800 Subject: [PATCH 117/127] fix: Update the directory structure --- tests/Sort/ChineseTextNumberSortTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Sort/ChineseTextNumberSortTest.php b/tests/Sort/ChineseTextNumberSortTest.php index 05715e8..bbc5cda 100644 --- a/tests/Sort/ChineseTextNumberSortTest.php +++ b/tests/Sort/ChineseTextNumberSortTest.php @@ -2,7 +2,7 @@ /** * Test * - * @author Pu ShaoWei + * @author Pu ShaoWei * @date 2019-05-17 * @version 1.0 */ From dcc7c7266f33fe26ca069348a772fab77960e9c6 Mon Sep 17 00:00:00 2001 From: pushaowei Date: Fri, 17 May 2019 10:44:29 +0800 Subject: [PATCH 118/127] fix: Update the directory structure --- composer.json | 5 ++++ src/Query/BinarySearchTree.php | 31 ------------------------ src/Sort/ChineseTextNumberSort.php | 13 ++++++++++ tests/BootStrapTest.php | 2 -- tests/Sort/ChineseTextNumberSortTest.php | 1 + 5 files changed, 19 insertions(+), 33 deletions(-) delete mode 100644 src/Query/BinarySearchTree.php create mode 100644 src/Sort/ChineseTextNumberSort.php diff --git a/composer.json b/composer.json index 25a5d5a..ac7bce9 100644 --- a/composer.json +++ b/composer.json @@ -12,6 +12,11 @@ "phpunit/phpunit": "~6.0", "mockery/mockery": "~0.9" }, + "autoload": { + "classmap": [ + "./src" + ] + }, "autoload-dev": { "classmap": [ "tests/" diff --git a/src/Query/BinarySearchTree.php b/src/Query/BinarySearchTree.php deleted file mode 100644 index eb9b975..0000000 --- a/src/Query/BinarySearchTree.php +++ /dev/null @@ -1,31 +0,0 @@ - - * @date 2017/8/25 - * @license MIT - * ------------------------------------------------------------- - * 思路分析:x为二叉查找树中的一个结点,x节点包含关键字key,节点x的key值记为key[x] - * 如果y是x的左子树中的一个结点,则key[y] <= key[x]; - * 如果y是x的右子树的一个结点, 则key[y] >= key[x]。 - * ------------------------------------------------------------- - * 在二叉查找树中: - * (01) 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值; - * (02) 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值; - * (03) 任意节点的左、右子树也分别为二叉查找树。 - * (04) 没有键值相等的节点(no duplicate nodes)。 - */ - -// +-------------------------------------------------------------------------- -// | 解题方式 -// +-------------------------------------------------------------------------- -class BinarySearchTree -{ - -} - -// +-------------------------------------------------------------------------- -// | 方案测试 | php `this.php` || PHPStorm -> 右键 -> Run `this.php` -// +-------------------------------------------------------------------------- diff --git a/src/Sort/ChineseTextNumberSort.php b/src/Sort/ChineseTextNumberSort.php new file mode 100644 index 0000000..800ba5e --- /dev/null +++ b/src/Sort/ChineseTextNumberSort.php @@ -0,0 +1,13 @@ + Date: Fri, 17 May 2019 11:44:48 +0800 Subject: [PATCH 119/127] fix: Update the directory structure --- src/Sort/ChineseTextNumberSort.php | 46 ++++++++++++++++++++++++ tests/Sort/ChineseTextNumberSortTest.php | 9 +++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/src/Sort/ChineseTextNumberSort.php b/src/Sort/ChineseTextNumberSort.php index 800ba5e..f852362 100644 --- a/src/Sort/ChineseTextNumberSort.php +++ b/src/Sort/ChineseTextNumberSort.php @@ -9,5 +9,51 @@ */ class ChineseTextNumberSort { + const CHINESE_DIGITAL_MATCHING = '/零|一|二|三|四|五|六|七|八|九|十/'; + + /** + * 解析文本到十位 + * + * @param $text + * @return false|float|int|string + */ + public function parsingText($text) + { + $structure = ''; + $mapping = array ('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'); + preg_match_all('/一|二|三|四|五|六|七|八|九|十/', $text, $structure, PREG_PATTERN_ORDER); + if (empty($structure[0])) { + return 0; + } + $currentNum = 0; + foreach ($structure[0] as $plane => $matchNum) { + if ($matchNum === '十') { + if ($plane === 0) { + $currentNum += 10; + continue; + } + if ($plane === 1) { + $index = array_search($structure[0][0], $mapping); + $currentNum -= $index; + $currentNum += $index * 10; + continue; + } + } + $index = array_search($matchNum, $mapping); + $currentNum += $index; + } + return $currentNum; + } + + /** + * isChinese + * + * @param $text + * @return bool + */ + public function isCompletelyChinese($text) + { + return boolval(preg_match('/^[\x7f-\xff]+$/', $text)); + } } \ No newline at end of file diff --git a/tests/Sort/ChineseTextNumberSortTest.php b/tests/Sort/ChineseTextNumberSortTest.php index 3fc29b5..39b8bc7 100644 --- a/tests/Sort/ChineseTextNumberSortTest.php +++ b/tests/Sort/ChineseTextNumberSortTest.php @@ -18,8 +18,11 @@ class ChineseTextNumberSortTest extends PHPUnit\Framework\TestCase */ public function testAnalysisText() { - new ChineseTextNumberSort(); - var_dump(1); - die; + $chineseObj = new ChineseTextNumberSort(); + $this->assertTrue($chineseObj->isCompletelyChinese('我艹'), 'Is not entirely Chinese'); + $this->assertEquals($chineseObj->parsingText('第一十二章四十五'), 12); + $this->assertEquals($chineseObj->parsingText('十三'), 13); + $this->assertEquals($chineseObj->parsingText('二十三'), 23); + $this->assertEquals($chineseObj->parsingText('一十三'), 13); } } From 8601407b2203911cf01d681e0a343f755ab315ca Mon Sep 17 00:00:00 2001 From: pushaowei Date: Thu, 23 May 2019 18:42:40 +0800 Subject: [PATCH 120/127] =?UTF-8?q?feat:=20=E4=B8=AD=E6=96=87=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 3 +- src/Sort/ChineseTextNumberSort.php | 164 ++++++++- tests/Sort/ChineseTextNumberExtractTest.php | 336 ++++++++++++++++++ tests/Sort/ChineseTextNumberSortModelTest.php | 301 ++++++++++++++++ tests/Sort/ChineseTextNumberSortTest.php | 236 +++++++++++- 5 files changed, 1028 insertions(+), 12 deletions(-) create mode 100644 tests/Sort/ChineseTextNumberExtractTest.php create mode 100644 tests/Sort/ChineseTextNumberSortModelTest.php diff --git a/composer.json b/composer.json index ac7bce9..05a3a26 100644 --- a/composer.json +++ b/composer.json @@ -38,6 +38,7 @@ "ext-openssl": "*", "php": ">=5.6.4", "ext-curl": "*", - "stojg/recommend": "^1.0" + "stojg/recommend": "^1.0", + "ext-iconv": "*" } } diff --git a/src/Sort/ChineseTextNumberSort.php b/src/Sort/ChineseTextNumberSort.php index f852362..e795395 100644 --- a/src/Sort/ChineseTextNumberSort.php +++ b/src/Sort/ChineseTextNumberSort.php @@ -9,7 +9,25 @@ */ class ChineseTextNumberSort { - const CHINESE_DIGITAL_MATCHING = '/零|一|二|三|四|五|六|七|八|九|十/'; + /** + * @var string text + */ + const CHINESE_DIGITAL_MATCHING = '/\x{96f6}|\x{4e00}|\x{4e8c}|\x{4e09}|\x{56db}|\x{4e94}|\x{516d}|\x{4e03}|\x{516b}|\x{4e5d}|\x{5341}/ui'; + + /** + * @var string regular rules [! order can not arbitrarily change] + */ + const MODEL_REGULAR_A = <<modelMappingIndex($regularModel)]); + } + throw new Exception('The matching error'); + } + + /** + * modelMappingIndex + * + * @param $regularModel + * @return int|mixed + */ + protected function modelMappingIndex($regularModel) + { + return array ( + static::MODEL_REGULAR_A => 1, + static::MODEL_REGULAR_B => 0, + static::MODEL_REGULAR_C => 0, + static::MODEL_REGULAR_D => 1, + static::MODEL_REGULAR_E => 1, + static::MODEL_REGULAR_F => 1, + static::MODEL_REGULAR_G => 1, + static::MODEL_REGULAR_H => 1, + static::MODEL_REGULAR_I => 2 + )[$regularModel] ?? 1; + } + + /** + * chineseConversionNum + * + * @param $text + * @return mixed + */ + public function chineseConversionNum($text) + { + if ($this->regularModel(static::CHINESE_DIGITAL_MATCHING, $text)) { + $mapping = array ('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'); + return array_search($text, $mapping); + } + return ltrim($text, 0); + } + + /** + * getAllModelRegular + * + * @return array + * @throws \ReflectionException + */ + public function getAllModelRegular() + { + $constants = (new \ReflectionClass(__CLASS__))->getConstants(); + $collection = array (); + foreach ($constants as $key => $value) { + if (strpos($key, 'MODEL_REGULAR_') !== false) { + $collection[$key] = $value; + } + } + return $collection; + } + + /** + * modelAnalysis + * + * @param $text + * @return int|string + * @throws \ReflectionException + */ + public function modelAnalysis($text) + { + foreach ($this->getAllModelRegular() as $item) { + if ($this->regularModel($item, $text)) { + return $item; + } + } + throw new Exception('Model Analysis of the failure !'); + } + + /** + * textAnalysis + * + * @param $text + * @return int + */ + public function textAnalysis($text) + { + try { + return (int)$this->chineseConversionNum($this->extractModel( + $this->modelAnalysis($text), + $text + ) + ); + } catch (Exception $e) { + return 0; + } + } + + /** + * chineseTextList + * + * @param array $list + * @return array + */ + public function chineseTextListSorter(array $list) + { + $container = $generate = array (); + foreach ($list as $item) { + $container[] = $this->textAnalysis($item); + } + if (count($container) !== count($list)) { + return $list; + } + uksort($list, function ($left, $right) use ($container) { + if ($left == $right) { + return 0; + } + return $container[$left] < $container[$right] ? -1 : 1; + }); + return array_values($list); + } } \ No newline at end of file diff --git a/tests/Sort/ChineseTextNumberExtractTest.php b/tests/Sort/ChineseTextNumberExtractTest.php new file mode 100644 index 0000000..61824e7 --- /dev/null +++ b/tests/Sort/ChineseTextNumberExtractTest.php @@ -0,0 +1,336 @@ + + * @date 2019-05-23 + * @version 1.0 + */ +class ChineseTextNumberExtractTest extends PHPUnit\Framework\TestCase +{ + /** + * @var + */ + protected $chineseObj; + + /** + * ChineseTextNumberSortTest constructor. + * + * @param string|null $name + * @param array $data + * @param string $dataName + */ + public function __construct( + ?string $name = null, + array $data = [], + string $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->chineseObj = new ChineseTextNumberSort(); + } + + /** + * testValidationModelA + * + * @test + * @throws \Exception + */ + public function testValidationModelA() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第二章 我是Marco小哥哥' + ), + '二' + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第一节 我是Marco小哥哥' + ), + '一' + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第二单元 我是Marco小哥哥' + ), + '二' + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第一章 我是Marco小哥哥' + ), + '1' + ); + } + + /** + * testValidationModelB + * + * @throws \Exception + * @test + */ + public function testValidationModelB() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '01我是Marco小哥哥' + ), + '01' + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '12我是Marco小哥哥' + ), + '12' + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '10章我是Marco小哥哥' + ), + '1' + ); + } + + /** + * testValidationModelC + * + * @throws \Exception + * @test + */ + public function testValidationModelC() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '1 我是Marco小哥哥' + ), + 1 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '22 我是Marco小哥哥' + ), + 22 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '22 我是Marco小哥哥' + ), + 21 + ); + } + + /** + * testValidationModelD + * + * @throws \Exception + * @test + */ + public function testValidationModelD() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '1页-我是Marco小哥哥' + ), + 1 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '22页-+我是Marco小哥哥' + ), + 22 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '2页-+我是Marco小哥哥' + ), + 22 + ); + } + + /** + * testValidationModelE + * + * @throws \Exception + * @test + */ + public function testValidationModelE() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '1-' + ), + 1 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '2-+我是Marco小哥哥' + ), + 2 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '23-我是Marco小哥哥' + ), + 24 + ); + } + + /** + * testValidationModelF + * + * @throws \Exception + * @test + */ + public function testValidationModelF() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '1 但是' + ), + 1 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '1 2对对对' + ), + 1 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '22 我是Marco小哥哥' + ), + 2 + ); + } + + /** + * testValidationModelG + * + * @throws \Exception + * @test + */ + public function testValidationModelG() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '1、、' + ), + 1 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '01、2对对对' + ), + 01 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '23、我是Marco小哥哥' + ), + 24 + ); + } + + /** + * testValidationModelH + * + * @throws \Exception + * @test + */ + public function testValidationModelH() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '我爱Marco老师小册10 :' + ), + 10 + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '我爱Marco老师小册1 : 阳光鱼' + ), + 1 + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '我爱Marco老师小册1 : 阳光鱼' + ), + 122 + ); + } + + /** + * testValidationModelI + * + * @throws \Exception + */ + public function testValidationModelI() + { + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '识字一 01 十' + ), + '01' + ); + + $this->assertEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '狮子 03卧槽' + ), + '03' + ); + + $this->assertNotEquals( + $this->chineseObj->extractModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '狮子 03卧槽' + ), + '04' + ); + } +} \ No newline at end of file diff --git a/tests/Sort/ChineseTextNumberSortModelTest.php b/tests/Sort/ChineseTextNumberSortModelTest.php new file mode 100644 index 0000000..edb610a --- /dev/null +++ b/tests/Sort/ChineseTextNumberSortModelTest.php @@ -0,0 +1,301 @@ + + * @date 2019-05-23 + * @version 1.0 + */ +class ChineseTextNumberSortModelTest extends PHPUnit\Framework\TestCase +{ + /** + * @var + */ + protected $chineseObj; + + /** + * ChineseTextNumberSortTest constructor. + * + * @param string|null $name + * @param array $data + * @param string $dataName + */ + public function __construct( + ?string $name = null, + array $data = [], + string $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->chineseObj = new ChineseTextNumberSort(); + } + + /** + * testValidationModelA + * + * @test + */ + public function testValidationModelA() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第二章 我是Marco小哥哥' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第一节 我是Marco小哥哥' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第二单元 我是Marco小哥哥' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_A, + '第一章我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelB + * + * @test + */ + public function testValidationModelB() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '01我是Marco小哥哥' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '12我是Marco小哥哥' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_B, + '第一章我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelC + * + * @test + */ + public function testValidationModelC() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '1 我是Marco小哥哥' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '22 我是Marco小哥哥' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_C, + '22我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelD + * + * @test + */ + public function testValidationModelD() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '1页-我是Marco小哥哥' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '1页-+我是Marco小哥哥' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_D, + '22我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelD + * + * @test + */ + public function testValidationModelE() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '1-' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '1-+我是Marco小哥哥' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_E, + '22我是Marco小哥哥' + ) + ); + } + + + /** + * MODEL_REGULAR_F + * + * @test + */ + public function testValidationModelF() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '1 但是' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '1 2对对对' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_F, + '22我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelG + * + * @test + */ + public function testValidationModelG() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '1、、' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '01、2对对对' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_G, + '22我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelG + * + * @test + */ + public function testValidationModelH() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '我爱Marco老师小册10 :' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '我爱Marco老师小册1 : 阳光鱼' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_H, + '22我是Marco小哥哥' + ) + ); + } + + /** + * testValidationModelG + * + * @test + */ + public function testValidationModelI() + { + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '识字一 01 十' + ) + ); + + $this->assertTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '狮子 03卧槽' + ) + ); + + $this->assertNotTrue( + $this->chineseObj->regularModel( + ChineseTextNumberSort::MODEL_REGULAR_I, + '22我是Marco小哥哥' + ) + ); + } +} \ No newline at end of file diff --git a/tests/Sort/ChineseTextNumberSortTest.php b/tests/Sort/ChineseTextNumberSortTest.php index 39b8bc7..7a50ef7 100644 --- a/tests/Sort/ChineseTextNumberSortTest.php +++ b/tests/Sort/ChineseTextNumberSortTest.php @@ -1,28 +1,246 @@ chineseObj = new ChineseTextNumberSort(); + } + + /** + * testChineseTextListSorter + */ + public function testChineseTextListSorter() + { + $this->assertArraySubset( + $this->chineseObj->chineseTextListSorter( + array ( + '第五章 我是Marco小哥哥', + '第一章 我是Marco小哥哥', + '第三章 我是Marco小哥哥', + '第三章 我是Marco小哥哥', + '第二章 我是Marco小哥哥', + )), + array ( + '第一章 我是Marco小哥哥', + '第二章 我是Marco小哥哥', + '第三章 我是Marco小哥哥', + '第三章 我是Marco小哥哥', + '第五章 我是Marco小哥哥', + ) + ); + + $this->assertArraySubset( + $this->chineseObj->chineseTextListSorter( + array ( + '05我是Marco小哥哥', + '03我是Marco小哥哥', + '02我是Marco小哥哥', + '04我是Marco小哥哥', + '01我是Marco小哥哥', + )), + array ( + '01我是Marco小哥哥', + '02我是Marco小哥哥', + '03我是Marco小哥哥', + '04我是Marco小哥哥', + '05我是Marco小哥哥', + ) + ); + + $this->assertArraySubset( + $this->chineseObj->chineseTextListSorter( + array ( + '6页-我是Marco小哥哥', + '2页-我是Marco小哥哥', + '3页-我是Marco小哥哥', + '4页-我是Marco小哥哥', + '5页-我是Marco小哥哥', + '1页-我是Marco小哥哥', + )), + array ( + '1页-我是Marco小哥哥', + '2页-我是Marco小哥哥', + '3页-我是Marco小哥哥', + '4页-我是Marco小哥哥', + '5页-我是Marco小哥哥', + '6页-我是Marco小哥哥', + ) + ); + + $this->assertArraySubset( + $this->chineseObj->chineseTextListSorter( + array ( + '我爱Marco老师小册6 :', + '我爱Marco老师小册2 :', + '我爱Marco老师小册3 :', + '我爱Marco老师小册4 :', + '我爱Marco老师小册5 :', + '我爱Marco老师小册1 :', + '我爱Marco老师小册7 :', + )), + array ( + '我爱Marco老师小册1 :', + '我爱Marco老师小册2 :', + '我爱Marco老师小册3 :', + '我爱Marco老师小册4 :', + '我爱Marco老师小册5 :', + '我爱Marco老师小册6 :', + '我爱Marco老师小册7 :', + ) + ); + + $this->assertArraySubset( + $this->chineseObj->chineseTextListSorter( + array ( + '6、2对对对', + '2、2对对对', + '4、2对对对', + '3、2对对对', + '5、2对对对', + '1、2对对对', + )), + array ( + '1、2对对对', + '2、2对对对', + '3、2对对对', + '4、2对对对', + '5、2对对对', + '6、2对对对', + ) + ); + } + + /** + * testTextAnalysis + */ + public function testTextAnalysis() + { + $this->assertEquals( + $this->chineseObj->textAnalysis('第二章 我是Marco小哥哥'), + 2 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('01我是Marco小哥哥'), + 1 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('1 我是Marco小哥哥'), + 1 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('1页-我是Marco小哥哥'), + 1 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('2-+我是Marco小哥哥'), + 2 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('1 2对对对'), + 1 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('1、2对对对'), + 1 + ); + $this->assertEquals( + $this->chineseObj->textAnalysis('我爱Marco老师小册10 :'), + 10 + ); + $this->assertNotEquals( + $this->chineseObj->textAnalysis('我爱Marco老师小册10 :'), + 12 + ); + } + + + /** + * testModelAnalysis + * + * @throws \ReflectionException + */ + public function testModelAnalysis() + { + $this->assertEquals( + $this->chineseObj->modelAnalysis('第二章 我是Marco小哥哥'), + ChineseTextNumberSort::MODEL_REGULAR_A + ); + $this->assertEquals( + $this->chineseObj->modelAnalysis('01我是Marco小哥哥'), + ChineseTextNumberSort::MODEL_REGULAR_B + ); + + $this->assertEquals( + $this->chineseObj->modelAnalysis('1 我是Marco小哥哥'), + ChineseTextNumberSort::MODEL_REGULAR_F + ); + + $this->assertEquals( + $this->chineseObj->modelAnalysis('1页-我是Marco小哥哥'), + ChineseTextNumberSort::MODEL_REGULAR_D + ); + $this->assertEquals( + $this->chineseObj->modelAnalysis('2-+我是Marco小哥哥'), + ChineseTextNumberSort::MODEL_REGULAR_E + ); + $this->assertEquals( + $this->chineseObj->modelAnalysis('1 2对对对'), + ChineseTextNumberSort::MODEL_REGULAR_F + ); + $this->assertEquals( + $this->chineseObj->modelAnalysis('1、2对对对'), + ChineseTextNumberSort::MODEL_REGULAR_G + ); + $this->assertEquals( + $this->chineseObj->modelAnalysis('我爱Marco老师小册10 :'), + ChineseTextNumberSort::MODEL_REGULAR_H + ); + $this->assertNotEquals( + $this->chineseObj->modelAnalysis('我爱Marco老师小册10 :'), + ChineseTextNumberSort::MODEL_REGULAR_G + ); + } + + /** + * description + * + * @test + */ /** * description * + * @throws \ReflectionException * @test */ public function testAnalysisText() { - $chineseObj = new ChineseTextNumberSort(); - $this->assertTrue($chineseObj->isCompletelyChinese('我艹'), 'Is not entirely Chinese'); - $this->assertEquals($chineseObj->parsingText('第一十二章四十五'), 12); - $this->assertEquals($chineseObj->parsingText('十三'), 13); - $this->assertEquals($chineseObj->parsingText('二十三'), 23); - $this->assertEquals($chineseObj->parsingText('一十三'), 13); + var_dump($this->chineseObj->getAllModelRegular()); + die; } + } From 02147892a96489090ae0efb6ad9bc3fea4ea92d6 Mon Sep 17 00:00:00 2001 From: Shaowei Pu <18391791+m9rco@users.noreply.github.com> Date: Thu, 23 May 2019 19:28:18 +0800 Subject: [PATCH 121/127] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 38 +++++++++++++++++++++++ .github/ISSUE_TEMPLATE/custom.md | 10 ++++++ .github/ISSUE_TEMPLATE/feature_request.md | 20 ++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/custom.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..dd84ea7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/custom.md b/.github/ISSUE_TEMPLATE/custom.md new file mode 100644 index 0000000..48d5f81 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/custom.md @@ -0,0 +1,10 @@ +--- +name: Custom issue template +about: Describe this issue template's purpose here. +title: '' +labels: '' +assignees: '' + +--- + + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..bbcbbe7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. From 9ceb4d9f1e846f33c2728a3833c7fd97ce8154c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E5=9F=8E?= Date: Fri, 11 Oct 2019 15:03:39 +0800 Subject: [PATCH 122/127] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E9=A3=8E=E8=BD=A6?= =?UTF-8?q?=E6=97=8B=E8=BD=AC=E6=8E=92=E5=BA=8F=E7=AE=97=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README-EN.md | 1 + README.md | 1 + src/Other/RotateSort.php | 166 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+) create mode 100644 src/Other/RotateSort.php diff --git a/README-EN.md b/README-EN.md index c1998e4..8aeeaef 100644 --- a/README-EN.md +++ b/README-EN.md @@ -70,6 +70,7 @@ │ └── Judge.php │ └── Factorial.php | └── HashTable.php +| └── RotateSort.php │ ├──LICENSE └──README.md diff --git a/README.md b/README.md index e77d2c0..a125b2a 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ │ └── Judge.php 面试题之扑克牌中任选五张判断是不是顺子 │ └── Factorial.php 面试题之N的阶乘末尾有多少个0 | └── HashTable.php HashTable +| └── RotateSort.php 面试题之风车旋转排序算法 │ ├──LICENSE └──README.md diff --git a/src/Other/RotateSort.php b/src/Other/RotateSort.php new file mode 100644 index 0000000..2fefd3c --- /dev/null +++ b/src/Other/RotateSort.php @@ -0,0 +1,166 @@ + | + * | Date: 2019/10/11 | + * | Time: 下午2:56 | + * ---------------------------------------- + * | _____ ______ _ _ | + * | | __ \| ____(_) | | | + * | | |__) | |__ _ _ __ __ _| | | + * | | ___/| __| | | '_ \ / _` | | | + * | | | | | | | | | | (_| | | | + * | |_| |_| |_|_| |_|\__,_|_| | + * ---------------------------------------- + * 说明: 面试遇到一个写一个函数 让输出效果 如风车一样旋转 如下 + * foo(4) 逆时针 + * 16,15,14,13 + * 5, 4, 3, 12 + * 6, 1, 2, 11 + * 7, 8, 9, 10 + * foo(4) 顺顺时针 + * 7, 8, 9, 10 + * 6, 1, 2, 11 + * 5, 4, 3, 12 + * 16,15, 14,13 + * + */ + + $num = 4; + $arr = foo($num); + for ($i = 0; $i < $num; $i++) { + echo implode(',', $arr[$i])."
"; + } + + /** + * @param $num + * @param int $direction 方向 1 为 顺时针旋转 2 为逆时针旋转 + * @return mixed + */ + function foo($num, $direction = 1) + { + //填充map + $data = new stdClass(); + $data->x = 1; + if ($direction == 1) { + $data->y = $num; + } elseif ($direction == 2) { + $data->y = 1; + } + $data->num = $num; + $data->len = $num * $num; + $data->tmp_data = []; + $data->rate = 1;//方向 + $data->struct = create_struct($num); + for ($i = $data->len; $i >= 1; $i--) { + $data->i = $i; + $key = change_key($data, $direction); + $data->tmp_data[$key] = $i; + unset($data->struct[$key]); + } + + //根据y坐标分组 + $data->struct = create_struct($num); + foreach ($data->tmp_data as $key => $value) { + $data->struct[$key] = $value; + } + for ($i = 1; $i <= $data->num; $i++) { + $start = ($i - 1) * $data->num; + $end = $data->num; + $slice = array_slice($data->struct, $start, $end); + $data->slice[] = $slice; + } + + return $data->slice; + } + + function create_struct($num) + { + $struct = []; + for ($i = 1; $i <= $num; $i++) { + //嵌套 + for ($m = 1; $m <= $num; $m++) { + $key = $m.','.$i; + $struct[$key] = ''; + } + } + + return $struct; + } + + function change_key($data, $direction) + { + $key = $data->x.','.$data->y; + if (isset($data->struct[$key])) { + return $key; + } + switch ($data->rate) { + // LEFT 方向 + case 1: + $data->tmp_x = $data->x + 1; + $key = $data->tmp_x.','.$data->y; + if (isset($data->struct[$key])) { + $data->x = $data->tmp_x; + + return $key; + } else { + if ($direction = 1) { + $data->rate = 4; + } elseif ($direction = 2) { + $data->rate = 2; + } + } + break; + // DOWN 方向 + case 2: + $data->tmp_y = $data->y + 1; + $key = $data->x.','.$data->tmp_y; + if (isset($data->struct[$key])) { + $data->y = $data->tmp_y; + + return $key; + } else { + if ($direction = 1) { + $data->rate = 1; + } elseif ($direction = 2) { + $data->rate = 3; + } + } + break; + // RIGHT 方向 + case 3: + $data->tmp_x = $data->x - 1; + $key = $data->tmp_x.','.$data->y; + if (isset($data->struct[$key])) { + $data->x = $data->tmp_x; + + return $key; + } else { + if ($direction = 1) { + $data->rate = 2; + } elseif ($direction = 2) { + $data->rate = 4; + } + } + break; + // UP 方向 + case 4: + $data->tmp_y = $data->y - 1; + $key = $data->x.','.$data->tmp_y; + if (isset($data->struct[$key])) { + $data->y = $data->tmp_y; + + return $key; + } else { + if ($direction = 1) { + $data->rate = 3; + } elseif ($direction = 2) { + $data->rate = 1; + } + } + break; + } + + return change_key($data, $direction); + } \ No newline at end of file From 820aceef80de9de324e86098066bbae17702f454 Mon Sep 17 00:00:00 2001 From: Shaowei Pu <18391791+m9rco@users.noreply.github.com> Date: Wed, 27 May 2020 09:43:04 +0800 Subject: [PATCH 123/127] Update ChineseTextNumberExtractTest.php --- tests/Sort/ChineseTextNumberExtractTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Sort/ChineseTextNumberExtractTest.php b/tests/Sort/ChineseTextNumberExtractTest.php index 61824e7..3c42222 100644 --- a/tests/Sort/ChineseTextNumberExtractTest.php +++ b/tests/Sort/ChineseTextNumberExtractTest.php @@ -3,7 +3,7 @@ /** * ChineseTextNumberSortModelTest * - * @author Pu ShaoWei + * @author Pu ShaoWei * @date 2019-05-23 * @version 1.0 */ @@ -333,4 +333,4 @@ public function testValidationModelI() '04' ); } -} \ No newline at end of file +} From d3c29dff2540148ff2903aa67535f9c07496b79e Mon Sep 17 00:00:00 2001 From: Shaowei Pu <18391791+m9rco@users.noreply.github.com> Date: Wed, 27 May 2020 09:43:22 +0800 Subject: [PATCH 124/127] Update ChineseTextNumberSortModelTest.php --- tests/Sort/ChineseTextNumberSortModelTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/Sort/ChineseTextNumberSortModelTest.php b/tests/Sort/ChineseTextNumberSortModelTest.php index edb610a..6b18e90 100644 --- a/tests/Sort/ChineseTextNumberSortModelTest.php +++ b/tests/Sort/ChineseTextNumberSortModelTest.php @@ -3,7 +3,7 @@ /** * ChineseTextNumberSortModelTest * - * @author Pu ShaoWei + * @author Pu ShaoWei * @date 2019-05-23 * @version 1.0 */ @@ -298,4 +298,4 @@ public function testValidationModelI() ) ); } -} \ No newline at end of file +} From ae1be2cb3ae15a3f1c9afa64062abe574568a983 Mon Sep 17 00:00:00 2001 From: Shaowei Pu <18391791+m9rco@users.noreply.github.com> Date: Tue, 3 Aug 2021 10:35:58 +0800 Subject: [PATCH 125/127] Create SECURITY.md --- SECURITY.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..034e848 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 5.1.x | :white_check_mark: | +| 5.0.x | :x: | +| 4.0.x | :white_check_mark: | +| < 4.0 | :x: | + +## Reporting a Vulnerability + +Use this section to tell people how to report a vulnerability. + +Tell them where to go, how often they can expect to get an update on a +reported vulnerability, what to expect if the vulnerability is accepted or +declined, etc. From 7c3e51c2209f1665c1d194cc2ef6cd1717736bfd Mon Sep 17 00:00:00 2001 From: Ziding Zhang Date: Tue, 3 Aug 2021 14:48:04 +0100 Subject: [PATCH 126/127] Update SECURITY.md A simple instruction for security researchers. --- SECURITY.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 034e848..ac1360d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,8 +14,4 @@ currently being supported with security updates. ## Reporting a Vulnerability -Use this section to tell people how to report a vulnerability. - -Tell them where to go, how often they can expect to get an update on a -reported vulnerability, what to expect if the vulnerability is accepted or -declined, etc. +Please report security issues to From 081a4758521876e78cee9545f1c91c6a348d502c Mon Sep 17 00:00:00 2001 From: Arvin Date: Wed, 6 Dec 2023 22:31:36 +0330 Subject: [PATCH 127/127] Add: NQueen NQueen problem solved using backtracking --- src/Other/NQueen.php | 89 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/Other/NQueen.php diff --git a/src/Other/NQueen.php b/src/Other/NQueen.php new file mode 100644 index 0000000..5b16798 --- /dev/null +++ b/src/Other/NQueen.php @@ -0,0 +1,89 @@ + + * @date 2023/12/06 + * @license MIT + */ +/* +|-------------------------------------------------------------------------- +| NQueen Algorithm +|-------------------------------------------------------------------------- +| +| Arrange N queens on an NxN chessboard without attacking each other diagonally, +| horizontally, or vertically—a classic problem in combinatorial optimization and +| recursion. +| +*/ + +class NQueen +{ + + //Variable to store the dimensions of the chessboard + protected int $n; + + //Chessboard represented as an array + protected array $board; + + //Constructor to initialize the chessboard dimensions and fill it with zeros + public function __construct(int $n) + { + $this->n = $n; + $this->board = array_fill(0, $this->n, array_fill(0, $this->n, 0)); + } + + public function solve_n_queen($col = 0): void + { + if ($col >= $this->n) { + $this->print_result(); + } + + //Iterating through each row in the current column + for ($row = 0; $row < $this->n; $row++) { + if ($this->move_is_promising($row, $col)) { + //Placing the queen at the current position + $this->board[$row][$col] = 1; + //Recursively solving for the next column + $this->solve_n_queen($col + 1); + //Backtracking by removing the queen from the current position + $this->board[$row][$col] = 0; + } + } + } + + public function move_is_promising($row, $col): bool + { + //Checking if there is no queen in the same row + for ($index = 0; $index < $col; $index++) + if ($this->board[$row][$index]) + return false; + + //Checking if there is no queen on the upper-left diagonal + for ($i = $row, $j = $col; $i >= 0 && $j >= 0; $i--, $j--) + if ($this->board[$i][$j]) + return false; + + //Checking if there is no queen on the lower-left diagonal + for ($i = $row, $j = $col; $i < $this->n && $j >= 0; $i++, $j--) + if ($this->board[$i][$j]) + return false; + + //If no conflicts are found, the move is promising + return true; + } + + public function print_result(): void + { + for ($i = 0; $i < $this->n; $i++) { + for ($j = 0; $j < $this->n; $j++) + echo $this->board[$i][$j]; + echo "\n"; + } + echo "\n"; + } +} + +$dimensions = 4; +(new NQueen($dimensions))->solve_n_queen();