Thread: rand() to choose?

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    7

    rand() to choose?

    If I have a function like select(int a, int b, int c) how can I use the rand() to select a, b or c and then return that value? ie.. if a=30, b=40 and c=50 how can i use rand() to just pick b and return 40 back out? And then the next time i call the function, if c=45 use rand() to pick c that time and return 45?

    So, in other words, I only need rand() to randomly pick either a, b or c and then return it. I know that the faq shows how to use rand to generate an actual value but thats not what I need for this. Thanks for any help.

  2. #2
    www.entropysink.com
    Join Date
    Feb 2002
    Posts
    603
    Generate a random number between 1 & 3, and then use a select case to select the relevant function based on the value.

    (Alternatively, use a GOTO [J/K Prelude]).
    Visit entropysink.com - It's what your PC is made for!

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    24
    Sone thing like this will work but to get a more random number you should really use a time seed "srand(time()0;" under the stdlib.h and time.h headers

    .code

    int select(int a, int b, int c)
    {
    int temp=rand()%3+1;
    if(temp==1)
    return a;
    if(temp==2)
    return b;
    if(temp==3)
    return c;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  2. HELP!!!!emergency ~expert please help
    By unknowppl in forum C Programming
    Replies: 1
    Last Post: 08-19-2008, 07:35 AM
  3. Probablity algorithm for N choose M in C or C++
    By kappajacko in forum C++ Programming
    Replies: 2
    Last Post: 09-20-2007, 04:19 PM
  4. Replies: 5
    Last Post: 06-06-2007, 11:10 PM
  5. N Choose R
    By .ZG. in forum C Programming
    Replies: 7
    Last Post: 05-18-2004, 02:43 AM