HASH.BAK 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 := sqrt(res);
  23. res := res - trunc(res);
  24. Hash := trunc(res * M);
  25. end;
  26. Procedure AddPair(key:tkey;val:tval);
  27. var
  28. nv : ps;
  29. nk : pk;
  30. c : 0..M-1;
  31. begin
  32. c := Hash(Key);
  33. while X[C] <> nil do c:=(c+1) mod M;
  34. New(nv);NV^ := val;
  35. New(nk);NK^ := key;
  36. X[C] := NK;
  37. Y[C] := NV;
  38. end;
  39. Function GetValue(key : tkey):tval;
  40. var
  41. c : 0..M-1;
  42. begin
  43. c := Hash(Key);
  44. while (X[C]^ <> Key) and (X[C] <> nil) do c:=(c+1) mod M;
  45. if X[C] <> nil then GetValue := Y[C]^
  46. else
  47. GetValue := NotError;
  48. end;
  49. var
  50. i : 0..M-1;
  51. begin
  52. for i := 0 to M-1 do begin X[i] := nil; y[i]:=nil;end;
  53. AddPair('SPB','Saint Petersburg');
  54. AddPair('MOS','Moscow');
  55. AddPair('_NY','New York');
  56. AddPair('TUA','Tula');
  57. AddPair('Sux','SuxxCity');
  58. WriteLn(GetValue('SPB'));
  59. WriteLn(GetValue('_NY'));
  60. WriteLn(GetValue('MOC'));
  61. WriteLn(GetValue('Sux'));
  62. end.