scheme: Finding the sum of the two largest digits in an integer

126 views Asked by At

I've been stuck on this question for a while, any hints or suggestions would be helpful. I want to find the sum of the two largest digits in a number using Scheme and I want to do it recursively, for which I think I need a helper functions, but I don't know what will this helper function do. I was able to solve the same problem in a iterative way, but I want to do it in an recursive way. Any hints or suggestions would be helpful.

Here's my iterative solution to the same problem:

(define (largest-sum n)
  (define (largest-sum-iter num largest second_largest)

    (cond ((= num 0) (+ largest second_largest))
          ((>= (remainder num 10) largest) (largest-sum-iter (quotient num 10) (remainder num 10) largest))

          ((and (< (remainder num 10) largest) (>= (remainder num 10) second_largest)) (largest-sum-iter (quotient num 10) largest (remainder num 10)))

          (else (largest-sum-iter (quotient num 10) largest second_largest))))

  (largest-sum-iter n 0 0))
1

There are 1 answers

0
mnemenaut On

Or using "named let" (often a convenient alternative to a recursive helper function):

(define (positive-integer->digits n)
  (let next-digit ((n n) (digits (list)))
    (if (zero? n)  digits
        (next-digit (quotient n 10) (cons (remainder n 10) digits)))))
        
(define (sum-top2 digits)        
  (let top2 ((l digits) (t1 0) (t2 0))
    (cond
      ((null? l)      (+ t1 t2))
      ((> (car l) t1) (top2 (cdr l) (car l) t1))
      ((= (car l) t1) (top2 (cdr l) t1 (car l)))
      (else           (top2 (cdr l) t1 t2)))))

(define (largest-sum n)    
  (sum-top2 (positive-integer->digits n)))