-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheasy_balance_checking_unit.pas
More file actions
69 lines (60 loc) · 1.55 KB
/
easy_balance_checking_unit.pas
File metadata and controls
69 lines (60 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
{
6 kyu
Easy Balance Checking
https://www.codewars.com/kata/59d727d40e8c9dd2dd00009f
}
unit easy_balance_checking_unit;
{$mode objfpc}{$H+}
interface
function Balance(book: string): string;
implementation
uses
SysUtils,
StrUtils,
RegExpr;
type
TStrArray = array of string;
function Balance(book: string): string;
var
Lines, cols: TStrArray;
i: integer;
bal, start, Value: double;
Count: integer;
begin
Result := '';
Lines := SplitString(book, '\n');
Count := 0;
for i := 0 to High(Lines) do
begin
Lines[i] := Trim(Lines[i]);
if Length(Lines[i]) > 0 then
Lines[i] := ReplaceRegExpr('[^. a-zA-Z0-9]', Lines[i], '');
if Length(Lines[i]) > 0 then
Lines[i] := ReplaceRegExpr('[ ]{2,}', Lines[i], ' ');
Lines[i] := Trim(Lines[i]);
if Length(Lines[i]) > 0 then
begin
cols := SplitString(Lines[i], ' ');
if i = 0 then
begin
bal := StrToFloat(cols[0]);
start := bal;
Result := Result + 'Original Balance: ' + Format('%f', [start]) + '\n';
end
else
begin
Inc(Count);
Value := StrToFloat(cols[2]);
bal := bal - Value;
Result := Result + cols[0] + ' ' + cols[1] + ' ' + Format('%f', [Value]) +
' Balance ' + Format('%f', [bal]) + '\n';
end;
end;
end;
Result := Result + 'Total expense ' + Format('%f', [start - bal]) + '\n';
if Count = 0 then
Result := Result + 'Average expense ' + Format('%f', [0.00])
else
Result := Result + 'Average expense ' + Format('%f', [(start - bal) / Count]);
end;
end.