0

I am not sure how to implement this, but here is the description:

  • Take a number as input in between the range 0-10 (0 always returning false, 10 always returning true)
  • Take the argument which was received as input, and pass into a function, determining at runtime whether the boolean value required will be true or false

Say for example:

Input number 7 -> (7 has a 70% chance of generating a true boolean value) -> pass into function, get the boolean value generated from the function.

This function will be run multiple times - perhaps over 1000 times.

Thanks for the help, I appreciate it.

James
  • 236
  • 5
  • 18

4 Answers4

4
bool func(int v) {
  float f = rand()*1.0f/RAND_MAX;
  float vv= v / 10.0f;
  return f < vv;
}
perreal
  • 94,503
  • 21
  • 155
  • 181
0

I would say generate a random number representing a percentage (say 1 to 100) then if the random number is less then or equal to the percentage chance mark it as true, else mark it as false.

MichelleJS
  • 759
  • 3
  • 16
  • 32
0

Here's an idea , I'm not sure that's it's gonna be helpful;

bool randomChoice(int number){
    int result =rand() % 10;
    return number>=result;

    }

Hope it's helpful

coolcoolcool
  • 381
  • 1
  • 6
  • 13
  • you've got some extra braces there. Also `if (number>=result) return true; else return false;` is a bit of an anti-pattern. Just `return (number>=result); ` Oh, and which `random()` function are you calling? The stdlib one doesn't take an argument http://linux.die.net/man/3/random – John Carter Jun 07 '13 at 22:34
  • 2
    Ack, **don't** call `srand` every time you call `rand`. Call it **once only**. – Pete Becker Jun 07 '13 at 23:20
  • 1
    Yeah, reseeding the random number to the current time on every call is a fantastic way to make your numbers not at all random. – John Carter Jun 08 '13 at 00:31
0

This is an interesting question! Here's what I think you should do, in pseudo code:

boolean[] booleans = new boolean[10]; //boolean array of length 10

function generateBooleans(){
    loop from i = 0 to 10:
        int r = random(10);    //random number between 0 and 9, inclusive
        if(r < i){
            booleans[i] = true;
        }
    }
}

You can then compare the user's input to your boolean array to get the pre-determined boolean value:

boolean isTrue = booleans[userInputNumber]
AndrewCox
  • 1,044
  • 7
  • 14