Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

NestedLoops and the Odometer Model

by Roy Johnson (Monsignor)
on Jan 10, 2006 at 20:56 UTC ( [id://522316]=perlmeditation: print w/replies, xml ) 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.

Replies are listed 'Best First'.
Re: NestedLoops and the Odometer Model
by wazoox (Prior) on Jan 10, 2006 at 22:55 UTC
    What you describe strongly resembles an Enigma machine, too :)

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://522316]
Approved by Corion
Front-paged by Old_Gray_Bear
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-20 06:18 GMT
Find Nodes?
    Voting Booth?

    No recent polls found