Question

I'm working on a project in Scheme language and I'm stuck on an error in my code. The problem is that when i run the code for (vide 4 '(2 3 1 5 5 2)) it gives me (2 (2 3 1 0 6 3)) instead of the correct answer (3 (2 3 1 0 6 3)) the problem is with the first part only.

Example of the fonction vide:

(vide 4 '(2 3 1 5 5 2)) ;-> (3 (2 3 1 0 6 3))
(vide 6 '(2 3 1 5 5 2)) ;-> (2 (2 3 1 5 5 0))
(vide 3 '(2 3 1 5 5 2)) ;-> (0 (2 3 0 6 5 2))


(define distribue
  (lambda (n l)
    (if (or (= n 0) (null? l))
        (list n l)
        (let ((r (distribue (- n 1) (cdr l))))
          (list (car r) (cons (+ 1 (car l))(cadr r)))))))

(distribue 5 '(2 3 1 5 5 2)) ;-> (0 (3 4 2 6 6 2))
(distribue 5 '(2 3 1)) ;-> (2 (3 4 2))

(define vide
  (lambda (n l)
    (if (null? l)
        (list n l)
      (let ((r (distribue (car l) (cdr l))))  
        (if (= n 1)
            (list  (car r)  (cons 0 (cadr r)))
            (list (+ (car l) (car r)) (cons (car l)(cadr (vide (- n 1) (cdr l))))))))))

(vide 4 '(2 3 1 5 5 2))
Was it helpful?

Solution

The issue is that in the last line, the term (+ (car l) (car r)) is entirely incorrect; (car l) is the first element of the input list, which might not affect the output at all; while r shouldn't even matter if n is not equal to 1. Instead, that term should be the left-overs from the recursive call to vide, i.e. (car (vide (- n 1) (cdr l))). Since you also use the cadr, I bound the recursive call in a let to avoid calling it twice. In addition, I put the binding of r to the result of distribue inside the (if (= n 1) ...) because it isn't used in the else clause now.

Here is the corrected implementation (distribue is left unchanged):

(define vide
  (lambda (n l)
    (if (null? l)
        (list n l)
        (if (= n 1)
            (let ((r (distribue (car l) (cdr l))))
              (list (car r) (cons 0 (cadr r))))
            (let ((v (vide (- n 1) (cdr l))))
              (list (car v) (cons (car l) (cadr v))))))))

As a side note to anyone else who comes by this question, I believe the rule implemented by vide here is akin to a single part of a move in the game Kalah, known as Mancala in the US.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top