Generating random numbers#

int rand(void);
#include <stdio.h>
#include <stdlib.h>
const size_t NUMBER_COUNT = 3;

int main() {
  printf("🎲  ");
  for (size_t i = 0; i < NUMBER_COUNT; ++i)
    printf("%d ", rand());
}
🎲  1804289383 846930886 1681692777 

Running the program again:

🎲  1804289383 846930886 1681692777 
πŸ€” Question to ponder

Would you call rand a random number generator?

pseudorandom number generator

an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers – also known as deterministic random bit generator. … is not truly random, because it is completely determined by an initial value, … called seed.

random seed

a number used to initialize a pseudorandom number generator

Activity 23 (Generating random numbers in an interval)

  1. Write code that generates five random numbers in the range [0, 4] and prints them.

  2. Do you think that this way of generating numbers is useful in our problem?

Generating a different sequence#

void srand(unsigned int seed);  // seed random number generator

From rand manual:

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

#include <stdio.h>
#include <stdlib.h>
const size_t NUMBER_COUNT = 3;

void generate_and_print_random_numbers() {
  printf("🎲  ");
  for (size_t i = 0; i < NUMBER_COUNT; ++i)
    printf("%d ", rand());
  puts("");
}

int main() {
  generate_and_print_random_numbers();

  srand(1);
  generate_and_print_random_numbers();

  srand(0);
  generate_and_print_random_numbers();

  srand(2);
  generate_and_print_random_numbers();
}
🎲  1804289383 846930886 1681692777 
🎲  1804289383 846930886 1681692777 
🎲  1804289383 846930886 1681692777 
🎲  1505335290 1738766719 190686788 

On my system, srand(0) and srand(1) have the same effect.

πŸ€” Question to ponder

Do you think that this way of generating numbers is useful in our problem? Why?

Generating a different sequence at each run#

Example using the time now as a seed.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const size_t NUMBER_COUNT = 3;

void generate_and_print_random_numbers() {
  printf("🎲  ");
  for (size_t i = 0; i < NUMBER_COUNT; ++i)
    printf("%d ", rand());
  puts("");
}

int main() {
  generate_and_print_random_numbers();

  srand(time(NULL));
  generate_and_print_random_numbers();
}
🎲  1804289383 846930886 1681692777 
🎲  1668393624 1215633736 1511416583 

Running the program again:

🎲  1804289383 846930886 1681692777 
🎲  142173631 277432175 458846131

Activity 24 (Generating random numbers in an interval for a game)

Modify your code from Activity 23 so that it is useful for our problem