What Math Actually Buys You: Optimizing a Rock-Paper-Scissors Game in C
I was looking through my old projects and found a couple of Rock-Paper-Scissors games I wrote in C a few years back. Why more than one? Because programming is fun, but also because I was experimenting. We're going to look at both versions and talk about how math actually shows up in code. This will not be some generic "you should know math" lecture, but a before/after comparison grounded in my…
In the pursuit of understanding the practical applications of mathematics in programming, I delved into my archived C projects, specifically two Rock-Paper-Scissors games I had written years ago. The objective was to compare these implementations, focusing on the role of mathematical concepts in the code.
The first iteration, a naive version, demonstrated a critical instance where mathematical principles, albeit inadvertently, guided the code's functionality. The main function initiated by seeding the random number generator with the current time, generating a random integer between 1 and 3 (representing Rock, Paper, Scissors), and entering a loop until one of the players reached 3 points.
The loop condition, however, contained an error - the variable 'option' was declared but not initialized before being checked. This resulted in undefined behavior due to the reading of a garbage value, which in this case, almost invariably wouldn't equal 1, 2, or 3. Therefore, the loop commenced as intended, although this was pure luck rather than a robust design.
The heart of the game's decision-making process resided in the 'check_rules' function, which used a switch statement to determine the winner based on the player's and computer's options. The function carefully handled each possible scenario, returning 0 if the game was a tie, 1 if the player won, and -1 if the computer won.
This example served to underscore the point that while programming provides the flexibility to creatively solve problems, the knowledge base is the fuel that powers this creativity. In this case, the mathematical underpinnings of the switch statement provided a precise method to express the game's rules, enabling clear reasoning and decision-making in the code.
The full source code of both versions is publicly available on GitHub for further exploration.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.