Let's Play Code Golf

Charles via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 23 16:59:17 PST 2015


On Monday, 23 February 2015 at 23:10:32 UTC, anonymous wrote:
> On Monday, 23 February 2015 at 20:21:20 UTC, Charles wrote:
>> My solution (150 characters, 15 points):
>>
>>    void main(){import std.stdio;int t,n;readf(" 
>> %d",&t);while(t--){readf(" %d",&n);real 
>> a=0,i=0;for(;i<n;i++)a+=(i%2?-1:1)/(i+i+1);writefln("%.15f",a);}}
>>
>> Link to problem site: 
>> https://www.hackerrank.com/challenges/leibniz
>>
>> Anyone care to do better? :)
>
> 126:
>
> void main(){import std.stdio;real n,a;for(readln;a=0,readf(" 
> %f",&n);writefln("%.15f",a))while(--n>=0)a+=(n%2?-1:1)/(n+n+1);}

Nice going. I didn't realize that the exponent operator was 
outside of std.math with ^^ which is why I used the ternary 
operator to achieve the same results, importing the standard 
library is probably the most expensive thing for this challenge. 
Yay learning things. With that in mind, and switching around --n 
to n--, we can get the code down to 120 characters:

void main(){import std.stdio;real n,a=0;for(readln;readf(" 
%f",&n);writefln("%.15f",a))while(n--)a+=(-1)^^n/(n+n+1);}

On Tuesday, 24 February 2015 at 00:03:55 UTC, bearophile wrote:
> Steve Sobel:
>
>> It can get down to 155 using ranges, but those imports really 
>> are killer.
>
> You usually don't want to design a language for code golfing 
> (but several exist, like http://esolangs.org/wiki/GolfScript ).


Yeah I know that they're languages designed for this, but they 
feel like cheating for sure. Plus, GolfScript would be kinda odd 
on DLang's forums ;)



More information about the Digitalmars-d mailing list