一定长度的幂集元素
给定 PHP 中的一个元素数组,我希望创建一个新的二维数组,仅包含幂集中特定长度的元素。例如,对于以下数组:
array(4) {
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D'
}
如果我要运行函数 fixed_length_power_set( $arr, 2 )
那么我希望它返回:
array(6) {
0 => array(2) {
0 => 'A',
1 => 'B'
}
1 => array(2) {
0 => 'A',
1 => 'C'
}
2 => array(2) {
0 => 'A',
1 => 'D'
}
3 => array(2) {
0 => 'B',
1 => 'C'
}
4 => array(2) {
0 => 'B',
1 => 'D'
}
5 => array(2) {
0 => 'C',
1 => 'D'
}
}
虽然我可以想到一些规则来概括该过程,由于某种原因,我似乎无法将其转换为代码。有人有建议吗?
Given an array of elements in PHP, I wish to create a new two-dimensional array containing only those elements of the power set that are a specific length. As an example, for the following array:
array(4) {
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D'
}
If I were to run the function fixed_length_power_set( $arr, 2 )
then I want it to return:
array(6) {
0 => array(2) {
0 => 'A',
1 => 'B'
}
1 => array(2) {
0 => 'A',
1 => 'C'
}
2 => array(2) {
0 => 'A',
1 => 'D'
}
3 => array(2) {
0 => 'B',
1 => 'C'
}
4 => array(2) {
0 => 'B',
1 => 'D'
}
5 => array(2) {
0 => 'C',
1 => 'D'
}
}
Although I can think of a few rules to generalize the process, for some reason I can not seem to turn it into code. Does anyone have suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用简单的递归算法:对于大小为
n
的集合中大小为k
的所有子集的集合,if
n == k
>,返回包含整个集合的集合;if
k == 1
返回所有单例的集合;否则从集合中删除元素
x
:现在您需要剩余集合的大小为k-1
的所有子集(即包含的子集) x
),以及剩余集合中大小为k
的所有子集(不包括x
的子集)。在 PHP 伪代码中:
这里
merge_into_each()
将x
添加到集合中的每个数组:Use a simple recursive algorithm: For the set of all subsets of size
k
from a set of sizen
,if
n == k
, return a set containing the entire set;if
k == 1
return the set of all singletons;otherwise remove an element
x
from the set: now you need all the subsets of sizek-1
of the remaining set (i.e. those subsets which includex
), as well as all the subsets of sizek
of the remaining set (those which don't includex
).In PHP pseudo-code:
Here
merge_into_each()
addsx
to each array in the collection:我不是 PHP 专家,所以我会用伪代码来回答。由于您似乎在询问数组和子序列(即使您使用英语单词“集合”和“子集”),我会这样做。我将使用符号
arr[m:n]
来表示构建一个长度为n - m + 1
的全新数组,该数组复制元素m , m+1, ..., n
来自arr
。I am not a PHP expert, so I will answer with pseudocode instead. Since you seem to be asking about arrays and subsequences (even though you use the English words "sets" and "subsets"), I'll do that. I'll use the notation
arr[m:n]
to mean the construction of a brand new array of lengthn - m + 1
that copies the elementsm, m+1, ..., n
fromarr
.