| 1 |
// name: array_shuffle.ck |
| 2 |
// desc: shuffling the contents of an array; useful for tasks like random without replacement |
| 3 |
// author: kunwoo, nshaheed, andrew, ge | 1.5.0.0 |
| 4 |
|
| 5 |
// an array |
| 6 |
[1,2,3,4,5] @=> int a[]; |
| 7 |
|
| 8 |
// uncomment to print array API |
| 9 |
// a.help(); |
| 10 |
// uncomment to explicitly set a random seed |
| 11 |
// Math.srandom(11); |
| 12 |
|
| 13 |
// shuffle a few times |
| 14 |
repeat( 10 ) |
| 15 |
{ |
| 16 |
// print |
| 17 |
for( int i; i < a.size(); i++ ) |
| 18 |
{ cherr <= a[i] <= " "; } cherr <= IO.nl(); |
| 19 |
// shuffle! |
| 20 |
a.shuffle(); |
| 21 |
} |
| 22 |
|
| 23 |
// one way to do random without replacement |
| 24 |
repeat( 3 ) |
| 25 |
{ |
| 26 |
cherr <= "--- random without replacment --- " <= IO.nl(); |
| 27 |
// shuffle! |
| 28 |
a.shuffle(); |
| 29 |
// just go through array in order after shuffle |
| 30 |
for( int i; i < a.size(); i++ ) |
| 31 |
{ |
| 32 |
// print the next "random" value |
| 33 |
cherr <= "next value: " <= a[i] <= IO.nl(); |
| 34 |
} |
| 35 |
} |