0

The following are some examples that you may see in an intro to programming course:

Print the elements of an nxn array...

  • Spiraling in from the outside
  • Spiraling out from the center
  • Zig zagging from the top left corner
  • Going right, then left, then right, then left(like a printer)
  • Etc.

These are fairly standard to whip up. However, the end result is typically ugly. It usually comes down to a bunch of nested for loops, with if statements sewn throughout, tailored to that specific transversal pattern. Heaven forbid you need to modify that, and account for a "width of the brush" or something.

Is there a cleaner pattern for this?

I've considered using some sort of automata, with directions as states. That seems plausible. However, I was wondering if there was something else, possibly more elegant/canonical, and less homebrew. We do talk about these examples all the time, after all!

Thoughts?

Kyle
  • 37
  • 1
  • 3
  • The reason you get all of these variations in a programming course is to exercise your analytical thinking and problem solving skills. In real-life, we seldom use even half of these variations. – Robert Harvey Dec 01 '20 at 16:17
  • I'm aware, I'm a professional developer. However, I happen to be in a situation where I needed to use one of them (Shells around the bottom left corner), and I couldn't help but wonder if we've come up with a general solution. That's something we typically do, especially with things we all have in common. – Kyle Dec 01 '20 at 16:55
  • You can use the iterator pattern to abstract away the traversal method, but besides that, I'm not sure there is a general but elegant way to represent all of these. What you can try to make the code nicer (and hopefully simpler and more maintainable) is to try and come up with a relatively easy to understand, but accurate high level description of the procedure, and then code it top-down - don't start with the loops and nitty-gritty details, but express the high-level descriptions as several high level method calls (creating the desired, more elegant API first), then implement those methods. – Filip Milovanović Dec 01 '20 at 17:42
  • You can apply the same top-down approach within those methods as well (basically, hierarchical divide-and-conquer, but for API design). It might take you several attempts before you come up with something you like. TDD could work nicely with this approach. The implementation is likely not going to be the most efficient possible, but it should be something reasonable; in many cases not having the most efficient implementation is not going to matter. – Filip Milovanović Dec 01 '20 at 17:42

0 Answers0