Thread: srand and Random number generator

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    8

    Question srand and Random number generator

    I am trying to generate 7 random number that doesn't repeat and print them out sorted and unsorted. I am having 1 error that
    i can't seem to fix. can anyone please help me. i am running out of time.

    Code:
    /* Aim: Write a C program to sort array of random numbers using bubble sort and rand() function */
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    
    // generate_random() function to generate array of random numbers
    void generate_random(int *a, int n)
    {
      {
        int main();
    
        int i, n, j;
        time_t t;
    
        n = 7;
    
        /* Intializes random number generator */
        srand((unsigned) time(&t));
    
        /* Print 5 random numbers from 0 to 50 */
        for (i = 0; i < n; i++) {
    
          printf("%d\n", rand() % 16);
        }
      }
      int j, temp, i;
      // Passing starting address and size to generate array of random numbers
      generate_random(a, n);
      // Displaying the random array
      printf("\n The random array: ");
      for (i = 0; i < n; i++)
        printf(" %d ", a);
    
      for (i = 1; i < n; i++) {
        for (j = 0; j < n - i; j++) {
          /* To sort in ascending order, change '<' to '>' to implement descending order sorting */
          if (a[j + 1] < a[j]) {
            temp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = temp;
          }
        }
      }
    
      // Displaying the sorted array.
      printf("\n The sorted array: ");
      for (i = 0; i < n; i++)
        printf(" %d ", a);
      printf("\n \n");
    }
    Last edited by Salem; 10-04-2019 at 11:59 AM. Reason: Removed crayola

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well your generate_random and main are all mushed together.

    It's
    Code:
    void generate_random ( int *a, int n ) {
         // some code goes here
    }
    
    int main ( ) {
        // main code goes here
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    How can I fix it, I need to use srand and the generated numbers should be a list of 7 numbers.

    Thanks for your help

  4. #4
    Guest
    Guest
    Quote Originally Posted by TKapeuasha View Post
    How can I fix it
    He just told you, and you already have the code. So what's the hold up? If you didn't write this code and didn't pay attention in class, then we're not going to do your homework.

  5. #5
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    Quote Originally Posted by Guest View Post
    He just told you, and you already have the code. So what's the hold up? If you didn't write this code and didn't pay attention in class, then we're not going to do your homework.
    perhaps i should have posted my code, the one that, i did not modify to include srand. my problem is my random generator is giving me the same numbers. all i need for you guys to help me with is, show me how to use the srand with this code. the way i am using it is not working, i do not know why.

    Code:
    /* Aim: Write a C program to sort array of random numbers using bubble sort and rand() function */
    
    #include<stdio.h>
    #include<stdlib.h>
    
    // generate_random() function to generate array of random numbers
    
    void generate_random(int *a, int n)
    {
      int i;
      n = 7;
      srand(time(NULL));
    
      for (i = 0; i < n; i++)
        a = rand() % (16 + 1 - 1) + 1;
    
    }
    
    int main()
    {
      int a[16], n, i, j, temp;
      n = 7;
    
    
      // Passing starting address and size to generate array of random numbers
      generate_random(a, n);
    
      // Displaying the random array
    
      printf("\n The draw result: ");
      for (i = 0; i < n; i++)
        printf(" %d ", a);
    
    
      for (i = 1; i < n; i++) {
        for (j = 0; j < n - i; j++) {
          /* To sort in ascending order, change '<' to '>' to implement descending order sorting */
          if (a[j + 1] < a[j]) {
            temp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = temp;
          }
        }
      }
    
    
      // Displaying the sorted array.
    
      printf("\n The sorted draw: ");
      for (i = 0; i < n; i++)
        printf(" %d ", a);
      printf("\n \n");
    
    }
    Last edited by Salem; 10-05-2019 at 07:33 AM. Reason: Removed crayola

  6. #6
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    i used
    Code:
    srand (time(0));
    for(i=0; i<7; i++)
    a(i)=rand()%16)
    however i still has repeating numbers sometimes. they said srand should get ride of repeating numbers, thats my dilemma

  7. #7
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Move the srand() function call to main, and ONLY call it once. That will eliminate the problem with the same number being generated by rand().

  8. #8
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    Quote Originally Posted by rstanley View Post
    Move the srand() function call to main, and ONLY call it once. That will eliminate the problem with the same number being generated by rand().
    thank you

  9. #9
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Another thing... If you toss a D6 dice, let's say, 20 times, you CAN get the same number in a "long" sequence... For the sake of argument, imagine tossing the dice and getting 3, four times, one after another...

    "Ramdomness" doesn't mean "unsequential", it only means the values you get are distributed equally in an unpredictable sequence (which CAN be "sequential").

    That said, the LCPRNG (Linear Congruential Pseudo Random Number Generator), used by srand/rand is less random if you take a few lower bits than if you get a few upper bits (see Knuth)... When you do:
    Code:
     r = rand() % 16;
    You are keeping the lower 4 bits and masking all the upper bits. To make sure the value is more "random", you can do (with GCC and CLANG), for the same 4 bits:
    Code:
    int randmax_bits = sizeof(int)*8 - __builtin_clz(RAND_MAX);
    int r = (unsigned int)rand() >> (randmax_bits - 4);
    Notice rand() returns an int, by definition.
    Last edited by flp1969; 10-05-2019 at 09:03 AM.

  10. #10
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    thank you. i am now having problem merging two source code. they are working separately. i am actually doing that assignment attached.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #define maxsize 100
     
    // generate_random() function to generate array of random numbers
     
    void generate_random(int *array, int n)
    {
     
      int i;
     
      int randmax_bits = sizeof(int)*8 - __builtin_clz(RAND_MAX);
    int r = (unsigned int)rand() >> (randmax_bits - 4);
      for(i=0;i<7;i++)
      array[i]=rand()%(16+1-1)+1;
     
    }
     
    int main()
     
    {
      int a[16],n,i,j,temp, x, y;
      n = 7;
     
     
    // Passing starting address and size to generate array of random numbers
      generate_random(a,n); 
     
    // Displaying the random array
     
      printf("\n The draw result: ");
      for(i=0;i<n;i++)
        printf(" %d ",a[i]);
     
     
      for(i=1;i<n;i++)
      {
        for(j=0;j<n-i;j++)
        {
    /* To sort in ascending order, change '<' to '>' to implement descending order sorting */
          if(a[j+1]<a[j]) 
          {
            temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp; 
          }
        }
      }
     
     
    // Displaying the sorted array.
     
      printf("\n The sorted draw: ");
      for(i=0;i<n;i++)
      printf(" %d ",a[i]);
      printf("\n \n");
    }
     
    
    
    
    int array (16);
        printf("Please enter the 7 Ticket number one by one followed by enter \n");
        for (x = 0; x < 7; x++)
        {
            scanf("%d", &array[x]);
        }
        printf("The Ticket number's are \n");
        for (x = 0; x < 7; x++)
        {
            printf("%d \n", array[x]);
        }
        /*   Bubble sorting begins */
        for (x = 0; x < 7; x++)
        {
            for (y = 0; y < (7 - x - 1); y++)
            {
                if (array[y] > array[y + 1])
                {
                    temp = array[y];
                    array[y] = array[y + 1];
                    array[y + 1] = temp;
                }
            }
        }
        printf("The sorted Ticket number's are...\n");
        for (x = 0; x < 7; x++)
        {
            printf("%d\n", array[x]);
        }
    }
    Attached Images Attached Images
    Last edited by TKapeuasha; 10-05-2019 at 10:49 AM.

  11. #11
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    You got it all wrong...

  12. #12
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    Quote Originally Posted by flp1969 View Post
    You got it all wrong...

    What do you mean?

  13. #13
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,787
    Are you just copy/pasting from random sources?

    Edit: as an aside, you may want to check your naming of the sorting algorithm you're using (well, algorithms, because you seem to be implementing two variants for some reason, neither of which are called "bubble sort" using Knuth's definition)
    Last edited by Hodor; 10-06-2019 at 06:55 PM.

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Question 4:
    (30 marks)
    This problem contains loops, sorting arrays, random generation, and variable matching.
    Include an analysis (data requirements) and algorithm in your reply.
    Write a “lottery engine” program to simulate drawing lottery numbers. You will draw 7 numbers,
    randomly selected from 1 to 16.

    a) Allow the user to enter their own selection of numbers first,
    Example numbers: 2 3 7 9 10 11 15
    b) then run your “lottery engine” to select the “winning numbers”. Numbers are drawn
    randomly.
    Use the clock as the seed value for your random function (Hint: use “srand(clock());” ).
    c) Be sure to remove duplicate entries.
    d) Print out the draw result as it was generated (unsorted), then sort the array and print out the
    sorted numbers.
    Example output:

    Draw unsorted: 2 12 16 14 7 13 1
    Draw sorted: 1 2 7 12 13 14 16

    e) Then print out the matching numbers selected by the user:
    f) Also print the sorted user selection and draw results and matching numbers to a TXT file
    called “Results.txt”.
    Example output

    Draw sorted: 1 2 7 12 13 14 16
    User’s sorted: 2 3 7 9 10 11 15
    Matching numbers: 2 – 7
    END
    Your first cut of C code should look like this.
    It's basically all the bullet points of your assignment written as comments.
    Code:
    int main ( ) {
        // a) Allow the user to enter their own selection of numbers first,
        // b) then run your “lottery engine” to select the “winning numbers”. Numbers are drawn randomly.
        // c) Be sure to remove duplicate entries.
        // d) Print out the draw result as it was generated (unsorted), then sort the array and print out the sorted numbers.
        // e) Then print out the matching numbers selected by the user:
        // f) Also print the sorted user selection and draw results and matching numbers to a TXT file
    }
    Your second cut maybe like this.
    You tackle each comment IN TURN.
    Do ONE thing at a time, compile and test it.
    Code:
    void inputUserGuesses(int *userLotteryGuesses, int nGuesses ) {
        printf("Enter your %d guesses\n",nGuesses);
        for ( int i = 0 ; i < nGuesses ; i++ ) {
            scanf("%d",&userLotteryGuesses[i]);
        }
    }
    int main ( ) {
        int userLotteryGuesses[7];
        // a) Allow the user to enter their own selection of numbers first,
        inputUserGuesses(userLotteryGuesses,7);
        // b) then run your “lottery engine” to select the “winning numbers”. Numbers are drawn randomly.
        // c) Be sure to remove duplicate entries.
        // d) Print out the draw result as it was generated (unsorted), then sort the array and print out the sorted numbers.
        // e) Then print out the matching numbers selected by the user:
        // f) Also print the sorted user selection and draw results and matching numbers to a TXT file
    }
    Now, write a function for step b that fills another array[7] (and pick a decent name for it) with pseudo random numbers.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #15
    Registered User
    Join Date
    Oct 2019
    Posts
    8
    <p>
    I gave up already without trying finding a complete solution that works. The problem is too complex for 30 marks. It&#39;s supposed to be at least 50 or more. We didn&#39;t do any problem that combined all those together, hence my approach was, first to write a program that will accept user numbers, then I went to the random generator.</p>
    <p>
    &nbsp;</p>
    <p>
    The code aree written separate, which proved to a problem when I wanted to combine them. To make matter worse, I didn&#39;t know how to search the array to find the marching numbers. Any suggestions of a good book, to study on my own? I submitted today, I know I will fail the assignment, however I want to learn from my mistakes..</p>
    <p>
    &nbsp;</p>
    <p>
    Thanks to all that supported me, with your comments. If I may ask, can someone really make a living out of coding c# only or you need to know other language? For those who knows python, how easy is it for me to learn that language after c#? I really have a soft spot for machine learning and python is extensively used in that field.</p>
    Last edited by TKapeuasha; 10-07-2019 at 02:08 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Random Number Generator Stuck on 1 Number?
    By Dollydaydream in forum C++ Programming
    Replies: 3
    Last Post: 11-26-2013, 08:43 AM
  2. Help With Random Number Generator
    By anonymoususer in forum C Programming
    Replies: 1
    Last Post: 11-08-2011, 12:02 PM
  3. need a random number generator thats not compleatly random
    By thedodgeruk in forum C++ Programming
    Replies: 1
    Last Post: 06-05-2011, 06:48 AM
  4. Random number with srand()
    By DanteXP in forum C++ Programming
    Replies: 7
    Last Post: 12-17-2010, 03:46 AM
  5. Random number generator/srand
    By Dave.b in forum C Programming
    Replies: 10
    Last Post: 12-01-2010, 12:39 AM

Tags for this Thread