PHP 日常总结
PHP 日常总结,方便以后分类
- 一个PHP实现的ID生成器
1 | <?php |
- PHP实现排列组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68<?php
// 阶乘
function factorial($n) {
return array_product(range(1, $n));
}
// 排列数
function A($n, $m) {
return factorial($n) / factorial($n-$m);
}
// 组合数
function C($n, $m) {
return A($n, $m) / factorial($m);
}
// 排列
function arrangement($a, $m) {
$r = array();
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i = 0; $i < $n; $i++) {
$b = $a;
$t = array_splice($b, $i, 1);
if ($m == 1) {
$r[] = $t;
} else {
$c = arrangement($b, $m-1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
// 组合
function combination($a, $m) {
$r = array();
$n = count($a);
if ($m <= 0 || $m > $n) {
return $r;
}
for ($i = 0; $i < $n; $i++) {
$t = array($a[$i]);
if ($m == 1) {
$r[] = $t;
} else {
$b = array_slice($a, $i+1);
$c = combination($b, $m-1);
foreach ($c as $v) {
$r[] = array_merge($t, $v);
}
}
}
return $r;
}
// ====== 测试 ======
$a = array("A", "B", "C", "D");
$r = arrangement($a, 2);
print_r($r);
$r = A(4, 2);
echo $r."\n";
$r = combination($a, 2);
print_r($r);
echo $r."\n";
本文作者 : Xuebin Zhang
原文链接 : https://capping.github.io/2018/10/11/PHP-Common/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!