[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Rounding a number to integer
- From: Dirk Laurie <dirk.laurie@...>
- Date: Thu, 4 Aug 2016 07:34:56 +0200
2016-08-03 22:29 GMT+02:00 Egor Skriptunoff <email@example.com>:
>> function round(x)
>> local ans = math.floor(x)
>> local err = x-ans
>> if err<0.5 then return ans
>> elseif err>0.5 then return ans+1
>> elseif ans%2==0 then return ans
>> else return ans+1
> Yes, that's correct (but cumbersome).
At least one person besides the author could see at a glance
that the code is correct. I'll take 'cumbersome' any day if it can
give me that.
> Don't you like codegolf? :-)
Yes, but it penalizes good Lua coding (e.g. 'local' uses up
five letters and a space). I'll propose another scoring method
> function round(x)
> local y = math.ceil(x - 0.5)
> return x - y + y/2%1 < 1 and y or math.ceil(x)
I'll take your word that it works, since you have a good
reputation for meticulous coding.
The scoring variation is: run `luac -l` on the code and count the
number of VM instructions actually executed on input selected
to make that number as large as possible. Let the games begin!