Random#

Introduction#

The C++ Standard Library provide functions to generate pseudo-random numbers. These can be used in VEXcode IQ (2nd gen) for behaviors that require variability or chance.

Below is a list of available methods:

  • rand – Returns a random integer.

  • srand – Set the random seed.

Number Generators#

rand#

rand returns a random integer with no maximum.

Usage:
rand()

Parameter

Description

This method has no parameters.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display a random number
  Brain.Screen.print("%d", rand());
}

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display a random number between 0 and 100
  Brain.Screen.print("%d", rand() % 101);
}

To return a random integer within a specific range, use the pattern rand() % (max - min + 1) + min.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display a random number between 5 and 10
  Brain.Screen.print("%d", rand() % (10 - 5 + 1) + 5);
}

srand#

srand sets the starting value, seed, used by the pseudo-random number generator in the rand function.

Usage:
srand()

Parameter

Description

This method has no parameters.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Use the same seed for random number
  srand(1);
  Brain.Screen.print("%d", rand() % 100);
}