Pages

Wednesday, 18 January 2012

Code Kata #1

In yesterday's post I described Code Katas and how they can be a useful form of programming practice. Dave Watson (the "inventor" of Code Katas) offers 21 on his Code Kata blog. I intend to publish my own from time-to-time, and here is the first. Enjoy...

Imagine you have to write some code for a vending machine. You are given a) the price of the product to be vended, and b) the amount of money tendered by the customer. Your task is to deduce what change to offer, i.e. how many of each type of coin. Optimise your result by minimising the number of coins given in change. Assume your vending machine has unlimited stocks of the following denomination: 1p, 2p, 5p, 10p, 20p, 50p, £1, £2.

Two examples of input and output follow:

i) Product price is 70p; money tendered is £1, i.e. 100p. Optimal output is 1 x 10p and 1 x 20p

ii) Product price is 63p; money tendered is 80p. Optimal output is 1 x 10p, 1 x 5p, 1 x 2p

This challenge is entirely language-independent, so your solution can be produced in the manner that best suits your regular coding activities. Hence, you might write your solution using DATA Steps and/or you might use macros. Your input values might be provided as global macro variables, or parameters to your macro(s), or supplied within a data set.

Once you've cracked the above, you might want to consider the following additions - perhaps on subsequent days.

A) Accept a "list" of coin denominations as additional input rather than hard-coding the list I supplied above. The list might be as a parameter to your macro, or in a data set

B) Rather than assume an unlimited stock of each coin in the machine, accept an input "list" that tells you how many coins of each denomination are in the machine. Consequently, you will need to consider the possibility that your result is a refusal to vend due to "insufficient change"

C) Rather than writing a simple textual result to the SAS log, produce some kind of coloured report or graph depicting the change given

You also might like to consider different solutions. The use of arrays or hash tables would be two alternatives.