Rock paper scissors lizard spock

Hi can anyone explain this piece of code below:

srand (time(NULL));

int computer = rand() % 3 + 1;

int user = 0;

I know that overall we use it for the computer to generate a random number, but I’m having trouble understanding this part why is it rand() % 3 + 1

  int computer = rand() % 3 + 1;
1 Like

Have you checked the documentation:

are some good examples as well as an explanation:

A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range.

1 Like

hey @pyninja21220 this is great. i’m going to go back in and add more description in the course. this is in the Rock Paper Scissors Lizard Spock project, right?

also, here’s a livestream where i go over this:

hope that helps!

(and five more modules coming after new years, so stay tuned :slight_smile: )

yes this is the rock paper lizard Spock project!

srand (time(NULL)) generates a random number; any number at all. int computer = rand () % 3 +1 assigns the random value to the computer for the rock-paper-scissors game. the modulus (%) gives the remainder of long division. in this case modulus any number will give a remainder of that number minus one, in this case it will output 0,1 or 2. we add one because we want the computer to have a value of 1,2 or 3 in this case. hope the mumbo jumbo helps

Many thanks! (Post must be at least 20 character)

Hey @sonnynomnom - thanks for the livestream link. In the first part of the Rock, paper, scissors, spock section, the YouTube video to start us off isn’t available, saying that it is private.