algorithm - partition of number without using consecutive integers -


i following cs61a spring 2015 class.

one of problem in scheme project is:

implement list-partitions procedure, lists of ways partition positive integer total without using consecutive integers. contents of each partition must listed in decreasing order. hint: define helper procedure construct partitions. built-in append procedure creates list containing elements of 2 argument lists. cons-all procedure in questions.scm adds first element each list in list of lists.

the number 5 has 4 partitions not contain consecutive integers:

5

4, 1

3, 1, 1

1, 1, 1, 1, 1

the following partitions of 5 not included because of consecutive integers:

3, 2

2, 2, 1

2, 1, 1, 1

i found 1 solution cannot understand it

;; list ways partition total without using consecutive numbers. (define (apply-to-all proc items)   (if (null? items)       '()        (cons (proc (car items))             (apply-to-all proc (cdr items)))))  (define (cons-all first rests)   (apply-to-all (lambda (rest) (cons first rest)) rests))  (define (caar x) (car (car x))) (define (cadr x) (car (cdr x))) (define (cddr x) (cdr (cdr x))) (define (cadar x) (car (cdr (car x)))) (define (cdar x) (cdr (car x)))  (define (partitions-r b)   (if (= 0) nil     (append (cons-all (list-partitions b))             (cons-f (partitions-r (- 1) (+ b 1))     ))   ))  (define (cons-f lst)   (cond          ((eq? lst nil) nil)         ((eq? (cdar lst) nil) lst)          ((< (caar lst) (cadar lst)) (cons-f (cdr lst)))         ((= (caar lst) (+ 1 (cadar lst))) (cons-f (cdr lst)))         (else (cons (car lst) (cons-f (cdr lst)))) ))  (define (list-partitions total)   (cond ((= total 1) '((1)) )         ((= total 0) '(()) )         (else (append nil (partitions-r total 0))) ))  ; these 2 tests, permutation of right answer accepted. (list-partitions 5) ; expect ((5) (4 1) (3 1 1) (1 1 1 1 1)) (list-partitions 7) ; expect ((7) (6 1) (5 2) (5 1 1) (4 1 1 1) (3 3 1) (3 1 1 1 1) (1 1 1 1 1 1 1)) 

what function partitions-r , cons-f do? thank much!

don't know scheme, recursive generation in pseudocode might like:

function partitions(n, lastvalue, list): if n = 0     print list else      min(lastvalue, n) downto  1         if (i != lastvalue - 1)    //reject consecutive number             partitions(n - i, i, list  + [i]); 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -