{*************************************************************************
 *                                                                       *
 *                    XI Olimpiada Informatyczna                         *
 *                                                                       *
 *   Rozwiązanie zadania: PIN-kod                                        *
 *   Plik:                pin2.pas                                       *
 *   Autor:               Tomasz Czajka                                  *
 *************************************************************************}

uses hsm;

var
  tab: array[0..9999, 0..3] of Longint;
  nposs: Longint;
  poss: array[0..9999] of Longint;


procedure fillTab;
var i,j,k: Longint;
begin
  for i:=0 to 9999 do begin
    j := i;
    for k:=3 downto 0 do begin
      tab[i][k] := j mod 10;
      j := j div 10;
    end;
  end;
end;

{ zwraca pin, dla ktorego maszyna maszyna zwroci TAK dla danego kodu i pytania }
function check(pin: array of Longint; pyt: Longint):Longint;
var i,res: Longint;
begin
  res := 0;
  for i:=0 to 3 do begin
    if (pyt and (1 shl pin[i])) <> 0 then
      res := res or (1 shl i)
  end;
  exit(res);
end;

procedure zrobRuch;
var
  pyt,bestPin,bestA,bestV,v,p,i: Longint;
  c: array[0..15] of Longint;
  a: array[0..15] of Longint;
  pin: array[0..3] of Longint;
  res: Boolean;
begin
  bestv := -1;
  for pyt:=0 to 1023 do begin
    for i:=0 to 15 do c[i]:=0;
    for i:=0 to nposs-1 do
      inc(c[check(tab[poss[i]], pyt)]);
    v := 0;
    for i:=0 to 15 do if c[i]>v then begin v:=c[i]; p:=i end;
    if nposs-v < v then v:=nposs-v;
    if v>bestv then begin bestPin:=p; bestA:=pyt; bestv:=v end
  end;

  for i:=0 to 15 do a[i] := (bestA shr (i mod 10)) and 1;
  for i:=0 to 3 do pin[i] := (bestPin shr i) and 1;  

  res := sprawdz(pin, a);

  i:=0;
  while i<nposs do begin
    if((check(tab[poss[i]], bestA)=bestPin)<>res) then begin
      poss[i] := poss[nposs-1];
      dec(nposs);
    end
    else inc(i)
  end;
end;


var i: Longint;
begin
  fillTab();
  
  for i:=0 to 9999 do poss[i]:=i;
  nposs := 10000;
  
  while nposs>1 do zrobRuch();
  
  wynik(tab[poss[0]]);
end.
