As an experiment, I'm trying to create a magic square program that checks every possible square with nine numbers. For those who do not know, a magic square is a 3x3 grid of numbers 1-9, where each row, column, and diagonal add up to 15. For example:
How would I go about checking each square using a table with Lua? I'm starting with the following table:
local sq = {
1, 1, 1,
1, 1, 1
1, 1, 1
}
How would I go about checking each table in the correct order? I'm able to draw out my thinking on paper, but I'm not completely sure how to translate it to code. I already created the function to check if the square is 'magic' (following), but I'm not sure how to increase each number in the correct fashion.
local isMagic = function(s)
return (
s[1] + s[2] + s[3] == 15 and
s[4] + s[5] + s[6] == 15 and
s[7] + s[8] + s[9] == 15 and
s[1] + s[4] + s[7] == 15 and
s[2] + s[5] + s[8] == 15 and
s[3] + s[6] + s[9] == 15 and
s[1] + s[5] + s[9] == 15 and
s[3] + s[5] + s[7] == 15
)
end