learn-cpp icon indicating copy to clipboard operation
learn-cpp copied to clipboard

Rock Paper Scissors Lizard Spock code simplification using graph theory.

Open JFichtl opened this issue 4 years ago • 0 comments

`/* This program will play rock, paper, scissors, lizard, spock with you */

#include

const char* int_to_pick(int a) { switch (a){ case 1: return "rock"; case 2: return "paper"; case 3: return "scissors"; case 4: return "spock"; case 5: return "lizard"; } }

int main(){ srand (time(NULL)); int computer = rand()%5 + 1; int user = 0; //string winner; // Live long and prosper 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! "; do { std::cin >> user; } while (user < 0 or user > 5); const char *user_pick = int_to_pick(user); const char *computer_pick = int_to_pick(computer); std::cout << "You pick " << user_pick; std::cout << "\n"; std::cout << "Computer picks " << computer_pick << "\n";

int compare = user - computer + 5; / * We can model this game using complete k-graphs with odd k. Every possible selection is a vertex in the 5-complete graph and we draw a directed edge connecting two vertices if v_1 wins against v_2 (or vice versa). We order the outer perimeter of the 5-complete graph so that we create a circuit where any vertex to the right of any given vertex v_o always wins against v_0. We connect the 'inner' vertices inside the pentagram so that there is always an unbroken circuit between any three vertices. If you fix v_0, you can always tell who the winner will be by looking at the directed distance between any vertex v_n. If the directed distance greater than zero and even, you've lost, if it's greater than zero and odd, you've won. A tie occurs when the distance becomes 0. Note that the directed distance is measured by moving only in the directions assigned to the edges. Since every vertex in a k-complete graph with odd k has even degree, there is an equal chance of winning or losing against the remaining options. Graphs with even k's will have vertices with odd degree, which means that there will be at least one vertex that has a greater chance of winning than the rest. */ if (compare%5 == 0) { std::cout << "It's a tie!\n"; } else if ((compare%5 +1)%2 == 0) { std::cout << user_pick << " beats " << computer_pick << "\n"; std::cout << "You win!\n"; } else if ((compare%5)%2 == 0) { std::cout << "The computer wins!\n"; std::cout << computer_pick << " beats " << user_pick << "\n"; } return 0; }`

JFichtl avatar Aug 15 '21 20:08 JFichtl