Choosing random data

The place for codemasters or beginners to talk about programming any language for the Spectrum.
Post Reply
User avatar
beanz
Microbot
Posts: 183
Joined: Wed Mar 21, 2018 1:10 pm
Location: Texas USA

Choosing random data

Post by beanz »

I want to have the program report the data array randomly rather than in order. So if I have say 5 city names int he data statement rather than reporting them in order it would be reported..out of order. So here is what I have

10 for a=1 to 5 step 1
20 read b$
30 Print b$
40 Next A
50 data "london", "machester", "liverpool", "Birmingham", "southport"

So instead of it going in order "london, manchester, liverpool, birmingham, southport" I'd like the results to be randomized in the order they appear.

Thanks.
AndyC
Dynamite Dan
Posts: 1408
Joined: Mon Nov 13, 2017 5:12 am

Re: Choosing random data

Post by AndyC »

Put the indices in a separate array (I e. The values 1 ..5) then shuffle those using a few random swaps. Then print out the city name by looping over that array in order and printing out the city at the position indicated by the stored index.
sn3j
Manic Miner
Posts: 500
Joined: Mon Oct 31, 2022 12:29 am
Location: Germany

Re: Choosing random data

Post by sn3j »

Code: Select all

 10 RESTORE 10: READ n: DIM s$(n,20): DATA 5,"s1","s2","s3","s4","s5"
 20 FOR i=1 TO n: READ s$(i): NEXT i
 30 GOSUB 100: REM shuffle
 40 FOR i=1 TO n: PRINT s$(i): NEXT i
 50 STOP
100 FOR i=n TO 2 STEP -1
110 LET a=INT(i*RND+1): REM random number 1..n
120 LET t$=s$(a): LET s$(a)=s$(i): LET s$(i)=t$: REM swap pair
130 NEXT i: RETURN
POKE 23614,10: STOP      1..0 hold, SS/m/n colors, b/spc toggle
User avatar
beanz
Microbot
Posts: 183
Joined: Wed Mar 21, 2018 1:10 pm
Location: Texas USA

Re: Choosing random data

Post by beanz »

Thanks
Post Reply