Page 1 of 1

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

Posted: Fri Dec 28, 2018 9:03 pm
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

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

Posted: Fri Dec 28, 2018 10:02 pm
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.

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

Posted: Fri Dec 28, 2018 10:07 pm
You beat me to it @Blerkotron ### Re: Spectrum Basic:putting random numbers in an array

Posted: Sat Dec 29, 2018 12:27 am
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``

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

Posted: Sat Dec 29, 2018 9:11 am
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

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

Posted: Sat Dec 29, 2018 8:48 pm
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