Author Topic: Optimizing some array operations  (Read 714 times)

0 Members and 1 Guest are viewing this topic.

Offline Polifen

  • Soldier
  • **
  • Posts: 127
Optimizing some array operations
« on: February 18, 2011, 01:21:26 pm »
Code: [Select]
procedure ShowPCaps(ID : byte; Text : string; show : boolean);
var
i, j, index, count, cID : integer;
file, cNick : string;
maps, uniq : array of string;
capped : boolean;
begin
count := def_count;
if Length(Text) <> 0 then
if Text[1] <> ' ' then begin
if (RegExpMatch('[0-9]+ (.)*', Text) = true) or (RegExpMatch('[0-9]+', Text) = true) then count := StrToInt(GetPiece(Text, ' ', 0));
end;
if count > 15 then count := 15
else if count < 0 then count := 0;
for i := 1 to Length(Text) do begin
if Text[1] <> ' ' then Delete(Text, 1, 1)
else break;
end;
Delete(Text, 1, 1);

cID := 0;
cNick := '';

try
cID := StrToint(Text);
except
cNick := Text;
end;

if cID <> 0 then begin
cID := StrToInt(Text);
cNick := GetPlayerStat(cID, 'Name');
end
else if cNick <> '' then begin
cNick := Text;
cID := ID;
end
else begin
cNick := GetPlayerStat(ID, 'Name');
cID := ID;
end;

if show = true then ID := 0;

if GetPlayerStat(cID, 'Active') = true then begin
if FileExists('stats/players/' + filterFilename(cNick) + '.txt') then begin
file := ReadFile('stats/players/' + filterFilename(cNick) + '.txt');
maps := Explode(file, chr(13) + chr(10));
if count <> 0 then begin
WriteConsole(ID, cNick + '''s last ' + IntToStr(count) + ' caps: ', Color);
for i := ArrayHigh(maps) - 1 downto ArrayHigh(maps) - count  do begin
if i < 0 then break;
WriteConsole(ID, 'Cap number ' + IntToStr(i + 1) + ' is ' + maps[i], Color);
end;
WriteConsole(ID, '', Color);
end;

capped := false;
index := 1;
SetArrayLength(uniq, index + 1);
for i := 0 to ArrayHigh(maps) do begin
if maps[i] = CurrentMap then capped := true;
for j := i to ArrayHigh(maps) do begin
if j = ArrayHigh(maps) then begin
uniq[index] := maps[i];
index := index + 1;
SetArrayLength(uniq, index + 1);
break;
end;;
if i <> j then begin
if maps[i] = maps[j] then break;
end;
end;
end;

WriteConsole(ID, cNick + ' has ' + IntToStr(ArrayHigh(maps)) + ' cap(s) including ' + IntToStr(ArrayHigh(uniq) - 2) + ' unique map(s)', Color);
if capped = false then WriteConsole(ID, cNick + '''s not capped ' + CurrentMap, Color)
else WriteConsole(ID, cNick + '''s already capped ' + CurrentMap, Color)
end
else WriteConsole(ID, cNick + ' has no caps', Color);
end
else WriteConsole(ID, 'There is no player with that ID on the server', Color);
end;

Hey, does anyone have an idea how to optimise it a bit? I guess the problem is the unique caps search loop. It worked fine till a player got more than 250 caps, now the server is freezing for a sec when someone checks this player's stats.