Just a simple javascript code to test from windows command line (cscript test.js
).
This is nothing more than a sum with carry where the "digits" are the position of the element in the set.
No recursion and only needs to store the set elements and the array to hold the current subset.
// define the initial set
var set = 'abcdefg'.split('');
var setLength = set.length;
// define the subset length and initialize the first subset
var subsetLength = 5;
var aSubset = new Array(subsetLength+1);
var i;
for( i = 0 ; i < subsetLength ; i++ ) aSubset[i]=i;
// place a guard at the end
aSubset[subsetLength] = setLength;
// generate each of the posible subsets
// This is just a sum with carry where the value of each of the "digits"
// is in the range [i..subset[i+1])
var r = 0, start = 0;
do {
// print the subset
for( i = 0 ; i < subsetLength ; i++ ) {
WScript.StdOut.Write( set[aSubset[i]] );
};
WScript.StdOut.WriteLine('');
// calculate the next subset
for( i = start, r = 1 ; i < subsetLength ; i++ ) {
aSubset[i]++;
if (aSubset[i] < aSubset[i+1]) {
start = ( i==0 ? 0 : i-1 );
r = 0;
break;
} else {
aSubset[i] = i
};
};
} while (r == 0);