# Paste: shuffle an array

Author: Pepijn de Vos forth Mon, 31 Oct 2011 14:39:29
Plain Text |
\ Simple random number generator
\ from Leo Brodie, _Starting Forth_

VARIABLE RND  \ Holds current result

\ Generate a random integer
: RANDOM  ( -- u )  RND @  31421 *  6927 +  DUP RND ! ;

\ Return a random integer between 0 and u-1
: CHOOSE  ( lo hi -- lo...hi-1 )
over -
RANDOM swap mod
+ ;

\ Initialize
: RANDOMIZE  ( -- )  TIME&DATE + + + + + RND ! ;

\ my code

: range ( n -- ) 0 do i , loop ;
: th ( n -- ) cells + ;
: s! swap ! ;
: scan ( addr count ) 0 do dup i cells + @ . loop ;

52 constant #cards
create deck #cards range

dup @ >r
swap
dup @ >r
r> s! r> s! ;

: shuffle
#cards 0 do
deck   i #cards choose   th
deck i th
interchange
loop ;

## Annotation: factoring

Author: Pepijn de Vos forth Mon, 31 Oct 2011 15:25:53
Plain Text |
\ Simple random number generator
\ from Leo Brodie, _Starting Forth_

VARIABLE RND  \ Holds current result

\ Generate a random integer
: RANDOM  ( -- u )  RND @  31421 *  6927 +  DUP RND ! ;

\ Return a random integer between 0 and u-1
: CHOOSE  ( lo hi -- lo...hi-1 )
over -
RANDOM swap mod
+ ;

\ Initialize
: RANDOMIZE  ( -- )  TIME&DATE + + + + + RND ! ;

\ my code

randomize

: range ( n -- ) 0 do i , loop ;
: th ( n -- ) cells + ;
: s! swap ! ;
: inspect ( addr count ) 0 do dup i cells + @ . loop ;

52 constant #cards
create deck #cards range
variable passing

: copy ( from to -- ) @ s! ;

passing
3 0 do
rot 2dup copy
loop
drop drop drop ;

: shuffle
#cards 0 do
deck   i #cards choose   th
deck i th
interchange
loop ;