## Spectrum Basic:putting random numbers in an array

The place for codemasters or beginners to talk about programming any language for the Spectrum.
KayBee
Berk
Posts: 17
Joined: Thu May 31, 2018 3:14 pm

### Spectrum Basic:putting random numbers in an array

Hello Spectrum BASIC experts,

I am new to programming and am self-teaching BASIC. I had an idea and would appreciate some mentoring on this. To test a simple game idea I would like to store random numbers in an array. Thank you for any guidance you can spare.

Cheers,

KB
0 x

Blerkotron
Dizzy
Posts: 90
Joined: Mon Nov 13, 2017 12:36 pm

### Re: Spectrum Basic:putting random numbers in an array

Try something like this:

Code: Select all

``````10 randomize: dim a(10)
20 for n = 1 to 10: let a(n) = int(rnd*10)+1: next n
30 for n = 1 to 10: print a(n): next n``````
Explanations:
10: initialise the random number generator and dimension your array of numbers, a, to hold ten numbers.
20: loop ten times, assigning a random number to each element of the array in turn. The number will be an integer (int) from 1 to 10 (rnd*10). Actually int(rnd*10) gives you a number from 0 to 9, so the +1 prevents you from getting a 0 and allows you to get a 10.
30: loop ten times again, this time printing each of the ten array elements to the screen.
1 x

PeterJ
Posts: 2665
Joined: Thu Nov 09, 2017 7:19 pm
Location: Surrey, UK

### Re: Spectrum Basic:putting random numbers in an array

You beat me to it @Blerkotron

1 x

ZXDunny
Manic Miner
Posts: 315
Joined: Tue Nov 14, 2017 3:45 pm

### Re: Spectrum Basic:putting random numbers in an array

How about we get a little fancier?

Code: Select all

``10 LET a\$="0123456789": DIM b(10): FOR f=1 TO 10: LET c=(RND*LEN a\$)+1: LET b(f)=VAL a\$(c)+1: LET a\$=a\$( TO c-1)+a\$(c+1 TO): NEXT f``
1 x

oblo
Berk
Posts: 29
Joined: Mon Dec 10, 2018 9:24 pm

### Re: Spectrum Basic:putting random numbers in an array

A (more unnecessarily complicated but fun) ZXBasic approach here:

Code: Select all

``````REM initialize screen
PAPER 0 : BORDER 0 : INK 7 : CLS

REM initialize array and variables; arrays starts at 0 but it can be changed
DIM myarray(9) as UBYTE
DIM y AS UBYTE

REM loop to fill array several times until user is satisfied with the result
DO
FOR y = 0 TO 9
myarray(y) = (RND*100)   REM INT is not needed because the array and variable were initialized as UBYTE
PRINT AT y,0; "myarray("; y; ")= "; myarray(y); " ";
NEXT y

PRINT AT 22,0; INK 5; BOLD 1; "Press ENTER to STOP or"; AT 23,0; INK 6; ITALIC 1;"Press any other key to retry";
PAUSE 0

LOOP WHILE INKEY\$ <> CHR(13)``````
Cheers
0 x
Cheers.

KayBee
Berk
Posts: 17
Joined: Thu May 31, 2018 3:14 pm

### Re: Spectrum Basic:putting random numbers in an array

Great Gentlemen,

Many helpful folks here, best quality forum I use. I especially appreciate the variations.

Cheers to you all.

And of course now it makes total sense, as most things seem to once you have the answer.

KB
1 x