Snack Break Problems #2 and #3
Posted on May 24, 2015 by Unclear
Followup on SB1
Here is the solution to SB1 that was posted on github.
Last week's question was FizzBuzz, an introductory programming problem meant to test programming competency. The strategy for that problem was rather straight forward; you simply had to check if numbers were divisible by 5, 3, both, or none!
If you knew of the %
operator, then you were in luck. A number a
is divisible by a number b
if a%b == 0
. Even if you did not know about %
, you could get away with using math.floor
to get the same result with a bit more computation; a%b == 0
is the same as a - b*math.floor(a/b) == 0
!
Explaining my solution
local results = { } for index = 1, 100 do if index % 15 == 0 then results[index] = "FizzBuzz" elseif index%3 == 0 then results[index] = "Fizz" elseif index%5 == 0 then results[index] = "Buzz" else results[index] = index end end print(table.concat(results, "\n"))
My solution is pretty close to the standard solution, but there are a few differences.
1: I chose to use index % 15 == 0
instead of index%3 == 0 and index%5 == 0
.
It turns out that if you want to check if a number is divisible by multiple divisors, you can just check if the number is divisible by the product of the divisors! That means that index%a == 0 and index%b == 0
is the same as index%(a*b) == 0
.
This has the advantage of not only showing off knowledge of a property of %
, but also being a bit easier on the computer to calculate by having fewer operations.
2: I chose to print out the result only once in string form
The print
function is an expensive operation. This means that it takes a lot of resources just to output some text onto the console! We can avoid using print
every single time we do a calculation by just keeping track of all of the results in string form through concatenation, and then using print
once at the very end.
Even after doing that, we can make it even easier on the computer to run this program! Instead of using the concatenation operator ..
, we can just use table.concat
. Every single time you use ..
, Lua stores the resulting concatenation in memory! As you can imagine, this can build up pretty quickly if you use ..
very often. However, using table.concat
tells Lua to only store the final concatenation; in our case, instead of storing 100 strings we are storing 1!
This week's problems
The real fun starts now; last week's problem was only a small warmup. This week you will be tackling two problems that are a lot more difficult than FizzBuzz!
Prime factorization is SB2. You will be splitting up numbers from 2 to 100 into a product of prime numbers!
Angular offset sign is SB3. You will be getting the sign of the direction it takes to get from one angle to another with the least amount of rotation!
Visit the links above for more details.
I'll see you all next week!
Commentary
Leave a Comment