DEV Community

loading...

Discussion on: Daily Challenge #4 - Checkbook Balancing

Collapse
peter279k profile image
peter279k

Here is my simple solution to parse balanced book string:

function balance($book) {
    $result = "Original Balance: ";
    $book = explode("\n", $book);
    if ($book[0] === "") {
      $totalDistance = sprintf("%.2f\n", (float)$book[1]);
      $index = 2;
    } else {
      $totalDistance = sprintf("%.2f\n", (float)$book[0]);
      $index = 1;
    }
    $result .= $totalDistance;

    $totalExpense = 0.0;
    $currentDistance = (float)$totalDistance;
    $currentCount = 0;
    for(; $index < count($book); $index++) {
      if ($book[$index] === "") {
        continue;
      }
      $currentCount += 1;
      $info = explode(' ', $book[$index]);
      $stringFormat = "%s %s %.2f Balance %.2f\n";
      preg_match('/(\w+)/', $info[1], $matched);
      $info[1] = $matched[0];

      preg_match('/(\d+).(\d+)/', $info[2], $matched);
      $info[2] = (float)$matched[0];
      $currentDistance = $currentDistance - $info[2];
      $result .= sprintf($stringFormat, $info[0], $info[1], (float)$info[2], (float)$currentDistance);
      $totalExpense += (float)$info[2];
    }

    $result .= sprintf("Total expense  %.2f\n", $totalExpense);
    $result .= sprintf("Average expense  %.2f", (string)round($totalExpense / $currentCount, 2));

    return $result;
}