Learning C++ for beginner

Build a Rock Scissor Paper with C++

Stone Paper Scissor or Rock Paper Scissor is a game that is played between two people, each player in this game forms one of three shapes. The winner will be decided as per the given rules:

Rock vs Scissor -> Rock wins
Rock vs Paper -> Paper wins
Paper vs Scissor -> Scissor wins

First version:

  • Take 2 string inputs among (R, P, S)
  • Declare getWinner function that take 2 args first choice and second choice, compare the combination and return 0 if it’s a tie 1 if first choice wins 2 if second choice wins
  • Output the result

Second version

  • Take 1 user input
  • Declare randomnizeChoice that will return among R, P, S as the computer choice
  • Compare the combination and output the result
  • Make main runs as a loop until user input Q to quit

What do I learn

  1. Randomize function
#include <cstdlib>
#include <ctime>

## Seed generator
std::srand(static_cast<unsigned int>(std::time(nullptr)));

int randNum = std::rand() % MAX; // if I want to randomize between 0 and MAX-1

int randomNumber = min + (std::rand() % (max - min + 1)); if I want to randomize between MIN and MAX

  1. I/O loop
while (true) {
 std::string userChoice;
 std::cout << "Enter your play (R, P, or S) or Q to quit: ";
 std::cin >> userChoice;
 
 // Convert to uppercase to make input case-insensitive
 std::transform(userChoice.begin(), userChoice.end(), userChoice.begin(), ::toupper);
 
 if (userChoice == "Q") {
   break;
 }
 
 if (userChoice != "R" && userChoice != "P" && userChoice != "S") {
   std::cout << "Invalid input. Please enter R, P, S, or Q.\n";
   continue;
 }
}

DSA

Valid palindrome (Hint: two pointers)

pseudo code

  • sanitize the string to include only alphabets and numerics /^[a-zA-Z0-9]+$/, convert to lowercase
  • set pointer 1 to left and pointer 2 to right of the above list
  • while pointer 1 is smaller than pointer 2, check the char at these 2 pointers if they are the same
  • if increase pointer 1 and decrease pointer 2
  • if not return false
  • finally return true
bool isPalindrome(string s) {
 int l=0; r=s.length()-1;
 while (l<r) {
  while (l<r && !isalnum(s[l]) { l++; }
  while (l<r && !isalnum(s[l]) { r--; }
  if (tolower(s[l]) != tolower(s[r])) {return false;}
  l++;
  r--;
 }
 return true;
}
Jasmine Nguyen