2017-08-18 20 views
-1

私はcs61a spring 2015クラスに従っています。連続する整数を使用しないでnumberのパーティション

スキームプロジェクトにおける問題の一つは、次のとおりです。

は パーティションの連続した整数を使用せずに、正の整数の合計の方法のすべてを一覧表示し、リスト・パーティションの手順を実装します。各パーティションの の内容は、降順でリストされている必要があります。 ヒント:パーティションを作成するヘルパープロシージャを定義します。組み込みの追加 プロシージャは、2つの引数リストのすべての要素を含むリストを作成します。 questions.scmのcons-allプロシージャは、リストのリストの各リストに最初の要素を追加します。 、

4、1

3、1、1

1、1、1、1:

数5は、連続した整数を含まない4つのパーティションを持っています1

の整数のため、次の5つのパーティションは含まれません。

3、2

2、2、1

2、1、1、1

私は一つの解決策が見つかりましたが

機能パーティションを何
;; List all ways to 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 a b) 
    (if (= a 0) nil 
    (append (cons-all a (list-partitions b)) 
      (cons-f (partitions-r (- a 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))) 
)) 

; For these two tests, any permutation of the right answer will be 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)) 

それを理解することはできません-rとcons-fはできますか?どうもありがとうございました!

答えて

0

スキームを知らないが、擬似コードで再帰的な生成は次のようになります。

function Partitions(N, LastValue, list): 
if N = 0 
    print list 
else 
    for i from Min(LastValue, N) downto 1 
     if (i != LastValue - 1) //reject consecutive number 
      Partitions(N - i, i, list + [i]); 
関連する問題