From c1ab4aab5936ed8d565ec3a0d2c6e64b69573c21 Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Wed, 1 May 2013 11:18:17 -0700 Subject: [PATCH] math.combinatorics: faster by using hints for the array common case. --- basis/math/combinatorics/combinatorics.factor | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/basis/math/combinatorics/combinatorics.factor b/basis/math/combinatorics/combinatorics.factor index 1da0ad100d..7136982e1b 100644 --- a/basis/math/combinatorics/combinatorics.factor +++ b/basis/math/combinatorics/combinatorics.factor @@ -2,8 +2,8 @@ ! See http://factorcode.org/license.txt for BSD license. USING: accessors arrays assocs binary-search classes.tuple fry -kernel locals math math.order math.ranges memoize namespaces -sequences sequences.private sorting ; +hints kernel locals math math.order math.ranges memoize +namespaces sequences sequences.private sorting ; FROM: sequences => change-nth ; IN: math.combinatorics @@ -100,13 +100,13 @@ PRIVATE> ] keep swap ] find-last drop nip ; + [ last ] keep [ [ > ] keep swap ] find-last drop nip ; inline : greater-from-last ( n seq -- i ) - [ nip ] [ nth ] 2bi [ > ] curry find-last drop ; + [ nip ] [ nth ] 2bi [ > ] curry find-last drop ; inline : reverse-tail! ( n seq -- seq ) - [ swap 1 + tail-slice reverse! drop ] keep ; + [ swap 1 + tail-slice reverse! drop ] keep ; inline : (next-permutation) ( seq -- seq ) dup cut-point [ @@ -114,6 +114,8 @@ PRIVATE> [ exchange ] [ reverse-tail! nip ] 3bi ] [ reverse! ] if* ; +HINTS: (next-permutation) array ; + PRIVATE> : next-permutation ( seq -- seq ) @@ -162,14 +164,14 @@ INSTANCE: combinations immutable-sequence = ] find-index drop ; + over length - '[ _ + >= ] find-index drop ; inline : increment-rest ( i seq -- ) [ nth ] [ swap tail-slice ] 2bi - [ drop 1 + dup ] map! 2drop ; + [ drop 1 + dup ] map! 2drop ; inline : increment-last ( seq -- ) - [ [ length 1 - ] keep [ 1 + ] change-nth ] unless-empty ; + [ [ length 1 - ] keep [ 1 + ] change-nth ] unless-empty ; inline :: next-combination ( seq n -- seq ) seq n find-max-index [ @@ -178,6 +180,8 @@ INSTANCE: combinations immutable-sequence seq increment-last ] if* seq ; +HINTS: next-combination array fixnum ; + :: combinations-quot ( seq k quot -- seq quot' ) seq length :> n n k nCk iota k iota >array seq quot n