THE PUZZLET PAGE

PUZZLET 030 - THE SOLUTION

' Puzzlet #030
' How many different ways can you make up one
' pound from 1p, 2p, 5p, 10p, 20p, 50p coins?
' Example: 1x50p + 3x10p + 6x2p + 8x1p = £1.
' You can change this to dollars and cents or
' Euros and cents etc if it feels better!
' By Dave Ellis.


declare GetSum()
' c50 is the variable for a 50p coin, etc.
def c50, c20, c10, c5, c2, c1: int
def flag, sum, count: int
openconsole
print
"Counting combinations ..."
count = 0
c50 = 0

do
    c20 = 0
    do
        c10 = 0
        do
            c5 = 0
            do
                c2 = 0
                do
                    c1 = 0
                    flag = 0
                    do
                        sum = GetSum()
                        if sum > 100
                            flag = 1
                        else
                            if
sum = 100
                                count = count + 1
                                locate 3, 1
                                print count,
                                print "combinations."
                            endif
                        endif

                        c1 = c1 + 1
                    until flag | c1 > 100
                    c2 = c2 + 1
                until c2 > 50               
                c5 = c5 + 1
            until c5 > 20
            c10 = c10 + 1
        until c10 > 10
        c20 = c20 + 1
    until c20 > 5
    c50 = c50 + 1
until c50 > 2

print: print "No more!"
print: print "Press a key to exit ...",
do: until inkey$ <> ""
closeconsole
end

sub
GetSum
' Totals the current combination of coins.
def tot: int
tot = c50*50 + c20*20 + c10*10 +c5*5 + c2*2 + c1
return tot


PROGRAM NOTES

The code looks complicated, but it's actually very simple.  This is a "brute force and ignorance" approach.  The do loops are nested in such a way as to generate every possible combination of  nominated coins that don't exceed one pound.  For every combination, a check is made to see if it equals one pound exactly.  If it does, variable count is updated.  At the end of the run, count is printed out.  

When you run the code,  it will produce the inset screen.  

Who would have thought there were so many different ways to add up those coins to make one pound!


Counting combinations ...

4562 combinations.

No more!

Press a key to exit ...

          


MAIN MENU
DOWNLOAD CODE
ARCHIVES

Site design/maintenance: Dave Ellis E-mail me!
Last Updated: February 22nd, 2004.