[REBOL] Re: Question and comment about randomizing a block of values
From: agem:crosswinds at: 19-Jun-2001 1:53
RE: [REBOL] Re: Question and comment about randomizing a block of values
[joel--neely--fedex--com] wrote:
> Hi, Jos (and all),
>
> Sorry to be replying to my own post, but another bit of explanation
> might be in order...
>
> Joel Neely wrote:
> >
> > random-iota: func [n [integer!] /local m f c r] [
> > f: n + 1
> > m: f * f
> > c: 0
> > r: make block! n
> > loop n [append r (f * random m) + c: c + 1]
> > ]
> >
>
> The reason why F needs to be N + 1 is that REBOL uses 1-origin
> indexing instead of 0-origin indexing. Since our weird numbers
> have to have remainders in the range 1..N we have to multiply
> the high-order randomness by N + 1 to protect all of the indexes.
>
> The reason why M is F * F is simply to give RANDOM more of a
> chance to "spread" the high-order randomness out, reducing the
> probability that we'll get duplicates in the H-O R.
>
> HOWEVER...
>
> Upon further reflection, I've decided that the coupling between
> RANDOM-IOTA and SHUFFLED is just too ugly for words. Therefore,
> I propose to atone for that ugliness that by offering the
> slightly-less-ugly:
>
> shuffled-iota: func [n [integer!] /local m f c r] [
> m: n * n
> c: -1
> r: make block! n
> loop n [append r (n * random m) + c: c + 1]
> sort r
> forall r [change r r/1 // n + 1]
> head r
> ]
>
;Aargh! whats this? you are going to beat Ladislav in puzzling!
;specially tricky the hidden assignment of 'c ! :)
; after puzzling a while i think you do this? :
[rebol []
???: func ["set-word!-?? , dump-tool" 'word value] [
print [mold :word " : " mold :value] word :value]
shuffled-iota: func [n [integer!] /local f r r1 i] [
f: 2 ** 30
;make a block of pairs [57 1 82 2 16 3 ..]
r1: make block! n * 2
repeat i n [append r1 reduce [random f i]] ;flat block!
sort/skip ?? r1 2 ;shuffle-map ready
? r1
;now keep only the indices, kill randoms
r: make block! n
forskip r1 2 [append r second r1]
r
]
shuffled-block: func [b [block!] /local n i r] [
r: make block! n: length? b
i: shuffled-iota n
foreach n i [append r pick b n]
]
;and test
random/seed now
??? test-data: repeat i 20 [append [] i] ;never in function!
??? new-data: shuffled-block test-data
??? all-numbers-there?: sort copy new-data
;-) Volker
]