development, tutorial

[code] Picking a random letter in CAOS

Malkin approached me on Discord, asking me how to pick a random letter. I’ve been using random numbers in CAOS with the RAND command for like forever, but I hadn’t found a reason yet to pick random letters. The question made me think, though.

Of course, there’s the old-fashioned, boring and bulky-code-way of just picking a random number between 1 and number-of-letters-in-the-alphabet. Then you can set a variable to a letter depending on the value of that number, in an if-elif-elif-elif-elif-… scenario.

Surely there should be a cleaner/easier way!

Recently I learned more about the CHAR variable thanks to Amaikokonut’s blog post over at Naturing :: Nurturing. I noticed char has two commands, one that returns a variable and one that sets a variable.

The command returning the character returns the ASCII number for that character.
I wondered if the one setting a variable also uses the ASCII code for a character: Yup!

So, all that’s left is to figure out the ASCII numbers of the characters you want to use.

For the characters A to Z, that’s 65 to 90. For the characters a to z, that’s 97 to 122.

So if you want a character between a to z, the resulting code would be this:

sets va00 “a”
setv va01 rand 97 122
char va00 1 va01

Nice and clean, right? 😀

 

Advertisements

1 thought on “[code] Picking a random letter in CAOS”

  1. Thanks for posting this up on your blog – the CAOS Coding Cave is great for getting a quick answer, but it’s important to have this information be more widely searchable, too.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s