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?
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: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
.