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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more