Using loop to solve if number < than 200 previous numbers, return 1

Viewed 64

I'm writing a small program in lua and I was hoping to get some pointers on what would be the most correct way to approach this. Basically, if my number is bigger than the last 200 numbers, return 1, else return 0.

I figure the best way would be a loop? Let's say x is the position of my number in a table, and then I want to check that it's bigger than the previous 200 numbers and return 1 at the end if it is and 0 if it's not.

while (x > x-a)
    do
        isbigger = 1;
        a = a+1;
        return isbigger;
    end

I'm not sure if that's correct syntax wise, it also would technically return 1 everytime it goes through the loop and I just want it at the end if true that my number is bigger than the 200 previous one. Also, how do get out of the loop if its false (I'd guess with a break)? Thanks for any help and have a nice day!

1 Answers

If you are looping over an array of values, you should use a for loop. you also do not want to return isbigger from inside the loop as it will prematurely end the loop

local last = 10
local myNumber = 123
local numbers = {}

--Setup our example numbers table
math.randomseed(os.clock())
for i = 1, 40 do
    numbers[i] = math.random(1,200)
end

--Run comparison on our the last x values
local isBigger = true
for i = #numbers, #numbers - last, -1 do
    print(myNumber, numbers[i],  myNumber > numbers[i])
    isBigger= isBigger and myNumber > numbers[i]
end

print("isBigger is: " .. isBigger)
return isBigger and 1 or 0

Example Output

123 181 false
123 6   true
123 77  true
123 78  true
123 145 false
123 130 false
123 104 true
123 114 true
123 6   true
123 4   true
123 15  true
isBigger is: false

The for loop above is better for understanding what is happening, but this one is better for use as it will exit once it has found an result that shows myNumber is not bigger.

local isBigger = true
for i = #numbers, #numbers - last, -1 do
    print(myNumber, numbers[i],  myNumber > numbers[i])
    if not (myNumber > numbers[i]) then
        isBigger = false
        break
    end
end
Related