** EDITED AGAIN - sorry I seem to be having trouble with the lua block codes, it’s being interpreted as one line of code which clearly it isn’t, so I’ve removed the lua tags - if anyone knows how to correct this problem I’ll reinstate them **
Whenever I see other people’s code I’m always amazed at how elegant and concise it is, so I was wondering if there was a better way to write this function. My current code feels very long-winded and as a coding newbie I get a lot by learning from other’s coding styles.
What I need the function to do is check for repetition in a simple array. The contents might be numbers, strings or references to tables. There’s no possibility of having to confirm that the tables are identical without having identical references, which simplifies things a little bit.
Just to clarify what I mean by repetition, it should return true if the table consists of exactly repetitive sequences, and false otherwise.
E.g. {0,1,0,1} returns true but {0,1,0,1,2} returns false. Even though the second table has some repetition, it is not wholly repetitive.
My current function seems to work ok, and it’s not in a performance critical section of my game, but I thought it might be an interesting exercise. I may be wrong of course!
function checkForRepetition( tab )
if type( tab ) ~= “table” then print(“Invalid input for repetition check”) end
local max = #tab
– takes a table of values and checks if they’re all the same
local function checkSame(arg)
for i = 1, (#arg-1) do
print(arg[i], arg[i + 1])
if arg[i] ~= arg[i + 1] then
return false
end
end
return true
end
– checks for periodic repetition and returns true if it finds it
local function subDivisorCheck( start, divisor)
print(“checking start”, start, “divisor”, divisor)
local i = start
local coll = {}
while i <= max do
coll[#coll + 1] = tab[i]
i = i + divisor
end
return checkSame(coll)
end
– default assumption is that there’s no repetition
local isThereRepetition = false
– check each possible sub-sequence length (called a divisor) e.g. for length 12 check 2,3,4,6
local maxDivisor = math.floor(max/2)
local divisor
for divisor = 1, maxDivisor do
local divisorRepetition = true
for start = 1, divisor do
if not subDivisorCheck(start, divisor) then
divisorRepetition = false
end
end
if divisorRepetition then
print(“Yes there is repetition”)
return true
end
end
print(“There is no repetition”)
return false
end