Monday, August 3, 2009

Project Euler #17, Optimization Script

So, as I said in my last post, one of the first obvious optimizations to make is to do away with the number name strings altogether, and just count the number of letters in each number name directly. Being lazy, I didn't want to go through my first script and do that by hand -- time-consuming and error-prone. So I wrote a new Perl 6 script to do it for me:

Note that the central loop is just a big serious of when statements. I suspect quite a few of my old Perl 5 scripts have inner loops which would be most naturally expressed this way. The first when is just to automatically pass on lines with comments, none of which I wanted to mess with. The second just transforms lines with strings by applying the letter counting subst from the previous script. The third just copies anything else over.

This doesn't result in a working Euler script -- I still needed to go through and change it from working with the now missing strings to the new numbers. But it did all the grunt work for the change.

This makes the Euler #17 code run about twice as fast. Next up is getting that sort statement out of the inner loop...

No comments:

Post a Comment