for times = 1,100,1 do
local printableOutput = ""
local function test(number, stringToAdd)
if times % number == 0 then
printableOutput = printableOutput .. stringToAdd
end
end
test(2,"Fizz")
test(3,"Buzz")
-- so on
if printableOutput == "" then
printableOutput = times
end
print(printableOutput)
end
The code works but i feel like it’s clunky and wondered if there’s some way to improve it
local function testModZero(str, a, b)
if a % b == 0 then
return str
end
return ""
end
for index = 1, 100 do
local output = testModZero("Fizz", index, 3) .. testModZero("Buzz", index, 5)
print(index, output)
end
There’s my version of FizzBuzz that respects how you approached the problem with a function that checks for two numbers mod to zero. We can make the function once and open a third parameter for the current loop iteration.
I’d say a system like this would be a bit more organized
local stringTimes = {
{2, "Fizz"},
{3, "Buzz"}
}
for times = 1,100 do
local printableOutput = ""
for _, info in ipairs(stringTimes) do
if times % info[1] ~= 0 then
continue
end
printableOutput ..= info[2]
end
print(printableOutput == "" and times or printableOutput)
end
stringTimes would be a table that contains tables in it, whose first index is the number to modulo with and the 2nd index is the word to append. The tables need to be written in order from smallest number to modulo with to largest number to modulo with as it could cause the strings to be weird.
Then everytime we iterate from 1 to 100, we go through the table and multiply times with the number in the table and if it equals 0, we continue and append the word to the variable. Then at the end we check if the variable is an empty string, and if it is we return the current number and if it isn’t, we return the string.
If you plan on adding more words you just make another table and wouldn’t destroy readability if ever add 10 or more words, @okeanskiy method is smaller, and could be made even small through the fake tenary,
if a % b == 0 then
return str
end
return ""
can be sortened to
return a % b == 0 and str or ""
But personally I don’t like the idea of having to increase an already lengthy line of code everytime i want to add another word