8.5 Permutations
(require rebellion/permutation) | package: rebellion |
A permutation is a rearrangement of a finite set, with elements of the set represented by natural numbers. More formally, a permutation of size n is a bijection from the set of natural numbers less than n to itself. Permutations are useful for efficiently expressing how collections are arranged, ordered, and sorted. Two permutations are equal? if they have the same size and rearrange elements in the same way.
procedure
(permutation? v) → boolean?
v : any/c
syntax
(permutation position ...)
> (permute "abcd" (permutation 0 2 1 3) #:into into-string) "acbd"
> (permute "abcd" (permutation 3 2 1 0) #:into into-string) "dcba"
syntax
(cyclic-permutation position ...)
> (permute "abcdefghijklmnopqrstuvwxyz" (cyclic-permutation 5 17 25 8 0) #:into into-string) "ibcdeaghzjklmnopqfstuvwxyr"
value
procedure
(permutation-size perm) → natural?
perm : permutation?
> (permutation-size (permutation 0 1 2 3 4 5)) 6
> (permutation-size (cyclic-permutation 6 18 4 3 11)) 19
procedure
(permutation-ref perm pos)
→ (and/c natural? (</c (permutation-size perm))) perm : permutation? pos : (and/c natural? (</c (permutation-size perm)))
> (define p (permutation 3 8 2 7 1 6 0 5 4)) > (permutation-ref p 0) 3
> (permutation-ref p 3) 7
> (permutation-ref p 8) 4
procedure
seq : (sequence/c any/c) perm : permutation? reducer : reducer? = (into-vector)
> (permute '(a b c d e f) (permutation 4 1 5 3 0 2)) '#(e b f d a c)
> (permute "abcdef" (permutation 4 1 5 3 0 2) #:into into-string) "ebfdac"
procedure
(permuting perm) → transducer?
perm : permutation?
> (transduce "abcdef" (permuting (permutation 5 4 3 2 1 0)) #:into into-string) "fedcba"
procedure
(permutation-reverse perm) → permutation?
perm : permutation?
(define shift-right-once (permutation 1 2 3 4 5 0))
> (permute "abcdef" shift-right-once #:into into-string) "bcdefa"
> (permute "abcdef" (permutation-reverse shift-right-once) #:into into-string) "fabcde"