thoga31

Friend Numbers

Jun 26th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.07 KB | None | 0 0
  1. (* From a list of given numbers, find out which pairs are friends.
  2. A pair of numbers, (A,B), is friend when A+B is a number which last digit is 0. *)
  3.  
  4. program friends_challenge;
  5. uses crt;  // for the Pause method, only
  6.  
  7. type TPair = record
  8.         a, b : byte;
  9.      end;
  10.      TList = array of byte;
  11.      TFrs  = array of TPair;
  12.  
  13. // Pause method (compacted in one line):
  14. procedure Pause; begin repeat until readkey = #13; end;
  15.  
  16. procedure GetNumbers(const q : byte; var list : TList);
  17. (* Gets the list of numbers from the user. *)
  18. var i : byte;
  19. begin
  20.     SetLength(list, q);
  21.     for i:=0 to q-1 do
  22.         readln(list[i]);
  23. end;
  24.  
  25. procedure GetFriends(const list : TList; var frs : TFrs);
  26. (* Algorithm - gets the list of pairs of numbers which are friends. *)
  27. const MAX = 255;
  28. var i, j : byte;
  29.     seen : array [0..MAX, 0..MAX] of boolean;
  30. begin
  31.     // initialization fo "seen"
  32.     for i:=0 to MAX do for j:=0 to MAX do seen[i,j]:=false;
  33.  
  34.     // finding the friends...
  35.     for i:=low(list) to high(list)-1 do
  36.         for j:=i+1 to high(list) do
  37.             if ((list[i] + list[j]) mod 10 = 0) and not seen[list[i], list[j]] then begin
  38.                 SetLength(frs, Length(frs)+1);
  39.                 frs[Length(frs)-1].a := list[i];
  40.                 frs[Length(frs)-1].b := list[j];
  41.                 seen[list[i], list[j]] := true;
  42.                 seen[list[j], list[i]] := true;
  43.             end;
  44. end;
  45.  
  46. var n : byte;         // how many numbers will be given
  47.     numbers : TList;  // the list of numbers to search
  48.     friends : TFrs;   // the list of pairs of number which are friends
  49.     elem : TPair;     // usage: FOR-IN cycle
  50.  
  51. begin
  52.     // INPUT
  53.     repeat
  54.         write('How many? '); readln(n);
  55.         if (n < 2) then writeln('Must be greater than or equal to 2!');
  56.     until (n >= 2);
  57.  
  58.     GetNumbers(n, numbers);        // getting the list...
  59.     GetFriends(numbers, friends);  // getting the friends...
  60.  
  61.     // OUTPUT
  62.     write('The ', Length(friends), ' friend pairs are: ');
  63.     for elem in friends do write('(', elem.a, ',', elem.b, ') ');
  64.     Pause;
  65. end.
Advertisement
Add Comment
Please, Sign In to add comment