Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {$mode objfpc}
- program guesses;
- uses crt, sysutils;
- type TSetChar = set of char;
- function GetKey(const LIST_OF_KEYS : TSetChar; const PROMPT : string = '') : char;
- begin
- repeat
- Write(PROMPT);
- GetKey := crt.ReadKey;
- until GetKey in LIST_OF_KEYS;
- WriteLn(GetKey);
- end;
- // We cannot use DIV or MOD. The student doesn't know bitwise operations (SHR and SHL).
- function GetMid(lower, upper : longint) : longint;
- var diff : longint;
- rest : longint;
- begin
- diff := upper - lower;
- rest := diff;
- while rest > 1 do begin
- Inc(lower);
- Dec(rest, 2);
- end;
- GetMid := lower;
- end;
- function Guess(lower, upper : longint; var tries : byte) : longint;
- var mid : longint;
- begin
- Inc(tries);
- if lower = upper then
- guess := lower
- else begin
- mid := GetMid(lower, upper);
- case GetKey(['+','-','='], 'N=' + IntToStr(mid) + ' --> greater = "+", lesser = "-", equal = "=" ?') of
- '+' : Guess := Guess(mid+1, upper, tries);
- '-' : Guess := Guess(lower, mid-1, tries);
- '=' : Guess := mid;
- end;
- end;
- end;
- (* BLOCO PRINCIPAL *)
- const LOWERLIM = 1;
- UPPERLIM = 1000;
- var tries : byte = 0;
- g : longint;
- begin
- WriteLn('Think in a number between ', LOWERLIM, ' and ', UPPERLIM, ', including those two.');
- g := Guess(LOWERLIM, UPPERLIM, tries);
- WriteLn('Your number = ', g, ' (in ', tries, ' tries)');
- end.
Advertisement
Add Comment
Please, Sign In to add comment