susanBuck / e2-fall22

0 stars 0 forks source link

Solving Rock Paper Scissors using a math formula #36

Closed susanBuck closed 1 year ago

susanBuck commented 1 year ago

I was working with a student and we were talking about how to determine the winner of Rock Paper Scissors using a mathematical formula. I thought the rest of the class might be interested in this as well, so below is the code. Also, hat tip to classmate @duyvhh who used a math approach to RPS in their projects.

<?php

# Solving RPS using a math formula
# Original source: https://therenegadecoder.com/code/rock-paper-scissors-using-modular-arithmetic/

$playerA = rand(0, 2);
$playerB = rand(0, 2);

if ($playerA == $playerB) {
    $winner = 'Tie';
} elseif (($playerA + 1) % 3 == $playerB) {
    $winner = 'Player B';
} else {
    $winner = 'Player A';
}