;;; unshuffle: split a given list into two, transferring alternate ;;; elements to different lists ;;; John David Stone ;;; Department of Mathematics and Computer Science ;;; Grinnell College ;;; stone@cs.grinnell.edu ;;; created February 2, 2000 ;;; last revised February 2, 2000 ;;; Given: ;;; LS, a list. ;;; Result: ;;; SPLIT, a list of two lists. ;;; Preconditions: ;;; None. ;;; Postconditions: ;;; Let |LS| be the length of LS. ;;; (1) The length of the first element of SPLIT is ;;; ceiling(|LS| / 2) and that of the second is floor(|LS| / 2). ;;; (2) For every natural number k less than |LS|, the element ;;; in position k of LS is the element in position floor(k / 2) ;;; of the first element of SPLIT if k is even, or the element ;;; in position floor(k / 2) of the second element of SPLIT if ;;; k is odd. (define unshuffle (lambda (ls) (if (null? ls) (list null null) (swap-and-cons (car ls) (unshuffle (cdr ls)))))) ;;; The helper procedure SWAP-AND-CONS takes the first element of a list ;;; and the result of a recursive call to UNSHUFFLE as its arguments and ;;; rearranges their pieces so as to built the appropriate value for ;;; UNSHUFFLE to return. Specifically, it recovers the two lists that ;;; are elements of the result of the recursive call, reverses their order ;;; (that's the ``swap'' part), conses the new element to the front of ;;; one (that's the ``cons'' part), and repackages them as a two-element ;;; list of lists. ;;; For instance: ;;; > (swap-and-cons 'a (list (list 'b 'd 'f 'h) (list 'c 'e 'g 'i))) ;;; ((a c e g i) (b d f h)) ;;; Givens: ;;; FIRST. ;;; UNSHUFFLED, a list of two lists. ;;; Result: ;;; RESULT, a list of two lists. ;;; Preconditions: ;;; None. ;;; Postconditions: ;;; (1) The element in position 0 of the element in position 0 of RESULT ;;; is FIRST. ;;; (2) For every natural number k less than the length of the element in ;;; position 1 of UNSHUFFLED, the element in position k + 1 of the ;;; element in position 0 of RESULT is the element in position k of ;;; the element in position 1 of UNSHUFFLED. ;;; (3) The element in position 1 of RESULT is the element in position 0 ;;; of UNSHUFFLED. (define swap-and-cons (lambda (first unshuffled) (list (cons first (car (cdr unshuffled))) (car unshuffled))))