diff --git a/basis/math/combinatorics/combinatorics-tests.factor b/basis/math/combinatorics/combinatorics-tests.factor index bdbbece4f5..14b662b63b 100644 --- a/basis/math/combinatorics/combinatorics-tests.factor +++ b/basis/math/combinatorics/combinatorics-tests.factor @@ -106,3 +106,7 @@ IN: math.combinatorics.tests { { 6 6 6 6 6 6 } } [ { 1 2 3 } [ sum ] map-permutations ] unit-test + +{ { 2 3 } } [ { 1 2 3 } 2 [ first 2 = ] find-combination ] unit-test + +{ { 2 1 3 } } [ { 1 2 3 } [ first 2 = ] find-permutation ] unit-test diff --git a/basis/math/combinatorics/combinatorics.factor b/basis/math/combinatorics/combinatorics.factor index 4652cd6a11..59dd83fa28 100644 --- a/basis/math/combinatorics/combinatorics.factor +++ b/basis/math/combinatorics/combinatorics.factor @@ -65,6 +65,10 @@ PRIVATE> : filter-permutations ( seq quot -- seq' ) selector [ each-permutation ] dip ; inline +: find-permutation ( seq quot -- elt ) + [ dup [ permutation-iota ] keep ] dip + '[ _ permutation @ ] find drop swap permutation ; inline + : reduce-permutations ( seq identity quot -- result ) swapd each-permutation ; inline @@ -145,7 +149,7 @@ PRIVATE> : each-combination ( seq k quot -- ) combinations-quot each ; inline -: map-combinations ( seq k quot -- ) +: map-combinations ( seq k quot -- seq' ) combinations-quot map ; inline : filter-combinations ( seq k quot -- seq' ) @@ -160,6 +164,9 @@ PRIVATE> : all-combinations ( seq k -- seq' ) [ ] map-combinations ; +: find-combination ( seq k quot -- i elt ) + [ combinations-quot find drop ] [ drop combination ] 3bi ; inline + : reduce-combinations ( seq k identity quot -- result ) [ -rot ] dip each-combination ; inline