Nathan Campos
Nathan Campos

Reputation: 29497

Choose For Random Strings In Commodore 64 BASIC

I have this variable declarations on my program:

X="MAGENTA"
Y="CYAN"
Z="TAN"
A="KHAKI"

Now what I want is to randomly choose one of these and PRINT it. But how to do this?

Upvotes: 9

Views: 1066

Answers (3)

rje
rje

Reputation: 274

Here's another way to do it, using one variable for the output and ON..GOSUB to set it based on a random number in the range [1..4].

10 ON INT(RND(1)*4+1) GOSUB 100,110,120,130
20 PRINT A$
30 END
100 A$ = "MAGENTA":RETURN
110 A$ = "CYAN":RETURN
120 A$ = "TAN":RETURN
130 A$ = "KHAKI":RETURN

Upvotes: 1

rje
rje

Reputation: 274

The above answer is correct and comprehensive.

This answer, on the other hand, is not, but I was actually doing a little bit of Commodore BASIC last month and decided that string indexing CAN be useful, sometimes, so here's a non-answer that sort of reframes your problem.

100 X$ = "MAGENTACYAN TAN KHAKI " 110 PRINT MID$(X$,INT(RND(1)*4)*7, 7)

This code gets a random int from 0 to 3, then uses that to find the start index into a single string that contains all four entries, each of which is padded out (where necessary) to 7 characters. That padding is needed because the final parameter to MID$ is the length of the substring to be extracted.

WHY BOTHER?

When to consider indexing over an array: (1) when your string data is near-uniform length, and (2) when you have a LOT of little strings.

If those two conditions are true, then the full code, including the data, is more compact, and takes less memory due to allocating fewer pointers.

P.S. Bonus point if you find that I've made an off-by-one error!

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881323

My BASIC is pretty rusty but you should just be able to use something like:

10 X$ = "MAGENTA"
20 Y$ = "CYAN"
30 Z$ = "TAN"
40 A$ = "KHAKI"
50 N = INT(RND(1) * 4)
60 IF N = 0 THEN PRINT X$
70 IF N = 1 THEN PRINT Y$
80 IF N = 2 THEN PRINT Z$
90 IF N = 3 THEN PRINT A$

or, putting it in a subroutine for code re-use:

  10 X$ = "MAGENTA"
  20 Y$ = "CYAN"
  30 Z$ = "TAN"
  40 A$ = "KHAKI"
  50 GOSUB 1000
  60 PRINT RC$
  70 END

1000 TV = INT(RND(1) * 4)
1010 IF TV = 0 THEN RC$ = X$
1020 IF TV = 1 THEN RC$ = Y$
1030 IF TV = 2 THEN RC$ = Z$
1040 IF TV = 3 THEN RC$ = A$
1050 RETURN

Of course, you probably should be using arrays for that sort of thing so you can just use:

10 DIM A$(3)
10 A$(0) = "MAGENTA"
20 A$(1) = "CYAN"
30 A$(2) = "TAN"
40 A$(3) = "KHAKI"
50 PRINT A$(INT(RND(1)*4))

Upvotes: 5

Related Questions