Paste: shuffle an array

Author: Pepijn de Vos
Mode: forth
Date: 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

: interchange ( addr1 addr2 -- )
  dup @ >r
  swap
  dup @ >r
  swap ( addr2 addr1 )
  r> s! r> s! ;

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

Annotation: factoring

Author: Pepijn de Vos
Mode: forth
Date: 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! ;

: interchange ( addr1 addr2 -- )
  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 ;

New Annotation

Summary:
Author:
Mode:
Body: