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.10Example 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.65Challenge 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!
Top comments (38)
Here's my attempt:
My attempt with comments:
Here is my attempt, did it in Go: Github
This executable boils down to:
Output:
Also, wooo first post on here 🎉
I'm impressed by how short many of the solutions are.
Clojure:
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:
You can see it working on this CodePen.
And as an extra, here is a version in which the checks are also sorted:
Here my contribution in javascript:
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. 😄
BASH
Here's my take (JavaScript). A few notes:
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.
Ruby
Output :
My JavaScript version:
Output: