Here's a different language from the usual to enjoy! This algorithm is O(n)
where n is the length of the input.
with Ada.Text_IO, Ada.Strings.Unbounded.Text_IO, Ada.Strings.Unbounded;
use Ada.Text_IO, Ada.Strings.Unbounded.Text_IO, Ada.Strings.Unbounded;
procedure Top5 is
type Pair_Type is
record
Key : Unbounded_String;
Count : Natural := 0;
end record;
N_Top : constant := 5;
N_Top_With_Sentinel : constant := N_Top + 1;
Top : array(1 .. N_Top_With_Sentinel) of Pair_Type;
I : Natural;
Input : Unbounded_String;
Tmp : Pair_Type;
begin
while not End_Of_File loop
Get_Line(Input);
I := Top'First;
while I <= N_Top loop
exit when Top(I).Key = Input;
I := I + 1;
end loop;
Tmp.Count := Top(I).Count + 1;
Tmp.Key := Input;
while I > Top'First and then Tmp.Count > Top(I - 1).Count loop
Top(I) := Top(I - 1);
I := I - 1;
end loop;
Top(I) := Tmp;
Top(N_Top_With_Sentinel) := (others => <>);
end loop;
for I in Top'Range loop
exit when Top(I).Count = 0;
Put_Line(Top(I).Key & Natural'Image(Top(I).Count));
end loop;
end Top5;
===
C:\>top5
a
b
c
f
a
d
e
f
b
f
f
^Z
f 4
a 2
b 2
c 1
d 1
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.