Friday 9 January 2015

Another quick code puzzle (any language)

Yeah, I'm a bit cheeky suggesting another puzzle when I've not yet found time to review all the answers for the last one (Something for the weekend? A wee code puzzle (in CFML, PHP, anything really...)), from back in November! Oh well. I'm sure it's the fun of the exercise rather than me reporting back on it that's the key bit anyone.

TBH I had forgotten about the other one, but will review another of the answers this weekend. I'll make a point of it.

Anyway... what's this one all about..?

OK, so we have an unordered data structure like this:

set = {
    one : {
        alphabet : "a",
        maori : "tahi",
        roman : "i",
        ordinal : "first"
    two : {
        alphabet : "b",
        maori : "rua",
        roman : "ii",
        ordinal : "second"
    three : {
        alphabet : "c",
        maori : "toru",
        roman : "iii",
        ordinal : "third"
    four : {
        alphabet : "d",
        maori : "wha",
        roman : "iv",
        ordinal : "fourth"

I want to call a function, getOrderedSubset() like this:

subset = ["four", "two"];
orderedSubset = getOrderedSubset(set, subset);

(or it could be a method of an object, but that general sort of thing).

And I want the result to be like this:


(not as JSON per se, but as an array of elements)

Things to note:
  1. the ordering is based on the subset elements, not the original set;
  2. a label key/value has been added to each element of the returned array.

The guidelines are the same as before:
  1. I'm after a function/method (not an entire application, Adam Presley ;-).
  2. Do it in any language you like. The more variation the merrier.
  3. Demonstrating you used TDD, and tested your edge cases earns brownie points.
  4. Submit your answers via a comment with a link to a Gist (etc). Do not post code in the comment.
  5. I'm after concise (whilst still being "clean code") answers. But elegant ones.
This actually came from a real-world requirement we had in PHP. I've got a solution, but it seems ham-fisted. I suspect this is just because it's PHP and it has limitations, but I'd like to see other people's approaches.

Oh, and hey if you could help me get the attention of people outside my limited readership / Twitter following (most of whom are just CFML devs, and I'm interested in non-CFML answers too), that'd really help. Could you pls consider retweeting this: