Thread: looping two random Values until they are the same, then stop:

  1. #1
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499

    looping two random Values until they are the same, then stop:

    I am looping two variables then when they are equal I want to see the number. I am output both variables because I want to confirm they are equal.
    Is this counter productive because I am using the same time on the same computer? In other words, will they always be equal?

    The code runs and stops. I play with it for a little while and thought I would seek some direction.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define NUMBER 6 
    int main(int argc, const char * argv[])
    {
    
        int randValue;
        int randValue2;
        int i;
        
        
        srand(time(NULL));
        
        while (randValue!=randValue2) {
            
            for (i=0; i < NUMBER; i++) {
                randValue= 1 + (int)rand() % 49;
            }
            
            for (i=0; i < NUMBER; i++) {
                randValue2= 1 + (int)rand() % 49;
            }
            
            printf("%d%d",randValue,randValue2);
        }
        
        
        return 0;
    }
    Last edited by jocdrew21; 08-20-2013 at 12:33 PM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by jocdrew21 View Post
    Is this counter productive because I am using the same time on the same computer? In other words, will they always be equal?

    The code runs and stops. I play with it for a little while and thought I would seek some direction.
    What did the output tell you? Are they always the same, or did your loop run several times, printing two different random numbers each iteration (except the last)?

    srand just sets the seed, i.e. the starting point for the PRNG algorithm to generate it's numbers from. Every call to rand() after that returns a new random number. One thing about random number sequences (true or pseudo) that newbies often miss, is that numbers are allowed to repeat. You can have a sequence like 13, 4, 79, 16, 16, ...

    Code:
    for (i=0; i < NUMBER; i++) {
        ...
    }
    Those for loops are pointless, you generate 6 random numbers, but throw away the first 5, since only the sixth value is stored in randValue at the end of the loop.
    Code:
    randValue2= 1 + (int)rand() % 49;
    That generates random values in the range of [1, 49]. You will not get 50, if that was your intention. x % N will give you a value between [0, N-1], so rand() % 49 will give you a value between [0, 48]. Adding 1 to that gives you a value in the range [1, 49]. For simple random numbers in a given range of [low, high], I use the following:
    Code:
    rand_range(int low, int high)
    {
        return (rand() % (high - low + 1)) + low;
    }
    So to get the same numbers you're getting now, [1, 49], you would call rand_range(1, 49). If you wanted to include 50, call rand_range(1, 50).

    Code:
    printf("%d%d",randValue,randValue2);
    Put some bloody space between your values. How would you know if output of 125 was 12 and 5 or 1 and 25?

  3. #3
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    It just runs and stops now. I took your advice about rand, not really how I was used to doing it but it did look neater. I added an if statement in hopes that would work but it didn't. I looked at the what it was outputting and both were random when I rand to 2 and the other to 1. See the comments on line 19. I did have them both using Macros with the format you mentioned but it didn't look right to me. Was I wrong in assuming so?

    My understanding is that it should loop until randValue is not equal to randValue2 and if they are equal print out the values.

    Thanks for noticing the spaces, I always do that and don't normally fix it until I see it's output.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #define HIGH 50
    #define LOW 1
    
    #define NUMBER 6 
    int main(int argc, const char * argv[])
    {
    
        int randValue;
        int randValue2;
    
        srand(time(NULL));
        
        
        while(randValue!=randValue2) {
    
            randValue2 =(rand() % (HIGH-LOW + 2)) + LOW;// this is always 32, if I change it to two, it's now random //
            
            randValue=1 + (int)rand()%50;
        
            if (randValue==randValue2) {
            
            printf("%d %d",randValue,randValue2);
        }
        }
        return 0;
    }

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    You should pay attention to your compiler
    Code:
    1>test.c(17): warning C4700: uninitialized local variable 'randValue' used
    1>test.c(17): warning C4700: uninitialized local variable 'randValue2' used
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Tweaking master Aslaville's Avatar
    Join Date
    Sep 2012
    Location
    Rogueport
    Posts
    528
    Before entering the while loop initialize the values randValue and randValue2.

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by jocdrew21 View Post
    Code:
            randValue2 =(rand() % (HIGH-LOW + 2)) + LOW;// this is always 32, if I change it to two, it's now random //
    Wrong. It cannot always produce the same number over and over when you have a +1 there, yet somehow no longer produce the same number over and over when you have a +2 there.
    If you believe that comment then you are mistaken, it cannot have such an effect.

    Change it back to + LOW as it should be, and make the line below use the same calculation.
    Then you'd perhaps best read Prelude's page about hashing the time to generate the random seed.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    I did it and the same thing happened, which is nothing. This is weird, and even weirder my compiler normally reminds me about initializing values and sometimes even tries to do it for me. Guess I should rely on it in the first place.

    I keep staring at this code and wondering why its failing.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define HIGH 50
    #define LOW 1
    
    int main(int argc, const char * argv[])
    {
        int randValue = 0;
        int randValue2= 0;
       
        srand(time(NULL));
        
        while (randValue!=randValue2){
        
            randValue= 1 + (int)rand() % 50;
            randValue2= (rand() %(HIGH-LOW+2))+LOW;
        
        if (randValue==randValue2) {
            printf("%d %d",randValue,randValue2);
        }
        }
        return 0;
        
    }

  8. #8
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You've initialised randValue and randValue2 to the same value (i.e. they're equal). The loop is while they are not equal .... which is never.

    Feel foolish now? Happens to everyone sometime.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Why it should not? when you first get to line 15 the condition is false and loop never executes
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #10
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Try changing the while loop to a do while loop. This will eliminate the uninitialized variables.

    Code:
    /* ... */
        do{
    /* ... */
            randValue = ... 
    /* ... */
            randValue2 = ... 
        }
        while (randValue != randValue2);
    Note that rand()'s seed is stored in a thread structure. If you want to have independent seeds, you'll need to write your own rand() functions. For example:

    Code:
    static int seed1 = 1;
    static int seed2 = 1;
    
    int rand1(void){
        return(( (seed1 = seed1 * 214013L + 2531011L) >> 16) & 0x7fff );
    }
    
    int rand2(void){
        return(( (seed2 = seed2 * 214013L + 2531011L) >> 16) & 0x7fff );
    }

  11. #11
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by rcgldr View Post
    Note that rand()'s seed is stored in a thread structure.
    This is not necessarily true. It might be true with some compilers/libraries but not with others.

    Your sample functions would actually generate two identical sequences (call #n of your rand1() would produce the same value as call #n of rand2(), for any n).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  12. #12
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by grumpy View Post
    This is not necessarily true. It might be true with some compilers/libraries but not with others.
    Yes, I forgot to mention this applied to microsoft compilers and windows. I'm not sure if other compilers / operating systems keep a separate seed for each thread of a task.
    Quote Originally Posted by grumpy View Post
    Your sample functions would actually generate two identical sequences (call #n of your rand1() would produce the same value as call #n of rand2(), for any n).
    That was the point. The seed values would need to be set differently to end up starting at a different points in each sequence. Then there is the possibility that since the sequence cycle is the same, once the seeds start off differently, getting equal values after performing some modulo operation may never occur. To avoid this issue, two different algorithms could be used. Wiki articles:

    Linear congruential generator - Wikipedia, the free encyclopedia

    Xorshift - Wikipedia, the free encyclopedia

  13. #13
    Registered User
    Join Date
    Dec 2012
    Posts
    307
    i have used this example in a 5 rolling dice game, and it does gen the same numbers now and again!

    Code:
    #include <stdlib.h>
    #include <time.h>
    int main ()
     {
      srand ( time(NULL) );
      int random_number = rand()%10;
      int random_number2 = rand()%10;
      printf("%i\n",random_number);
      printf("%i\n",random_number2);
      return 0;
     }

    edit: Btw this does 0-9

  14. #14
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    Got it doing just what I wanted, thank you. I had it working once I initialized the two to different number. I felt a bit silly @grumpy. However I decided to go with the do statement in the end because I never really use them.

    I used a for loop because I wanted it done a few times. Next I was thinking about sending the information to a txt file 100 times and pulling the top 10 modes from the txt file. I'll start playing with that tonight.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    #define HIGH 49
    #define LOW 1
    
    int main(int argc, const char * argv[])
    {
        static int randValue = 1;
        static int randValue2= 0;
        int j=0;
        
        srand(time(NULL));
        
        for (j=0; j<6; j++) {    // loops 6 times resulting in the while loop producing 6 numbers
                                // that were produced at the sametime
        do{
            randValue= (rand() %(HIGH-LOW+1))+LOW;   
            randValue2= (rand() %(HIGH-LOW+1))+LOW;
        }
            
        while (randValue!=randValue2);
        
                if (randValue==randValue2) {
                    printf("%d   %d\n",randValue,randValue2);
        }
        }
        return 0;
    }

  15. #15
    Registered User
    Join Date
    Jul 2013
    Location
    Germany
    Posts
    499
    I know how to pass a char to a file but now I am passing a int and calling a function from another function. I want to have the random numbers sent to a txt file. I will tackle the later quest after.

    Code:
     #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
    
    #define HIGH 49
    #define LOW 1
    
    int random_generated()
    {
        static int randValue = 1;
        static int randValue2= 0;
        int j=0;
        
        srand(time(NULL));
        
        for (j=0; j<6; j++) {       // loops 6 times resulting in the while loop producing 6 numbers
                                    // that were produced at the sametime
            do{
                randValue= (rand() %(HIGH-LOW+1))+LOW;          //generates random values
                randValue2= (rand() %(HIGH-LOW+1))+LOW;         //generates random values
            }
            
            while (randValue!=randValue2);
            
            if (randValue==randValue2) {
                printf("%d   %d\n",randValue,randValue2);
            }
        }
         
    }
    
    void datafile()
    {
        char file_name[81];
        char *p;
        int string = 0;   
        FILE *fp;
        
        printf("Enter a file name:");
        fgets(file_name,sizeof(file_name),stdin);
        p=strchr(file_name, '\n');
        if ((p)) {
            *p='\0';
        }
        
        fp =fopen(file_name,"w");
        if(fp==NULL)
        {
            printf("The file was not successfully opened\n");
            printf("Please check if the file exists\n");
            exit(1);
        }
        string = random_generated();
        
       // here I want to call the outher function "random_generated" and put it into the file
        
        //fclose(fp);
    }
    
    int main(int argc, const char * argv[])
    {
        datafile();
        
        random_generated();
        
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need help with looping lowest priority values first
    By spendotw in forum C Programming
    Replies: 21
    Last Post: 01-18-2012, 03:36 PM
  2. how to stop the looping?
    By justin8077 in forum C Programming
    Replies: 12
    Last Post: 03-31-2011, 10:35 AM
  3. Int Array - Stop taking values at [zero]
    By bunko in forum C Programming
    Replies: 3
    Last Post: 12-04-2008, 12:54 AM
  4. My menu program won't stop looping
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 01-26-2002, 04:30 PM
  5. My program won't stop looping
    By davie_scotland in forum C Programming
    Replies: 7
    Last Post: 01-18-2002, 02:34 PM