Skip to content

Instantly share code, notes, and snippets.

@farseerfc
Created December 4, 2011 15:06
Show Gist options
  • Save farseerfc/1430398 to your computer and use it in GitHub Desktop.
Save farseerfc/1430398 to your computer and use it in GitHub Desktop.
Permutation genetator in scheme
(define (empty? list)
(eq? list '()))
(define (len list)
(cond ((empty? list) 0)
(else (+ 1 (len (cdr list))))))
(define (append list num)
(cond ((empty? num) list)
((empty? list) (cons num '()))
(else (cons (car list) (append (cdr list) num)))))
(define (last list)
(cond ((empty? list) '())
((empty? (cdr list)) (car list))
(else (last (cdr list)))))
(define (reverse list)
(define (iter li rem)
(cond ((empty? li) rem)
(else (iter (cdr li) (cons (car li) rem)))))
(iter list '()))
(define (del-last list)
(define (iter li rem)
(cond ((empty? li) rem)
((empty? (cdr li)) rem)
(else (iter (cdr li) (cons (car li) rem)))))
(reverse (iter list '())))
(define (concate l1 l2)
(cond ((empty? l1) l2)
(else (concate (del-last l1) (cons (last l1) l2)))))
(define (fc l1 l2)
(concate (del-last l1)
(concate (cons (car (filter (lambda (x)(> x (last l1))) (reverse l2)))
(filter (lambda (x)(<= x (last l1))) (reverse l2)))
(cons (last l1)
(cdr (filter (lambda (x)(> x (last l1))) (reverse l2)))))))
(define (fr l1 l2)
(cond ((empty? l2) (fr (del-last l1) (cons (last l1) l2)))
((empty? l1) '())
((> (last l1) (car l2)) (fr (del-last l1) (cons (last l1) l2)))
(else (fc l1 l2))))
(define (perm list)
(cond ((empty? list) '())
(else (cons list (perm (fr list '()))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment