summaryrefslogtreecommitdiff
path: root/harmoneff/magicsort.pas
blob: 3d04bbedb061a2e15f75e1cb0e0f51560ba5a049 (plain)
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
program magicsort;

uses math;

var F:        Textfile;
    common,s: string;
    I,J,L:    Integer;
    lines:    array of string;
    nums:     array of integer;
    found:    boolean;

begin
 if Paramcount<>1 then
  begin
   Writeln('usage: '+Paramstr(0)+' imputfile > outputfile');
   halt;
  end;
 Assign(F,Paramstr(1));
 Reset(F);
 J:=0;
 if not eof(F) then
  begin
   readln(F,S);
   writeln(S);
  end; 
 while not eof(F) do
  begin
   readln(F,S);
   if S='' then continue;
   if J=0 then common:=s;
   inc(J);
   for I:=1 to min(length(common),length(S)) do
    if common[I]<>S[I] then
     begin
      delete(common,I,length(common)-I+1);
      break;
     end;
  end;
 Close(F);
 setlength(lines,J);
 setlength(nums,J);
 J:=0;
 Reset(F);
 if not eof(F) then
  readln(F,S);
 while not eof(F) do
  begin
   Readln(F,S);
   if S='' then continue;
   lines[J]:=S;
   nums[J]:=0;
   I:=length(common)+1;
   while (I<length(S)) and (S[I] in ['0'..'9']) do
    begin
     nums[J]:=nums[J]*10 + ord(S[I]) - ord('0');
     inc(I);
    end;
   inc(J);
  end;
 Close(F);
 L:=-1;
 repeat
  found:=false;
  J:=-1;
  For I:=0 to length(nums)-1 do
   if ((J=-1) or (nums[I]<nums[J]) or ((nums[I]=nums[J]) and (I<J))) and
      ((L=-1) or (nums[I]>nums[L]) or ((nums[I]=nums[L]) and (I>L))) then
    begin
     J:=I;
     found:=true;
    end;
  L:=J;
  if found then writeln(lines[J]);
 until not found; 
end.