DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Efficient PHP Script for Calculating Scores in a Baseball Game (code practice recuiter)

Have you ever wondered how to efficiently calculate scores in a baseball game using PHP? Look no further! In this post, we'll delve into a well-optimized PHP script that effectively processes a sequence of baseball game operations and delivers accurate results.

<?php
$ops = ["5", "-2", "4", "C", "D", "9", "+", "+"];
$results = [];

foreach ($ops as $op) {

    if (is_numeric($op)) {
        // If the current operation is a number, add it to the results array
        $results[] = $op;
    } elseif ($op == "+") {
        // If the current operation is '+', calculate the sum of the last two scores and add the result to the array
        $score = end($results) + $results[count($results) - 2];
        $results[] = $score;
    } elseif ($op == "D") {
        // If the current operation is 'D', double the last score and add the result to the array
        $score = end($results) * 2;
        $results[] = $score;
    } elseif ($op == "C") {
        // If the current operation is 'C', remove the last score from the array
        array_pop($results);
    }
}

// Calculate the sum of all scores in the results array and echo the result
echo array_sum($results);
?>

Enter fullscreen mode Exit fullscreen mode

Operations Array: $ops = ["5", "-2", "4", "C", "D", "9", "+", "+"]; - Defines an array of operations (numbers, '+', 'D', 'C').

Results Array: $results = []; - Initializes an empty array to store the scores.

Main Loop: foreach ($ops as $op) { ... } - Iterates through each operation in the $ops array.

Handling Numeric Values: if (is_numeric($op)) { ... } - If the current operation is a number, add it to the $results array.

Handling '+' Operation: elseif ($op == "+") { ... } - If the current operation is '+', calculate the sum of the last two scores and add the result to the $results array.

Handling 'D' Operation: elseif ($op == "D") { ... } - If the current operation is 'D', double the last score and add the result to the $results array.

Handling 'C' Operation: elseif ($op == "C") { ... } - If the current operation is 'C', remove the last score from the $results array.

Calculate and Echo Sum: echo array_sum($results); - Calculates the sum of all scores in the $results array and echoes the result.

Top comments (0)