-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartesianProduct.php
More file actions
53 lines (48 loc) · 1.14 KB
/
CartesianProduct.php
File metadata and controls
53 lines (48 loc) · 1.14 KB
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
<?php
/**
* php 计算多个集合的笛卡尔积
*
* @author fdipzone
* @DateTime 2023-03-20 19:36:40
*
*/
class CartesianProduct
{
/**
* 计算多个集合的笛卡尔积
*
* @author fdipzone
* @DateTime 2023-03-20 19:37:52
*
* @param array $sets 需要参与计算笛卡尔积的集合
* @return array
*/
public static function cal(array $sets):array
{
// 保存结果
$result = array();
// 循环遍历集合数据
for($i=0,$count=count($sets); $i<$count; $i++)
{
// 初始化,第一个集合,不用做笛卡尔积
if($i==0)
{
$result = $sets[$i];
continue;
}
// 保存临时数据
$tmp = array();
// 结果与当前集合计算笛卡尔积
foreach($result as $res)
{
foreach($sets[$i] as $set)
{
$tmp[] = $res.$set;
}
}
// 将笛卡尔积写入结果
$result = $tmp;
}
return $result;
}
}