MAKN

iguessyournumber.lua

Dec 31st, 2020 (edited)
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.80 KB | None | 0 0
  1. --"I guess your number" not "guess a number"
  2. function cheat(rsmall,rbig,number)
  3.     local small=rsmall;
  4.     local big=rbig;
  5.     local num=small+(big-small)/2
  6.     for attempt=0,math.ceil(math.log(rbig-rsmall)/math.log(2)),1 do local num=small+(big-small)/2
  7.         io.write("Attempt ",attempt,'/',math.ceil(math.log(rbig-rsmall)/math.log(2)),'\n')
  8.         io.write("N: ",math.floor(num),'\n')
  9.         if (math.floor(num)==number) then io.write(math.floor(num)," = ",math.floor(number),'\n');return true;
  10.         elseif (math.floor(num) < number) then io.write(math.floor(num),"< ",math.floor(number),'\n');small=num;
  11.         elseif (math.floor(num) > number) then io.write(math.floor(num)," > ",math.floor(number),'\n');big=num;
  12.         end
  13.     end
  14.     return false;
  15. end
  16.  
  17. function main()
  18. io.write("Enter number range\nfrom>");smaller = io.read('*n');
  19. io.write("to>");bigger = io.read('*n');
  20.     local win=false;local attempt=0;local bg=bigger;local sm=smaller
  21.     while(win==false) do attempt=attempt+1; io.write("Attempt ",attempt,'/',math.ceil(math.log(bg-sm) / math.log(2)),'\n')
  22.         if (attempt > math.ceil(math.log(bg-sm) / math.log(2))) then print("I lost");
  23.         io.write("Type your number\n>")if cheat(sm,bg,io.read('*n')) then print("You are a cheater"); end
  24.         return 1;
  25.         end
  26.     n=smaller+(bigger-smaller)/2
  27.     print("i guess",math.floor(n));
  28.     io.write("Is that your number?\n1 - Guess = Number\n2 - Guess < Number\n3 - Guess > Number\n>");
  29.         while(1) do choice= io.read('*n');
  30.             if (choice==1) then win=true; break;
  31.             elseif (choice==2) then smaller=n break
  32.             elseif (choice==3) then bigger=n; break
  33.             else print("Invalid Choice");
  34.             end
  35.         end
  36.     end
  37.     io.write("I guessed it")
  38.     return 0;
  39. end
  40. main()
Add Comment
Please, Sign In to add comment