math.combinatorics: improve all-subsets and selections words.

db4
John Benediktsson 2010-07-26 08:12:36 -07:00
parent 0b7ed3bdb9
commit f1eb6a9d6e
2 changed files with 12 additions and 17 deletions

View File

@ -78,7 +78,7 @@ IN: math.combinatorics.tests
[ { } ] [ { 1 2 } 0 selections ] unit-test [ { } ] [ { 1 2 } 0 selections ] unit-test
[ { { 1 2 } } ] [ { 1 2 } 1 selections ] unit-test [ { { 1 } { 2 } } ] [ { 1 2 } 1 selections ] unit-test
[ { { 1 1 } { 1 2 } { 2 1 } { 2 2 } } ] [ { { 1 1 } { 1 2 } { 2 1 } { 2 2 } } ]
[ { 1 2 } 2 selections ] unit-test [ { 1 2 } 2 selections ] unit-test

View File

@ -1,8 +1,10 @@
! Copyright (c) 2007-2010 Slava Pestov, Doug Coleman, Aaron Schaefer, John Benediktsson. ! Copyright (c) 2007-2010 Slava Pestov, Doug Coleman, Aaron Schaefer, John Benediktsson.
! See http://factorcode.org/license.txt for BSD license. ! See http://factorcode.org/license.txt for BSD license.
USING: accessors assocs binary-search fry kernel locals math math.order
math.ranges namespaces sequences sorting make sequences.deep arrays USING: accessors arrays assocs binary-search fry kernel locals
combinators ; math math.order math.ranges namespaces sequences sequences.deep
sorting ;
IN: math.combinatorics IN: math.combinatorics
<PRIVATE <PRIVATE
@ -129,21 +131,14 @@ PRIVATE>
[ -rot ] dip each-combination ; inline [ -rot ] dip each-combination ; inline
: all-subsets ( seq -- subsets ) : all-subsets ( seq -- subsets )
dup length [0,b] [ dup length [0,b] [ all-combinations ] with map concat ;
[ dupd all-combinations [ , ] each ] each
] { } make nip ;
: (selections) ( seq n -- selections ) : (selections) ( seq n -- selections )
dupd [ dup 1 > ] [ [ [ 1array ] map dup ] [ 1 - ] bi*
swap pick cartesian-product [ [ cartesian-product concat ] with times
[ [ dup length 1 > [ flatten ] when , ] each ] each [ flatten ] map ;
] { } make swap 1 -
] while drop nip ;
: selections ( seq n -- selections ) : selections ( seq n -- selections )
{ dup 0 > [ (selections) ] [ 2drop { } ] if ;
{ 0 [ drop { } ] }
{ 1 [ 1array ] }
[ (selections) ]
} case ;