DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #4 - Checkbook Balancing

Good morning, everyone.

Don’t say I didn’t warn you, we’re moving from letters to numbers with this challenge.

Today’s challenge comes from user @g964 on CodeWars.

You are given a small checkbook to balance that is given to you as a string. Sometimes, this checkbook will be cluttered by non-alphanumeric characters.

The first line shows the original balance. Each other (not blank) line gives information: check number, category, and check amount.

You need to clean the lines first, keeping only letters, digits, dots, and spaces. Next, return the report as a string. On each line of the report, you have to add the new balance. In the last two lines, return the total expenses and average expense. Round your results to two decimal places.

Example Checkbook

1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10

Example Solution

Original_Balance: 1000.00
125 Market 125.45 Balance 874.55
126 Hardware 34.95 Balance 839.60
127 Video 7.45 Balance 832.15
128 Book 14.32 Balance 817.83
129 Gasoline 16.10 Balance 801.73
Total expense 198.27
Average expense 39.65

Challenge Checkbook

1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;

Good luck and happy coding!


Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Oldest comments (37)

Collapse
 
flrnd profile image
Florian Rand

(There is a small typo, it's BSD-2 license, FreeBSD is the OS ;).

Collapse
 
devencourt profile image
Brian Bethencourt

Thanks for spotting it, we'll get it fixed.

Collapse
 
zerquix18 profile image
I'm Luis! \^-^/

Here's my attempt:

const checkbook = `
1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;
`.trim()

const round = value => Math.round(value * 100) / 100

const cleanedCheckBook = checkbook.replace(/[^A-Za-z0-9\s\.]/gmi, '')
const lines = cleanedCheckBook.split("\n")
const originalBalance = parseFloat(lines.shift())

let totalExpenses = 0
const expenses = []

const linesProcessed = lines.map(line => {
  const [number, category, expense] = line.split(' ')
  const expenseFloat = parseFloat(expense)
  totalExpenses += expenseFloat
  expenses.push(expenseFloat)

  const currentBalance = originalBalance - totalExpenses

  return `${number} ${category} ${round(expense)} Balance ${round(currentBalance)}`
}).join("\n")

const averageSpent = expenses.reduce((total, sum) => total + sum) / expenses.length

console.log(`
Original_Balance: ${round(originalBalance)}
${linesProcessed}
Total Expenses: ${round(totalExpenses)}
Average spent: ${round(averageSpent)}
`)

My attempt with comments:

const checkbook = `
1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;
`.trim() // this will remove spaces, tabs, and breaklines \n at the beginning and end

// Math.round doesn't round to X number of digits so I'm using this hacky method
const round = value => Math.round(value * 100) / 100
// skip all non A-Za-z0-9\s\. caracters, globally, multiline, and case insensitive
const cleanedCheckBook = checkbook.replace(/[^A-Za-z0-9\s\.]/gmi, '')
// make an array where every element is a line
const lines = cleanedCheckBook.split("\n")
// extract the first element and save the value in float
const originalBalance = parseFloat(lines.shift())

let totalExpenses = 0
const expenses = [] // for the average

// go thru each line and change it
const linesProcessed = lines.map(line => {
  const [number, category, expense] = line.split(' ')
  const expenseFloat = parseFloat(expense)

  totalExpenses += expenseFloat
  expenses.push(expenseFloat)

  const currentBalance = originalBalance - totalExpenses

  return `${number} ${category} ${round(expense)} Balance ${round(currentBalance)}`
}).join("\n")

const averageSpent = expenses.reduce((total, sum) => total + sum) / expenses.length

console.log(`
Original_Balance: ${round(originalBalance)}
${linesProcessed}
Total Expenses: ${round(totalExpenses)}
Average spent: ${round(averageSpent)}
`)
Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

JavaScript

This is going to be one of those "don't do this at home" types of code (or maybe "do it at home but not at work"). I tried to do it as a single chain of commands, assuming that the string is going to be valid. It can be further cleaned and reduced, I'll try later.

Here is the code commented step-by-step:

const generateReport = checkbook => {
  let current = 0;
                   // use regular expressions to remove unwanted characters
  return checkbook.replace(/[^0-9a-z\. \n]/gi, "")
                   // separate the string into an array splitting by new line
                  .split("\n")
                   // update each value to include the total at the end
                  .map((val, index) => {
                    current = index === 0 ? val : (current - val.split(" ")[2]).toFixed(2);
                    return index === 0 ? "Original Balance: " + val : val + ` ${current}`;
                  })
                   // convert array into string again
                  .join("\n")
                   // concatenate the total and average
                  .concat(`\nTotal expense: ${(checkbook.split("\n")[0] - current).toFixed(2)}`)
                  .concat(`\nAverage expense: ${((checkbook.split("\n")[0] - current)/(checkbook.split("\n").length-1) || 0).toFixed(2)}`);
}

You can see it working on this CodePen.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

And as an extra, here is a version in which the checks are also sorted:

const generateReport = checkbook => {
  let current = 0;
  return checkbook.replace(/[^0-9a-z\. \n]/gi, "")
                  .split("\n")
                  .sort((a,b) => {
                    const arrA = a.split(" ");
                    const arrB = b.split(" ");
                    if (arrA.length > arrB.length) {
                      return 1;
                    } else if (arrB.length > arrA.length) {
                      return -1;
                    } else {
                      return parseInt(arrA[0]) > parseInt(arrB[0]) ? 1 : -1;
                    }
                  })
                  .map((val, index) => {
                    current = index === 0 ? val : (current - val.split(" ")[2]).toFixed(2);
                    return index === 0 ? "Original Balance: " + val : val + ` ${current}`;
                  })
                  .join("\n")
                  .concat(`\nTotal expense: ${(checkbook.split("\n")[0] - current).toFixed(2)}`)
                  .concat(`\nAverage expense: ${((checkbook.split("\n")[0] - current)/(checkbook.split("\n").length-1) || 0).toFixed(2)}`);
}
Collapse
 
kerrishotts profile image
Kerri Shotts

Here's my take (JavaScript). A few notes:

  • I sort by line #, and then by category
  • The first line might actually be blank, so I trim the input
  • Categories are assumed to be single words (no spaces allowed)
  • Output includes digit grouping by current locale
  • Full code (incl some basic tests): gist.github.com/kerrishotts/461a90...

const sanitize = str => str.replace(/[^0-9A-Za-z\.\s]/g, "");

const notBlank = str => str !== "";

const extract = str => {
    const [ line, category, expense ] = str.split(/\s+/);
    return { line: Number(line), category, expense: Number(expense) };
};

const byLineAndCategory = (a, b) => a.line < b.line 
    ? -1 : a.line > b.line 
        ? 1 : a.category < b.category 
            ? -1 : a.category > b.category 
                ? 1 : 0;

const balanceReducer = (
    {openingBalance, totalExpenses, entries}, 
    {line, category, expense}
) => {
    const newTotal = totalExpenses + expense;
    const newBalance = openingBalance - newTotal;
    return {
        openingBalance,
        totalExpenses: newTotal,
        averageExpense: newTotal / (entries.length + 1),
        entries: [ ...entries, {line, category, expense, balance: newBalance }]
    }
};

const round2 = n => (Math.round(n * 100) / 100)
    .toLocaleString(undefined, {
        style: "decimal",
        minimumFractionDigits: 2,
        useGrouping: true
    });

const balanceCheckbook = (checkbook) => {
    const [openingBalanceStr, ...entries] = 
        sanitize(checkbook)
        .trim()
        .split("\n")
        .filter(notBlank);

    const openingBalance = Number(openingBalanceStr);

    const initialState = { 
            openingBalance, 
            entries: [], 
            averageExpense: 0, 
            totalExpenses: 0
    };

    const report = 
        entries
        .map(extract)
        .sort(byLineAndCategory)
        .reduce( balanceReducer, initialState );

    return `
Original Balance: ${round2(report.openingBalance)}
${report.entries.map(({line, category, expense, balance}) =>
`${line} ${category} ${round2(expense)} Balance ${round2(balance)}`
).join("\n")}
Total Expenses: ${round2(report.totalExpenses)}
Average Expense: ${round2(report.averageExpense)}
`.trim();
};

Enter fullscreen mode Exit fullscreen mode
Collapse
 
zerquix18 profile image
I'm Luis! \^-^/

I think is the most scalable solution since you first move all the data to a manipulable format, deal with it and then output it.

Collapse
 
martyhimmel profile image
Martin Himmel • Edited

PHP

It wasn't specified, but I sorted the check order. Also noticed that checks 123 and 129 are repeated two and three times, respectively, while 126, 128, and 131 are missing. I'm guessing the duplicate number were supposed to be the missing numbers. 😄

$text = '1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;';

function checkbook_report(string $str) {
    $data = format_checkbook_string($str);
    $balance = floatval(array_shift($data));
    $output = 'Original Balance: ' . number_format($balance, 2) . PHP_EOL;
    $expenses = [];

    sort($data);

    foreach ($data as $index => $line) {
        $parts = explode(' ', $line);
        // handles multi-word categories (even though they don't exist in this challenge)
        foreach ($parts as $line_segment) {
            if ($line_segment != end($parts)) {
                $output .= "$line_segment ";
            }
        }
        $expenses[] = floatval(end($parts));
        $balance -= end($expenses);
        $output .= number_format(end($parts), 2) . ', Balance: ' . number_format($balance, 2) . PHP_EOL;
    }

    $total_expenses = array_sum($expenses);
    $output .= 'Total expenses: ' . number_format($total_expenses, 2) . PHP_EOL;
    $output .= 'Average expense: ' . number_format($total_expenses / count($expenses), 2) . PHP_EOL;
    return $output;
}

function format_checkbook_string(string $str) {
    $data = explode(PHP_EOL, $str);
    return array_map('filter_line', $data);
}

function filter_line(string $line) {
    return preg_replace('/[^\w\s.]+/', '', $line);
}

echo checkbook_report($text);
Collapse
 
coreyja profile image
Corey Alexander

Walking through the requirements now while I'm on the train so I can get rolling on this tonight!

I see some people are sorting the checkbook before doing the balances by check number.
I am NOT going to do this, because I'm not confident the check number order is necessarily the order the checks were used / were processed by the bank. Therefore I think it might be more correct to keep the ordering of the given list!

Collapse
 
coreyja profile image
Corey Alexander • Edited

Here is my Rust Version!

#[macro_use]
extern crate lazy_static;

use regex::Regex;

#[derive(Debug)]
struct Transaction {
    check_number: String, // This is just an identifier to me. Who am I to stop your UUID check number
    category: String,
    amount: f32,
}

impl Transaction {
    fn from_line(line: &str) -> Self {
        lazy_static! {
            static ref STRIP_REGEX: Regex = Regex::new(r"[^\w \.]").unwrap();
            static ref PARSE_REGEX: Regex = Regex::new(r"(\d+) (.+) (\d*\.\d*)").unwrap();
        }

        let stripped_line: String = STRIP_REGEX.replace_all(line, "").to_string();

        println!("{}", stripped_line);
        let captures = PARSE_REGEX.captures(&stripped_line).unwrap();

        Self {
            check_number: captures.get(1).unwrap().as_str().to_owned(),
            category: captures.get(2).unwrap().as_str().to_owned(),
            amount: captures.get(3).unwrap().as_str().parse().unwrap(),
        }
    }

    fn to_string(&self) -> String {
        format!("{} {} {:.2}", self.check_number, self.category, self.amount)
    }
}

pub fn process_checkbook_string(input: &str) -> String {
    let mut lines = input.lines();
    let starting_balance: f32 = lines.next().unwrap().parse().unwrap();

    let transactions = lines.map(Transaction::from_line);

    let mut current_balance = starting_balance;
    let mut total_expense = 0.;
    let mut transaction_count = 0;
    let mut transaction_strings: Vec<String> = transactions
        .map(|transaction| {
            current_balance -= transaction.amount;
            total_expense += transaction.amount;
            transaction_count += 1;
            format!("{} Balance {:.2}", transaction.to_string(), current_balance)
        })
        .collect();

    let starting_balance_string = format!("Original_Balance: {:.2}", starting_balance);
    let total_expense_string = format!("Total expense {:.2}", total_expense);
    let avg_expense_string = format!(
        "Average expense {:.2}",
        total_expense / transaction_count as f32
    );

    let mut output = vec![starting_balance_string];
    output.append(&mut transaction_strings);
    output.push(total_expense_string);
    output.push(avg_expense_string);
    output.join("\n")
}

#[cfg(test)]
mod tests {
    use crate::*;

    const EXAMPLE_INPUT: &str = "1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10";

    const EXAMPLE_OUTPUT: &str = "Original_Balance: 1000.00
125 Market 125.45 Balance 874.55
126 Hardware 34.95 Balance 839.60
127 Video 7.45 Balance 832.15
128 Book 14.32 Balance 817.83
129 Gasoline 16.10 Balance 801.73
Total expense 198.27
Average expense 39.65";

    const CHALLENGE_INPUT: &str = "1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;";

    const CHALLENGE_OUTPUT: &str = "Original_Balance: 1233.00
125 Hardware 24.80 Balance 1208.20
123 Flowers 93.50 Balance 1114.70
127 Meat 120.90 Balance 993.80
120 Picture 34.00 Balance 959.80
124 Gasoline 11.00 Balance 948.80
123 Photos 71.40 Balance 877.40
122 Picture 93.50 Balance 783.90
132 Tires 19.00 Balance 764.90
129 Stamps 13.60 Balance 751.30
129 Fruits 17.60 Balance 733.70
129 Market 128.00 Balance 605.70
121 Gasoline 13.60 Balance 592.10
Total expense 640.90
Average expense 53.41";

    #[test]
    fn it_works_for_the_example() {
        assert_eq!(EXAMPLE_OUTPUT, process_checkbook_string(EXAMPLE_INPUT));
    }

    #[test]
    fn it_works_for_the_challenge() {
        assert_eq!(CHALLENGE_OUTPUT, process_checkbook_string(CHALLENGE_INPUT));
    }
}

It's not quite as well factored as I'd like, and it definitely doesn't account for nearly as many edge cases as it should but it works!

Collapse
 
ryansmith profile image
Ryan Smith

My JavaScript version:

/**
 * Given a string containing checkbook transactions, format the transactions and calculate the running total
 */
function balanceCheckbook (checkbook) {
  let balance = 0
  let totalExpense = 0
  let balancedCheckbook = ''

  // Split the string into an array of transactions based on new lines.
  const transactions = checkbook.split('\n')

  // Loop over the transactions to construct the checkbook and calculate total expense.
  transactions.forEach((transaction) => {
    const sanitizedTransaction = sanitizeInput(transaction).split(' ')

    // If this transaction only has one column, set it to be the starting balance. Otherwise, process a transaction.
    if (sanitizedTransaction.length === 1) {
      balance = sanitizedTransaction
      balancedCheckbook += `Original_Balance: ${sanitizedTransaction} \n`
    } else {
      const transactionNumber = sanitizedTransaction[0]
      const description = sanitizedTransaction[1]
      const cost = sanitizedTransaction[2]
      const newBalance = (balance -= cost).toFixed(2)

      totalExpense += parseFloat(cost)

      // Format the transaction into a string.
      balancedCheckbook += `${transactionNumber} ${description} ${cost} Balance ${newBalance} \n`
    }
  })

  balancedCheckbook += `Total expense ${totalExpense.toFixed(2)} \n`
  balancedCheckbook += `Average expense ${(totalExpense / (transactions.length - 1)).toFixed(2)}`

  return balancedCheckbook
}

/**
 * Remove invalid characters from a transaction.
 */
function sanitizeInput (inputText) {
  const removeSpecialCharactersRegex = /[^A-Z0-9\s.]/gi

  return inputText.trim().replace(removeSpecialCharactersRegex, '')
}
console.log(
  balanceCheckbook(
    `1233.00
    125 Hardware;! 24.8?;
    123 Flowers 93.5
    127 Meat 120.90
    120 Picture 34.00
    124 Gasoline 11.00
    123 Photos;! 71.4?;
    122 Picture 93.5
    132 Tires;! 19.00,?;
    129 Stamps 13.6
    129 Fruits{} 17.6
    129 Market;! 128.00?;
    121 Gasoline;! 13.6?;`
  )
)

Output:

Original_Balance: 1233.00 
125 Hardware 24.8 Balance 1208.20 
123 Flowers 93.5 Balance 1114.70 
127 Meat 120.90 Balance 993.80 
120 Picture 34.00 Balance 959.80 
124 Gasoline 11.00 Balance 948.80 
123 Photos 71.4 Balance 877.40 
122 Picture 93.5 Balance 783.90 
132 Tires 19.00 Balance 764.90 
129 Stamps 13.6 Balance 751.30 
129 Fruits 17.6 Balance 733.70 
129 Market 128.00 Balance 605.70 
121 Gasoline 13.6 Balance 592.10 
Total expense 640.90 
Average expense 53.41
Collapse
 
dak425 profile image
Donald Feury • Edited

Here is my attempt, did it in Go: Github

This executable boils down to:

package main

import (
    "fmt"

    "github.com/Dak425/dev-to-challenge-4-go/pkg/checkbook/memory"
)

func main() {
    raw := `1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;`

    cb := memory.NewInMemoryCheckBook(raw)

    fmt.Print(cb.FullReport())
}

Output:

Starting Balance: 1233.00
[1] -> Check Number: 125, Category: Hardware, Amount: 24.80, Remaining Balance: 1208.20
[2] -> Check Number: 123, Category: Flowers, Amount: 93.50, Remaining Balance: 1114.70
[3] -> Check Number: 127, Category: Meat, Amount: 120.90, Remaining Balance: 993.80
[4] -> Check Number: 120, Category: Picture, Amount: 34.00, Remaining Balance: 959.80
[5] -> Check Number: 124, Category: Gasoline, Amount: 11.00, Remaining Balance: 948.80
[6] -> Check Number: 123, Category: Photos, Amount: 71.40, Remaining Balance: 877.40
[7] -> Check Number: 122, Category: Picture, Amount: 93.50, Remaining Balance: 783.90
[8] -> Check Number: 132, Category: Tires, Amount: 19.00, Remaining Balance: 764.90
[9] -> Check Number: 129, Category: Stamps, Amount: 13.60, Remaining Balance: 751.30
[10] -> Check Number: 129, Category: Fruits, Amount: 17.60, Remaining Balance: 733.70
[11] -> Check Number: 129, Category: Market, Amount: 128.00, Remaining Balance: 605.70
[12] -> Check Number: 121, Category: Gasoline, Amount: 13.60, Remaining Balance: 592.10
Total Costs: 640.90
Average Cost: 53.41

Also, wooo first post on here 🎉

Collapse
 
jaloplo profile image
Jaime López

Here my contribution in javascript:

const input = `1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;`;

// clean the input
let balanceInputs = input
  .split('\n')
  .map(x => x.split(' ')
  .filter(x => x.trim() !== ''));

// process input to create an object with all information
function processData(balance, ...inputs) {
  const data = {
    original : parseFloat(balance[0]),
    totalExpense: 0.0,
    averageExpense: 0.0
  };

  const orders = inputs.map(i => {
    const order = {
      id: parseInt(i[0]),
      concept: i[1].match(/[0-9a-zA-Z.\s]/g).reduce((acc, current) => acc.concat(current)),
      value: parseFloat(i[2]),
      balance: data.original - data.totalExpense - parseFloat(i[2])
    };
    data.totalExpense += order.value;
    return order;
  });

  data.averageExpense = data.totalExpense / orders.length;

  return {
    data: data,
    orders: orders
  }
}

// shows data in the console as a report
function createReport(report) {
  console.log('Original_Balance: ' + report.data.original.toFixed(fixed));
  report.orders.forEach(function(order) {
    console.log(order.id + ' ' + order.concept + ' ' + order.value.toFixed(fixed) + ' Balance ' + order.balance.toFixed(fixed));
  });
  console.log('Total expense ' + report.data.totalExpense.toFixed(fixed));
  console.log('Average expense ' + report.data.averageExpense.toFixed(fixed));
}


const fixed = 2; // set the number of decimal places
const data = processData(...balanceInputs); // process data
createReport(data); // shows the report
Collapse
 
johncip profile image
jmc • Edited

I'm impressed by how short many of the solutions are.

Clojure:

(ns checkbook
  (:require [clojure.string :refer [join split]]))

;; split line into tokenized "entry"
(defn tokens [line]
  (map read-string (re-seq #"(?:\w|\.)+" line)))

;; append running balance onto entries
(defn with-running-balance [[start & entries]]
  (reduce
    (fn [acc entry]
      (let [prev-bal  (last (last acc))
            cur-bal   (- prev-bal (last entry))
            new-entry (conj (vec entry) "Balance" cur-bal)]
        (conj acc new-entry)))
    [["Original_Balance" (last start)]]
    entries))

;; output entry as string, with numbers rounded
(defn format-entry [xs]
  (case (count xs)
    2 (apply format "%s %.2f" xs)
    5 (apply format "%s %s %.2f %s %.2f" xs)))

;; append running balance, include total & average, format nums
(defn balance [s]
  (let [lines   (split s #"\n")
        entries (map tokens lines)
        $$      (map last (rest entries))]
    (join "\n"
      (map format-entry
        (conj (with-running-balance entries)
              ["Total expense" (apply + $$)]
              ["Average expense" (/ (apply + $$) (count $$))])))))