Sunday, October 27, 2013

Travel Itinerary Algorithm in Ruby

I've found a great new site for interesting and challenging programming exercises called TalentBuddy. Today I completed a fairly straight forward algorithm to reconstruct a travel itinerary from a pair of parallel arrays containing all the history departures and destinations. One of the neat things about TalentBuddy is that they expose your work to fairly large data sets (around 10,000 elements) and have a two second timeout, so implementations must be efficient.

My implementation begins by mapping the parallel arrays to a hash of destinations and departures. Then we calculate the first departure by getting the intersection of the two original arrays. Then a loop begins iterating through all destinations, retracing the history. This is made easy by the fact that no destination is visited twice. Finally, we have to handle the final case where the loop terminates when no additional destinations are found, printing the final destination. As always, full source is on GitHub

class PlaneTickets
  def get_journey(departure_ids, destination_ids)
    destination_for = map_departures_to_destinations(departure_ids, destination_ids)

    next_departure = (departure_ids - destination_ids).first

    while next_departure
      puts next_departure

      last_departure = next_departure
      next_departure = destination_for[next_departure]
    end

    puts destination_for[last_departure]
  end
end

Saturday, October 5, 2013

Product Pricing Kata in Ruby

Continuing along with Dave Thomas's kata series, I'd like to share my implementation of the Product Pricing kata where we're asked to implement a checkout system that accepts rules for different pricing strategies. This immediately reminded me of my FizzBuzz implementation. In the end it was actually a fairly straight forward implementation of the Strategy pattern. The more challenging part of the exercise was extracting the actual pricing rules from the supplied test suite; a user story is often easier to read than a test of very specific behavior.

In the end, I was pleased with the rule set I implemented. For the full solution, please visit GitHub.

def rules
    [
        QuantityDiscountRule.new(sku: "A", quantity: 3, price: 30),
        QuantityDiscountRule.new(sku: "B", quantity: 2, price: 15),
        RegularPriceRule.new({
                                 "A" => 50,
                                 "B" => 30,
                                 "C" => 20,
                                 "D" => 15
                             })
    ]
end