Skip to content

Commit c7ed0b1

Browse files
authored
Add Duplicate Character Counter in Pascal (TheRenegadeCoder#4830)
1 parent f1a2c41 commit c7ed0b1

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
program DuplicateCharacterCounter;
2+
3+
{$mode objfpc}{$H+}
4+
5+
uses
6+
Classes,
7+
Generics.Collections,
8+
SysUtils;
9+
10+
type
11+
TCountDictionary = specialize TDictionary<char, integer>;
12+
13+
procedure ShowUsage;
14+
begin
15+
Writeln('Usage: please provide a string');
16+
Halt(1);
17+
end;
18+
19+
function IsAlphanumeric(c: char): boolean;
20+
begin
21+
Result := CharInSet(c, ['0'..'9', 'A'..'Z', 'a'..'z']);
22+
end;
23+
24+
procedure CountDuplicates(const Str: string);
25+
var
26+
Counts: TCountDictionary;
27+
Outputted: TCountDictionary;
28+
Character: char;
29+
CurrentCount: integer;
30+
HasDuplicates: boolean;
31+
begin
32+
Counts := TCountDictionary.Create;
33+
Outputted := TCountDictionary.Create;
34+
try
35+
// Count all alphanumeric characters
36+
for Character in Str do
37+
if IsAlphanumeric(Character) then
38+
begin
39+
if not Counts.TryGetValue(Character, CurrentCount) then
40+
Counts.Add(Character, 1)
41+
else
42+
Counts[Character] := CurrentCount + 1;
43+
end;
44+
45+
HasDuplicates := False;
46+
47+
// Output duplicates in order of first appearance
48+
for Character in Str do
49+
if Counts.TryGetValue(Character, CurrentCount) and (CurrentCount > 1) and
50+
not Outputted.ContainsKey(Character) then
51+
begin
52+
Writeln(Character, ': ', CurrentCount);
53+
Outputted.Add(Character, 1);
54+
HasDuplicates := True;
55+
end;
56+
57+
if not HasDuplicates then
58+
Writeln('No duplicate characters');
59+
finally
60+
Counts.Free;
61+
Outputted.Free;
62+
end;
63+
end;
64+
65+
var
66+
InputStr: string;
67+
begin
68+
if ParamCount <> 1 then
69+
ShowUsage;
70+
71+
InputStr := Trim(ParamStr(1));
72+
if InputStr = '' then
73+
ShowUsage;
74+
75+
CountDuplicates(InputStr);
76+
end.
77+
78+

0 commit comments

Comments
 (0)