35S-Section-Solution

35S-Section-Solution - CS107 Spring 2007 Handout 35S May...

This preview shows pages 1–2. Sign up to view the full content.

CS107 Handout 35S Spring 2007 May 25, 2007 Section Solution: All Things Scheme Problem 1: Building Subsets of a Certain Size ;; Function: k-subsets ;; ------------------- ;; k-subsets constructs a list of all those subsets ;; of the specified set whose size just happens to equal k. ;; ;; Examples: (k-subsets '(1 2 3 4) 2) -> ((1 2) (1 3) (1 4) (2 3) (2 4) (3 4)) ;; (k-subsets '(1 2 3 4 5 6) 1) -> ((1) (2) (3) (4) (5) (6)) ;; (k-subsets '(a b c d) 0) -> (()) ;; (k-subsets '(a b d d) 5) -> () (define (k-subsets set k) (cond ((eq? (length set) k) (list set)) ((zero? k) '(())) ((or (negative? k) (> k (length set))) '()) (else (let ((k-subsets-of-rest (k-subsets (cdr set) k)) (k-1-subsets-of-rest (k-subsets (cdr set) (- k 1)))) (append (map (lambda (subset) (cons (car set) subset)) k-1-subsets-of-rest) k-subsets-of-rest))))) Problem 2: Up Down Permutations a. ;; Function: is-up-down? ;; --------------------- ;; Returns true if and only if the specified list is an up-down list ;; according to the specified predicate. ;; ;; Examples: (is-up-down? '() <) -> #t

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/14/2010 for the course CS 107 taught by Professor Cain,g during the Spring '08 term at Stanford.

Page1 / 2

35S-Section-Solution - CS107 Spring 2007 Handout 35S May...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online