generate random value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momogi
    New Member
    • Sep 2007
    • 28

    generate random value

    I'm making a TSP (Travelling Salesman Problem) project in Simulated Annealing Method.
    Here, I need to add a condition to the generated random value.
    I wanna ask you, how to generate two random value in which the first random value must bigger than the second one. random1>random2

    here the code I have :
    Code:
    for (int i=1;i<=2;i++)
     printf("%d\n", rand());
    thanks....
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by momogi
    I'm making a TSP (Travelling Salesman Problem) project in Simulated Annealing Method.
    Here, I need to add a condition to the generated random value.
    I wanna ask you, how to generate two random value in which the first random value must bigger than the second one. random1>random2

    here the code I have :
    Code:
    for (int i=1;i<=2;i++)
     printf("%d\n", rand());
    thanks....
    Random means you cant guarantee that the second value will be greater than the first one.
    What you can do is you can call rand in loop till you can get the second one greater than second.

    Raghuram

    Comment

    • mac11
      Contributor
      • Apr 2007
      • 256

      #3
      Alternatively, you can simplify things greatly like this:

      Code:
      // grab two random numbers, you don't care what they are
      random1 = get_me_a_random_number();  // get a random number
      random2 = get_me_a_random_number();  // get another random number
      
      // then see if random2 is greater than random1, if the second one is
      // greater than the first one just swap em so they appear to have come in the
      // order you want
      if( random2 > random1 )  
      {
          // random2 is greater than random1 - swap 'em so random1 is bigger
          swap( random2, random1 );
      }
      
      // now we know random1 is bigger (or they might be the same I guess)
      printf( %d is greater than or equal to %d\n", random1, random2 );
      They are both random numbers, you just use a little logic to figure out which one is greater and you don't have to sit in a loop waiting.

      I guess if you want to make absolutely sure they aren't equal (which is very unlikely) you will need a loop, but it won't actually loop very often.
      Last edited by mac11; Mar 3 '08, 03:28 PM. Reason: add comments

      Comment

      • gpraghuram
        Recognized Expert Top Contributor
        • Mar 2007
        • 1275

        #4
        Very good idea.
        I went for a approach which is not very efficient

        Raghuram

        Comment

        Working...