lundi 25 octobre 2021

What should I fill this if statement?

I did my best to solve this question, but I failed.

Here is code about a little bit weird coin.

#include <stdio.h>

int main(){

    char coin;
    int r = rand();

    if ( ??? )
        coin = 'H';
    else
        coin = 'T';
    printf("%c\n", coin);

    return 0;
}
  1. If you flip this coin, you can see head with a probability of 25% and tail with a probability of 75%. You must fill if-statement above. You CANNOT use relational operators like ==, !=, <=, <, >=, >.
  2. Now you got another coin. You can see head with a probability of 3/8 and tail with a probability of 5/8. You must fill if statement. Now you CANNOT use logical operators like !, &&, || additionally.

r can have a value between 0 and RAND_MAX. Assume that RAND_MAX is given appropriately.

I could solve 1 easily, by writing !(r % 4). But I cannot get an idea to solve 2 completely. 2 can be solved easily if I use logical operators. There are many ways like:

  1. (r % 8) || ((r - 1) % 8) || ((r - 2) % 8)
  2. (r % 2) && !(r % 8)

But I cannot find a way to express the proper condition without any logical operators. Can anybody give me some hint?

Aucun commentaire:

Enregistrer un commentaire