On 02/08/06, Daniel Baird <danielbaird / gmail.com> wrote:
> Hi all,
>
> I've been golfing around with the sieve of Eratosthenes.  Here's what
> I've got so far:
>
> a=(2..100).to_a;p a.each{|c|a.map!{|d|c&&d&&c<d&&d%c==0?nil:d}}.compact
>
> It's already under 80 chars, but I'd still love to remove the
> definition of the array a, and do the whole thing with no semicolons.
> Any suggestions?
>
> If you're interested, here's an indented/commented copy that might
> save a few minutes..
>
> # create an array of integers, 2 to 100
> a=(2..100).to_a;
> p a.each{ |c|
>   # for each element c in that array, if c isn't nil, it's prime. so
> set multiples of c to nil
>   a.map!{ |d|
>     c && d && c<d && d%c == 0 ? nil : d
>   }
> }.compact  # finally, print the array minus the nils
>
>
> I'd appreciate any comments.
>
> Cheers
>
> ;Daniel
>
>
> --
> Daniel Baird
> http://tiddlyspot.com (free, effortless TiddlyWiki hosting)
> http://danielbaird.com (TiddlyW;nks! :: Whiteboard Koala :: Blog ::
> Things That Suck)

Here's my attempt. Note that I have made it a bit more general by
assigning s = 100 beforehand.

(2..(s**0.5)).inject((2..s).to_a){|a,c|a.map!{|d|c&&d&&c<d&&d%c==0?nil:d}}.compact

I got rid of the semi-colons and assigning the arrays (although
technically it's still 'assigned' in the inject) although it might has
made it a bit loner.

Farrel