hash.pas 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. const
  2. KEYLEN = 3;
  3. N = 5;
  4. M = 2*N;
  5. type
  6. tkey = string[KEYLEN];
  7. tval = string;
  8. ps = ^tval;
  9. pk = ^tkey;
  10. Const
  11. NotError : tval = 'Not in table';
  12. VAR
  13. Y : array [0..M-1] of ps;
  14. X : array [0..M-1] of pk;
  15. Function Hash(key : tkey):word;
  16. var
  17. i : byte;
  18. res : real;
  19. begin
  20. res := 0;
  21. for i := 1 to KEYLEN do res := res + ord(key[i]);
  22. res := Frac(sqrt(res));
  23. Hash := trunc(res * M);
  24. end;
  25. Procedure AddPair(key:tkey;val:tval);
  26. var
  27. nv : ps;
  28. nk : pk;
  29. c : 0..M-1;
  30. begin
  31. c := Hash(Key);
  32. while X[C] <> nil do c:=(c+1) mod M;
  33. New(nv);NV^ := val;
  34. New(nk);NK^ := key;
  35. X[C] := NK;
  36. Y[C] := NV;
  37. end;
  38. Function GetValue(key : tkey):tval;
  39. var
  40. c : 0..M-1;
  41. begin
  42. c := Hash(Key);
  43. while (X[C]^ <> Key) and (X[C] <> nil) do c:=(c+1) mod M;
  44. if X[C] <> nil then GetValue := Y[C]^
  45. else
  46. GetValue := NotError;
  47. end;
  48. var
  49. i : 0..M-1;
  50. begin
  51. for i := 0 to M-1 do begin X[i] := nil; y[i]:=nil;end;
  52. AddPair('SPB','Saint Petersburg');
  53. AddPair('MOS','Moscow');
  54. AddPair('_NY','New York');
  55. AddPair('TUA','Tula');
  56. AddPair('Sux','SuxxCity');
  57. WriteLn(GetValue('SPB'));
  58. WriteLn(GetValue('_NY'));
  59. WriteLn(GetValue('MOC'));
  60. WriteLn(GetValue('Sux'));
  61. end.