|Just another Perl shrine|
NestedLoops and the Odometer Modelby Roy Johnson (Monsignor)
|on Jan 10, 2006 at 20:56 UTC||Need Help??|
This falls somewhere between a meditation and a tutorial. It's about using the NestedLoops function from Algorithm::Loops, but it's also about a certain mental model I have found useful recently.
A normal set of nested loops is like the odometer on a car. The outermost loop is the leftmost digit, and the innermost loop is the rightmost digit. A normal odometer can only loop through the same set of digits on each dial, but in programming, each dial can have a completely different set of values.
Now imagine that each time one of the dials changes, all the dials to the right of it can be remade. For example, each dial could exclude any numbers that exist on any dial to its left. A whole set of dials like that would generate the permuations of a set of numbers. In any situation where you're generating a set of values, and you can build them member-by-member, you can probably use this odometer model. And NestedLoops makes it pretty easy. All you need to mess with is the first argument.
The first argument to NestedLoops is the set (arrayref) of dials it will iterate over. A dial can be either an arrayref or a coderef that, when executed, returns an arrayref. So you can generate dials dynamically. Furthermore, when the coderef is executed, @_ will contain the values that are currently on the dials to the left, so you can do the kind of filtering I talked about above. With a little bookkeeping, I was able to make an elegant derangement iterator the other day.
Today, find all paths of length n in a graph inspired yet another solution in the same vein. Simply keeping track of where you can go next, you can explore a graph. And for the OP in that thread, while you're filtering, you can check to see if the set of characters you're assembling is a prefix of any valid words, to save a whole lot of checking later.
So keep your eyes open for solutions like this. They are easy and efficient.
Caution: Contents may have been coded under pressure.