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
kfrom a set of sizen,if
n == k, return a set containing the entire set;if
k == 1return the set of all singletons;otherwise remove an element
xfrom the set: now you need all the subsets of sizek-1of the remaining set (i.e. those subsets which includex), as well as all the subsets of sizekof the remaining set (those which don’t includex).In PHP pseudo-code:
Here
merge_into_each()addsxto each array in the collection: