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

Shorten this block.

Started by Bluethousandand2, 16 January 2014 - 07:36 PM
Bluethousandand2 #1
Posted 16 January 2014 - 08:36 PM
Any way to use the 'for' loop to shorten this block?


if x==1 then
time=285
elseif x==2 then
time=560
elseif x==3 then
time=835
elseif x==4 then
time=973
elseif x==5 then
time=1110
elseif x==6 then
time=1248
elseif x==7 then
time=1385
elseif x==8 then
time=1660
elseif x==9 then
time=1935
else
print("Ya' done goofed.")
abort()
end
Lyqyd #2
Posted 16 January 2014 - 10:09 PM
Not sure where a for loop would enter into it.


local times = { 285, 560, 835, 973, 1110, 1248, 1385, 1660, 1935 }

if x >= 1 and x <= 9 then
    time = times[x]
else
    print("Ya' done goofed.")
    abort()
end
Bab #3
Posted 17 January 2014 - 01:03 AM
Unless the time values follow some sort of pattern I'm not aware of, a for loop isn't possible for that block.
Buho #4
Posted 17 January 2014 - 10:53 AM
They are increments of either 275 or 137 or 138. The 137 and 138 are probably rounding errors since they both straddle 275 / 2. The first value could be an offset of 10. You could get the series with this:

function table.contains(table, element)
    for value in table do
        if value == element then
            return true
        end
    end
    return false
end

local c = 137.5
local times = {  }
local excludeIndexes = { 1, 3, 5, 11, 13 }
for i = 1, 14 do
    if not table.contains(excludeIndexes, i) then
        table.insert(times, math.floor(i * c) + 10)
    end
end
I see no pattern with the excluded indexes, so the algorithm is still longer, and strictly-speaking, it spits out 972 instead of 973 and 1247 instead of 1248.