Why is a CPU branch instruction slow?

A branch instruction is not inherently slower than any other instruction. However, the reason you heard that branches should avoided is because modern CPUs follow a pipeline architecture. This means that there are multiple sequential instructions being executed simultaneously. But the pipeline can only be fully utilised if it’s able to read the next instruction … Read more

Are there any good / interesting analogs to regular expressions in 2d?

Not being a regex expert, but finding the problem interesting, I looked around and found this interesting blog entry. Especially the syntax used there for defining the 2D regex looks appealing. The paper linked there might tell you more than me. Update from comment: Here is the link to the primary author’s page where you … Read more

How to calculate distance from a point to a line segment, on a sphere?

Here’s my own solution, based on the idea in ask Dr. Math. I’d be happy to see your feedback. Disclaimer first. This solution is correct for spheres. Earth isn’t a sphere, and the coordinates system (WGS 84) doesn’t assume it’s a sphere. So this is just an approximation, and I can’t really estimate is error. … Read more

Code Golf: Beehive

Perl, 99 characters @P=map{$/.substr$”.’__/ \\’x99,$_,$W||=1+3*pop}0,(3,6)x pop; chop$P[0-$W%2];print” __”x($W/6),@P Last edit: Saved one character replacing -($W%2) with 0-$W%2 (thanks A. Rex) Explanation: For width W and height H, the output is 2+2 * H lines long and 3 * W+1 characters wide, with a lot of repetition in the middle of the output. For convenience, we … Read more

What data structures can efficiently store 2-d “grid” data?

Here are a few approaches. I’ll (try to) illustrate these examples with a representation of a 3×3 grid. The flat array +—+—+—+—+—+—+—+—+—+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +—+—+—+—+—+—+—+—+—+ a[row*width + column] To access elements on the left or right, subtract or … Read more