This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrpoopy345's profile picture

Why does this loop go on forever?

Started by mrpoopy345, 28 October 2014 - 01:35 PM
mrpoopy345 #1
Posted 28 October 2014 - 02:35 PM
I made a guess the number "AI", and I was curious to find out the average number of guesses it takes for this AI to guess the correct number.
So I made this:

avg = 0
l = 0
max = 100
min = 1
avgs = {}
--term.write("Enter a number between 1 100: ")
--input = tonumber(read())
for i = 1, 20 do
input = math.random(1, 100)
repeat
guess = math.random(min, max)
l = l+1
if guess < input then
  min = guess
elseif guess > input then
max = guess
end
until guess == input
table.insert(avgs, l)
print("The number was "..guess..", and it took "..l.." guesses")
end
for k, v in pairs(avgs) do
avg = avg + v
avg = avg/20
end
print("The final average guesses: "..avg)
But this just runs the guessing AI twice and then pauses, and then throws and outOfBounds Exception.
Any help?
TheOddByte #2
Posted 28 October 2014 - 03:49 PM
You'd have to reset the variables max and min before the repeat loop
DannySMc #3
Posted 28 October 2014 - 03:50 PM
I made a guess the number "AI", and I was curious to find out the average number of guesses it takes for this AI to guess the correct number.
So I made this:

avg = 0
l = 0
max = 100
min = 1
avgs = {}
--term.write("Enter a number between 1 100: ")
--input = tonumber(read())
for i = 1, 20 do
input = math.random(1, 100)
repeat
guess = math.random(min, max)
l = l+1
if guess < input then
  min = guess
elseif guess > input then
max = guess
end
until guess == input
table.insert(avgs, l)
print("The number was "..guess..", and it took "..l.." guesses")
end
for k, v in pairs(avgs) do
avg = avg + v
avg = avg/20
end
print("The final average guesses: "..avg)
But this just runs the guessing AI twice and then pauses, and then throws and outOfBounds Exception.
Any help?

You need a sleep() as it's running for too long without a yield. try adding a sleep(0.1) and try again?
Dragon53535 #4
Posted 28 October 2014 - 04:02 PM
TheOddByte is correct, your loop is basically seeing min and max as the last guess, and then trying to guess that number over and over again for the number.

for whatever
  math.random(1,100)
  repeat
	math.random(min,max)--#Eventually when you repeat, this will be
	--#math.random(1,2) which will always go over and over again trying just that bit, and since it's not going to hit the other number, shuts down
	min = 1
	max = 2
  until whatever
end

Also you should reset l inside your loop as well, since the messages stack up to like 200 guesses at the end
Edited on 28 October 2014 - 03:02 PM