A sequencing problem

firebus's picture

I had to implement a function the other day to abbreviate a set of days of the week, taking every sequence of adjacent days and replacing them with a hyphenated range. Comma-separating non-adjacent items.

So, {Mon, Tue, Wed, Fri} would become "Mon - Wed, Fri"

I came up with a really ugly, mishmashy recursive solution for it.

Bigokro suggested a non-recursive, linear-time algorithm which is not terrible.

But I still feel like there's something more elegant out there.

Does anyone know if this kind of algorithm has a name and if there's a canonical solution?

Powered by Drupal - Design by Artinet - Amazon Affiliate