-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest_and_smallest_unit.pas
More file actions
104 lines (92 loc) · 2.01 KB
/
closest_and_smallest_unit.pas
File metadata and controls
104 lines (92 loc) · 2.01 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
{
5 kyu
Closest and Smallest
https://www.codewars.com/kata/5868b2de442e3fb2bb000119
}
unit closest_and_smallest_unit;
{$mode objfpc}{$H+}
interface
type
TClosestSmallestArray = array of array[0..2] of int64;
function Closest(strng: string): TClosestSmallestArray;
implementation
uses
Generics.Collections,
Generics.Defaults,
StrUtils,
SysUtils,
Types;
type
TNuminfo = record
number: int64;
position: int64;
weight: int64;
end;
TNuminfoList = specialize TList<TNuminfo>;
TNuminfoComparer = specialize TComparer<TNuminfo>;
function CompareNuminfo(constref L, R: TNuminfo): integer;
begin
{ weight ascending }
if L.weight < R.weight then
Result := -1
else if L.weight > R.weight then
Result := 1
else
begin
{ if equal: position ascending }
if L.position < R.position then
Result := -1
else if L.position > R.position then
Result := 1
else
Result := 0;
end;
end;
function DigitSum(num: int64): int64;
begin
Result := 0;
while (num <> 0) do
begin
Result := Result + (num mod 10);
num := num div 10;
end;
end;
function Closest(strng: string): TClosestSmallestArray;
var
nums: TStringDynArray;
list: TNuminfoList;
temp: TNuminfo;
i, j, diff, diffmin: int64;
begin
if strng = '' then
Exit([]);
nums := SplitString(strng, ' ');
list := TNuminfoList.Create;
for i := Low(nums) to High(nums) do
begin
temp.position := i;
temp.number := StrToInt(nums[i]);
temp.weight := DigitSum(temp.number);
list.Add(temp);
end;
list.Sort(TNuminfoComparer.Construct(@CompareNuminfo));
diffmin := High(int64);
for i := 0 to list.Count - 2 do
begin
diff := list.Items[i + 1].weight - list.Items[i].weight;
if diff < diffmin then
begin
diffmin := diff;
j := i;
end;
end;
SetLength(Result, 2);
for i := 0 to 1 do
begin
Result[i][0] := list.Items[j + i].weight;
Result[i][1] := list.Items[j + i].position;
Result[i][2] := list.Items[j + i].number;
end;
list.Free;
end;
end.