The Friday Fragment

Published on 6 March 2010
This post thumbnail

I've always been a sucker for a good (yet simple) puzzle: crosswords, Sodoku, the Car Talk Puzzler, PC-lint's Bug of the Month, you name it. And the same goes for programming and logic puzzles. I'm not talking about k-coloring, circuit satisfiability, or RSA factoring: I mean simple problems with simple solutions. In fact, the simpler the solution, the better. After all, I'm a sucker for elegance, too.

And elegance is sorely needed. I've stumbled across more than my share of clumsy, confusing code: functions and methods that go on for dozens of lines that were easily rewritten to just a few straightforward statements. You'd think the programmer was paid by the line of code. So to do my small part to remedy that, I've often given quick assignments to my eldest son and other suitable victims. Nothing fancy, just simple problems that can be summed up in a couple of sentences and that exercise standard techniques: loops, arrays, iterators, collections, streams, strings, recursion, induction, closures, etc. I did that just recently, and that gave me the idea to try it here. If for no other purpose than to provide fodder for other beginning programmers.

So, I'm introducing my for the Friday Fragment: a weekly programming, logic, or related problem. The problem won't be hard; rather, it'll usually be something quite common, and often a chance to try a "kernel" of a problem in multiple languages or with multiple techniques. And it'll truly be a fragment: the problem and solution will be at most just a few sentences (or lines of code). Each weekly post will include solution(s) for the previous week's fragment and a new problem. This'll go on until I find out that it's harder than it seems.

If you want to "play along", post a solution as a comment or send it via email. To avoid "spoilers", simply don't expand comments for the post. For programming problems, pick the language of your choice. That could add interest, since language wars can be great sport.

This Week's Fragment

Write code to create a string of "fill data" of a given length, containing the digits 1-9, then 0, repeating. For example, if given a length of 25, return "1234567890123456789012345". For a length of 1, return "1"; for a length less than 1, return an empty string.

The idea for this came from some recent code I wrote, as part of a "test mode" to generate dummy data, up to a maximum field length. This was so that XML output files could be fully validated against a rich schema (XSD), even if many of the source data fields were missing. I used all digits for numeric fields, and the modulus positions were helpful for demonstrating field lengths.

"See" you in a week, when we'll frag this one and add another.