[plt-scheme] Combining digits to form numbers

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Tue Feb 17 11:38:17 EST 2009

On Feb 16, 2009, at 2:59 PM, aditya shukla wrote:

> I am trying to solve this exercise from htdp ...

Yes, I like that exercise, and I've given it to my students on a  
number of occasions.  Which is one reason for not giving you a  
solution to it on an e-mail list :-)

However, I can suggest a general technique that helps here as well as  
in many other problems.  Assuming you've already seen "templates" or  
"inventories", a step of program design in which you write down what  
you have available (mostly parameters to the current function) and  
their types, I call this technique "Inventories with Values".

Suppose you've already got
; convert-3-digits : number (lsb) number (csb) number (msb) -> number
(check-expect (convert-3-digits 0 0 0) 0)
(check-expect (convert-3-digits 1 2 3) 321)
(check-expect (convert-3-digits 5 1 0) 15)
(check-expect (convert-3-digits 2 9 7) 792)
(define (convert-3-digits lsb csb msb)
    ; lsb            a number, 0-9
    ; csb           a number, 0-9
    ; msb          a number, 0-9
    ...
    )

Pick a moderately-complicated one of your examples; let's try the  
last one, 792.  For each item in your inventory, write down not only  
its type but its VALUE FOR THIS EXAMPLE.  Also add a line to the  
inventory labelled "Right Answer", with ITS value for this example.

; convert-3-digits : number (lsb) number (csb) number (msb) -> number
(check-expect (convert-3-digits 0 0 0) 0)
(check-expect (convert-3-digits 1 2 3) 321)
(check-expect (convert-3-digits 5 1 0) 15)
(check-expect (convert-3-digits 2 9 7) 792)
(define (convert-3-digits lsb csb msb)
    ; lsb            a number, 0-9          2
    ; csb           a number, 0-9          9
    ; msb          a number, 0-9          7
    ; right answer   a number      792
    ...
    )

Now the challenge is to use your human pattern-recognition abilities  
to figure out how to get to the "right answer" from the available  
expressions.  Since everything in sight is a number, the most likely  
operations are arithmetic: +, -, *, /.  What arithmetic expression  
involving 2, 9, and 7 would give you 792?  (You might want to try an  
example with msb=0 first.)

Stephen Bloch
sbloch at adelphi.edu



Posted on the users mailing list.