math.combinators: Add filter-permutations/combinations. Minor cleanup.

db4
Doug Coleman 2012-04-18 15:17:48 -07:00
parent 229d0e0549
commit 0322b4d028
2 changed files with 25 additions and 5 deletions

View File

@ -94,3 +94,15 @@ IN: math.combinatorics.tests
{ 2 1 1 } { 2 1 2 } { 2 2 1 } { 2 2 2 } } ]
[ { 1 2 } 3 selections ] unit-test
{ V{ { 1 2 } { 1 3 } } }
[ { 1 2 3 } 2 [ { 1 } head? ] filter-combinations ] unit-test
{ { 3 4 5 } }
[ { 1 2 3 } 2 [ sum ] map-combinations ] unit-test
{ V{ { 1 2 3 } { 1 3 2 } } }
[ { 1 2 3 } [ { 1 } head? ] filter-permutations ] unit-test
{ { 6 6 6 6 6 6 } }
[ { 1 2 3 } [ sum ] map-permutations ] unit-test

View File

@ -42,23 +42,29 @@ PRIVATE>
: permutation-indices ( n seq -- permutation )
length [ factoradic ] dip 0 pad-head >permutation ;
: permutation-iota ( seq -- iota )
length factorial iota ; inline
PRIVATE>
: permutation ( n seq -- seq' )
[ permutation-indices ] keep nths ;
: all-permutations ( seq -- seq' )
[ length factorial iota ] keep
[ permutation-iota ] keep
'[ _ permutation ] map ;
: each-permutation ( seq quot -- )
[ [ length factorial iota ] keep ] dip
[ [ permutation-iota ] keep ] dip
'[ _ permutation @ ] each ; inline
: map-permutation ( seq quot -- )
[ [ length factorial iota ] keep ] dip
: map-permutations ( seq quot -- seq' )
[ [ permutation-iota ] keep ] dip
'[ _ permutation @ ] map ; inline
: filter-permutations ( seq quot -- seq' )
selector [ each-permutation ] dip ; inline
: reduce-permutations ( seq identity quot -- result )
swapd each-permutation ; inline
@ -142,6 +148,9 @@ PRIVATE>
: map-combinations ( seq k quot -- )
combinations-quot map ; inline
: filter-combinations ( seq k quot -- seq' )
selector [ each-combination ] dip ; inline
: map>assoc-combinations ( seq k quot exemplar -- )
[ combinations-quot ] dip map>assoc ; inline
@ -169,4 +178,3 @@ PRIVATE>
: selections ( seq n -- selections )
dup 0 > [ (selections) ] [ 2drop { } ] if ;