The simple and obvious way to walk through a graph
At some point in your programming career you may have to go through a graph of items and process them all exactly once. If you keep following neighbours, the path might loop back on itself, so you need to keep track of which ones have been processed already.
function process_node( node ) { if ( node.processed ) { return; } node.processed = true; var i; for( i = 0; i < node.neighbours.length; i++ ) { process_node( node.neighbours[i] ); } // code to process the node goes here. It is executed only // once per node. }
The code works, but it only works once! The next time you try it, all the nodes will already be marked as processed, so nothing will happen.
Here's a neat trick that elegantly solves the problem. Instead of using a boolean flag in each node, use a generation count.
var CurrentGeneration = 0; function process_node( node ) { if ( node.generation == CurrentGeneration ) { return; } node.generation = CurrentGeneration; var i; for( i = 0; i < node.neighbours.length; i++ ) { process_node( node.neighbours[i] ); } // code to process the node goes here. It is executed only // once per node. } function process_all_nodes( root ) { CurrentGeneration += 1; process_node( root ); }
It's simple and obvious right? So why didn't I think of it in eight years?
function process_node( node, processed )
{
if ( node.id in processed ) {
return;
}
processed[node.id] = true;
// ...
}
function process_all_nodes( root )
{
process_node( root, {} );
}
This is useful if you might be sub-processing parts of the graph as part of the main processing : the processing function is now re-entrant!
My favourite Google Cardboard Apps
I have never been a gamer. The most I've played was Super Mario Bros (the original). I then took a break for a decade or two and spent a few weeks with Simcity 4. All that changed when I got Google Cardboard.Why don't web browsers do this?

When a reporter mangles your elevator pitch
If a reporter asks you about your new startup company, be careful what you say.Rules for Effective C++
The rules for safe C++ code are surprisingly controversial.20 lines of code that will beat A/B testing every time

What does your phone number spell?
Here, I explain a technique for figuring out which words are in which phone numbers. Full C source code is included.My thoughts on various programming languages

You don't need a project/solution to use the VC++ debugger
You learn a lot of things on the job as a programmer. Years ago, at my first coop position, I was a little confused when my boss went to Visual C++, and tried to open the .EXE file as a project. What a dolt! I thought. That's not going to work.