Adding a randomize word to sequences-lib.

db4
John Benediktsson 2008-09-25 13:11:48 -07:00
parent 901288a835
commit fd969a3a7f
2 changed files with 18 additions and 0 deletions

View File

@ -18,3 +18,8 @@ HELP: each-withn
"passed to the quotation given to each-withn for each element in the sequence."
}
{ $see-also map-withn } ;
HELP: randomize
{ $values { "seq" sequence } { "seq'" sequence } }
{ $description "Shuffle the elements in the sequence randomly, returning the new sequence." } ;

View File

@ -160,3 +160,16 @@ PRIVATE>
: ?nth* ( n seq -- elt/f ? )
2dup bounds-check? [ nth-unsafe t ] [ 2drop f f ] if ; flushable
! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
USE: math.ranges
USE: random
: randomize ( seq -- seq' )
dup length 1-
[ dup 1 > ] [
[ [0,b) random ] keep dup
[ rot [ exchange ] keep ] dip 1-
] [ drop ] while ;