Monthly Archive


Enter the Clones

Following my comments about PowerShell being designed for the Jedi -!43CFA46A74CF3E96!2066 – I discovered the Clones are now getting into the action -

Lee (of Cookbook fame) has a very nice script for working out the smallest number of coins needed to make perfect change ie meet the price without needing change back.

The script makes very clever use of the Clone() method of a hash table – a clone can be regarded as a copy of the object in this case – and then builds an array of hash tables to hold the results.  For each possible value of 1 – 99 a hash table is created showing which coins are required to created that number of cents, pence or whatever

I really recommend that you have a look at this technique.

If you want convert the script to use any other currency just change the hash table – for instance for UK currency it becomes

$coins = @{ 0.50 = 0; 0.20 = 0; 0.10 = 0; 0.05 = 0; 0.02 = 0; 0.01 = 0 }

The other clever bit is the way the results are presented to automatically include the correct currency symbol.   In case you are wondering the results for the UK are

£0.50: 1
£0.20: 2
£0.10: 1
£0.05: 1
£0.02: 2
£0.01: 1

We only need 8 coins to make any amount of change below £1


Technorati Tags: PowerShell

Leave a Reply