0

I have this,

    srand( ( unsigned) 0 );
    for( n = 0; n < len; ++n )  
     {                          
         word[ n ] = 'a' + rand( ) % ;

     }
     word[ n ] = '\0';

and i need it to select the random characters from a set list of non consecutive, characters, B,H,G,K,V and fill the string with the characters selected. What I don't know how to do is get my program to select from only those few characters

1 Answers1

2

Generate an integer between 0 and 4 (last index of [B,H,G,K,V]).

Then use this random integer to index into an array of your characters:

static const char letters[] = "BHGKV"; //your letters as a string
word[n] = letters[rand() % 5]; //get a random letter from letters

Note, rand() % 5 may not be the best way to generate a random number in a range.

Community
  • 1
  • 1
River
  • 8,585
  • 14
  • 54
  • 67
  • Note this will not generate an uniform distribution if `(RAND_MAX + 1) % 5 != 0` Sidenote: why not use a string literal, but an `int`? – too honest for this site Jun 15 '15 at 20:10
  • @Olaf Yep, indeed. But what about the missing operand after `%` in OP's code? Did you notice? – Sourav Ghosh Jun 15 '15 at 20:14
  • why do you use the `floor` function? it is a no-op in the best case and will create problems if the `double` value of an integer is smaller than the `int` itself. – mch Jun 15 '15 at 20:23
  • @mch because I'm a C newbie. My code is more pseudo than actual. What is the proper way to floor an `int` in C? (Just looked it up, I will change to an `int` cast.) – River Jun 15 '15 at 20:29
  • As `floor()` rounds a float to the next lower `int`: what do you want and`int` to be rounded to? Note: `rand()` already returns an `int`. – too honest for this site Jun 15 '15 at 20:33
  • @Olaf thank you. Ah my I assumed it was analogous to the Java Math.random(). Think my code should be C-worthy now. – River Jun 15 '15 at 20:34
  • 1
    Well, I would make `letters` `static const` so it will not be created/copied on each call. And there is still the issue with non-uniform distribution. Albeit I would not care too much for this question:-} and as you added a link to that, it looks ok to me. – too honest for this site Jun 15 '15 at 20:35