# 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:

http://www.cplusplus.com/reference/cstdlib/rand/

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: https://www.youtube.com/watch?v=puMne8pqmxw

hope that helps!

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

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.

Thanks,

Dave

This code works fine.
Please review and point out mistakes in this code if there are any.

#include

#include <stdlib.h>

int main()

{

srand (time(NULL)) ;

int computer = std::rand() % 5 + 1 ;

std::cout << computer << " \n";

int user = 0 ;

std::cout << “====================\n”;

std::cout << “rock paper scissors lizard spock!\n”;

std::cout << “====================\n”;

std::cout << “1) \n”;

std::cout << “2) \n”;

std::cout << “3) \n”;

std::cout << “4) \n”;

std::cout << “5) \n”;

std::cout << "shoot! ";

std::cin >> user ;

if(user == computer)

{

``````std::cout << "Tied\n";
``````

}

else if(user == 1 && computer == 2||user == 2 && computer == 3||user == 3 && computer == 1||user == 1 && computer == 5||user == 2 && computer == 4||user == 3 && computer == 5)

{

``````std::cout << "Computer won \n";
``````

}

else

{

``````std::cout << "User won \n";
``````

}

return 0;

}