I've written a simple PHP script which checks if a random value is a valid Rugby Union score. It works quite nicely but isn't particularly efficient, any advice on improving it would be most welcome.
$score = rand(0, 60);
/* Rugby Union
*
* Try = 5 points
* Conversion = 2 points
* Penalty = 3 points
* Drop goal = 3 points
*
*/
echo "<h1>Score: ".$score."</h1>";
for ($tries = 0; $tries <= 12; $tries++)
{
for ($conversions = 0; $conversions <= 30; $conversions++)
{
for ($dropgoals = 0; $dropgoals <= 20; $dropgoals++)
{
if ($conversions > $tries)
{
//echo "<br />Illegal score";
}
else
{
$testscore = ($tries * 5) + ($conversions * 2) + ($dropgoals * 3);
if ($testscore == $score)
{
if ($dropgoals == 0)
{
echo "Found a way to achieve score with ".$tries." tries ".$conversions." conversions and ".$dropgoals." drop goals.<br />";
}
else
{
echo "Found a way to achieve score with ".$tries." tries ".$conversions." conversions and ".$dropgoals." drop goals or penalties.<br />";
}
}
}
}
}
}
Okay, here's the revised solution as it stands, it'd be nice to reduce the amount of nested for loops if possible...
echo "<h1>Score: ".$score."</h1>";
for ($tries = 0; $tries <= 12; $tries++) {
for ($conversions = 0; $conversions <= $tries; $conversions++) {
for ($dropgoals = 0; $dropgoals <= 20; $dropgoals++){
if ($conversions <= $tries) {
$testscore = ($tries * 5) + ($conversions * 2) + ($dropgoals * 3);
if ($testscore == $score) {
echo "Found a way to achieve score with ".$tries." tries ".$conversions." conversions and ".$dropgoals.($dropgoals == 0 ? " drop goals.<br />" : " drop goals or penalties.<br />");
}
}
}
}
}