Skip to content

Instantly share code, notes, and snippets.

@KiraBen
Created December 15, 2020 13:10
Show Gist options
  • Save KiraBen/fd70ea1063dfcdadfea0332343e37558 to your computer and use it in GitHub Desktop.
Save KiraBen/fd70ea1063dfcdadfea0332343e37558 to your computer and use it in GitHub Desktop.
(define (lst-without-first-occurrence-of lst element)
(cond
[(empty? lst) empty]
[(= (first lst) element) (rest lst) ]
[else (cons (first lst) (lst-without-first-occurrence-of (rest lst) element))]))
(define ( len lst)
(cond
[(empty? lst) 0]
[else (+ 1 (len (rest lst)))]))
(define (last lst)
(cond
[(empty? lst)0]
[(= (len lst) 1) (first lst)]
[else (last (rest lst))]))
(define (swap lst)
(cond
[(empty? lst)0]
[else(cons (last lst)(lst-without-first-occurrence-of lst (last lst)))]))
(define (factorial n)
( if ( = n 0 ) 1 ( * n ( factorial ( - n 1 ) ) ) ) )
(define (is-there? accu-list elementlst)
(cond
[(empty? accu-list)#f]
[(and(empty? accu-list)(empty? elementlst)) #f]
[(equal? (first accu-list) (list elementlst))#t]
[else (is-there? (rest accu-list) elementlst)]))
(define (all-permutations-helper lst accu)
(local
((define (all-permutations-helper-accu lst-helper prefix accu)
(cond
[(and (empty? lst-helper)(empty? prefix))(all-permutations (swap lst accu))]
[[empty? prefix] (all-permutations-helper-accu (rest lst-helper) (list (first lst-helper)) accu) ]
[(is-there? accu prefix) (all-permutations-helper-accu (swap (rest lst-helper)) (first prefix) accu)]
[(empty? lst-helper) (all-permutations prefix ( append (list prefix) accu))]
[(= (len lst-helper)1) (all-permutations-helper-accu (rest lst-helper) (append (list (first lst-helper)) prefix) accu)]
[else (all-permutations-helper-accu (swap (rest lst-helper)) (append (list (first lst-helper)) prefix) accu)])))
(all-permutations-helper-accu lst empty accu)))
(define (all-permutations lst accu)
(cond
[(empty? lst) #f]
[(= (len accu)(factorial(len lst))) accu]
[else (all-permutations-helper lst accu)]
))
(all-permutations (list 1 2 3) empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment