Jacob
Jacob

Reputation: 105

How to generate random characters from only 'A', 'B', 'S' and 'Z' in C?

This code generates random characters from 'A' to 'Z' but I need to generate random characters from only 'A', 'B', 'S' and 'Z' characters. Please help.

int main (void)
{
    srand(time(NULL));
    char random;

    random = (rand() % 26) + 'A';

    printf ("Random: %c\n", random);

    return 0;
}

Upvotes: 3

Views: 239

Answers (3)

chux
chux

Reputation: 153468

user3386109 good answer is far too simple, portable, understandable and useful.

How about some obfuscation?

int rand ABSZ(void) {
  int x = rand()%4;
  return ((x*-13 + 63)*x + -47)*x/3 + 'A';
}

Upvotes: 1

Paolo
Paolo

Reputation: 15827

Make a string with the allowed characters;

select a random number from 0 to the number of characters - 1 (c arrays starts from zero);

finally pick the random selected character from the string accessing it as an array

(strings are arrays of characters)

int main (void)
{
    char *characters="ABSZ";
    int  whichOne;

    srand(time(NULL));

    whichOne = rand() % 4; // 0..3

    printf ("Random: %c\n", characters[whichOne]);

    return 0;
}

Upvotes: 2

user3386109
user3386109

Reputation: 34829

Since a string literal, e.g. "ABSZ" can be used like an array of char, you can choose a random character from a set of allowed characters with code like this

random = "ABSZ"[rand()%4];

Upvotes: 3

Related Questions