Question

I have a project about the game "Oware", we are supposed to write the game in the program Dr.Racket. These are the rules for the game, they explain it pretty well, illustrating with pictures: http://www.awale.info/jugar-a-lawale/les-regles-de-lawale/?lang=en Im kinda stuck on the first exercise, i have the method, but its not giving the numbers in the right order.

The first function we have to write is called "distribute" which should re-put x grains in the holes, giving the result in a form of a list consisting of the number of grains rest and the new numbers for the holes.

This is whats expected:

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

What I wrote:

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

What it gives:

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

I was trying to change the list cons append, but never got the expected form of answer

Was it helpful?

Solution

How about

(define (distribue n l)
  (define (iterator n p q)
    (if (or (= n 0) (null? q))
        (list n (append p q))
        (iterator (- n 1) (append p (list (+ 1 (car q)))) (cdr q))))
  (iterator n '() l))

where

(distribue 5 '(2 3 1 5 5 2))
(distribue 5 '(2 3 1))

returns

'(0 (3 4 2 6 6 2))
'(2 (3 4 2))

as required.

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