(a)
void getBitCombinations(CombinationHandler ch,
	BitSet bs, int start, int current, int target)
{
    if (current == target) {
		// success, so process the combination 
		// (clone 'bs' so that we're sure it's not modified)
		ch.process((BitSet) bs.clone());
		return;
    }
    if (start == a.length)
        return;					// failure

    bs.set(start);
    current++;
    getBitCombinations(ch, bs, start + 1, current, target);

    bs.clear(start);
    current--;
    getBitCombinations(ch, bs, start + 1, current, target);
}

(b)
import java.util.*;

/**
 *  An interface that defines a callback method for handling
 *  combinations.
 */
public interface CombinationHandler {

    /**
     *  The combination-handling method, called back by the
     *  general routine.
     */
    public void process(BitSet combination);

}

Example 3: (a) A version of the code that passes solutions to a callback function; (b) an interface for exposing callback functions that process solutions.

Back to Article