]> gitweb.factorcode.org Git - factor.git/commitdiff
io.random: much faster version of random-lines for large n.
authorJohn Benediktsson <mrjbq7@gmail.com>
Wed, 24 Oct 2012 02:03:34 +0000 (19:03 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Wed, 24 Oct 2012 02:03:34 +0000 (19:03 -0700)
extra/io/random/random.factor

index a12574fb4367dbcc4b41e6d3b203394434e91952..0c0f28d29fb25537e985064e9e662586186fa2b5 100644 (file)
@@ -1,8 +1,8 @@
 ! Copyright (C) 2012 John Benediktsson
 ! See http://factorcode.org/license.txt for BSD license
 
-USING: fry io kernel locals math random sequences
-sequences.extras ;
+USING: combinators fry io kernel locals math math.order random
+sequences ;
 
 IN: io.random
 
@@ -19,10 +19,10 @@ PRIVATE>
 :: random-lines ( n -- lines )
     V{ } clone :> accum
     [| line line# |
-        line# random :> r
-        r n < [
-            line# n <=
-            [ line r accum insert-nth! ]
-            [ line r accum set-nth ] if
-        ] when
+        line# n <=> {
+            { +lt+ [ line accum push ] }
+            { +eq+ [ line accum [ push ] [ randomize drop ] bi ] }
+            { +gt+ [ line# random :> r
+                     r n < [ line r accum set-nth ] when ] }
+        } case
     ] each-numbered-line accum ;