I discovered Project Euler [1] yesterday via a post [2] on the Ruby-Talk [3] mailing list. If you're the sort of person who enjoys puzzles and doesn't mind math, I suggest that you try out the problems for yourself.
I've been working through the problems slowly and in numerical order. While most of my solutions have been "brute force," it has given me an opportunity to learn how to do things in Ruby.
Why slowly? Because I haven't had a lot of time.
Why in numerical order? Later problems build on earlier ones. As I reach a problem that requires a given function or routine, I can go "Hey, I just did that in problem #x" and reuse it.
Why Ruby? Ruby was my "language to learn" last year but I neglected it so I'm hoping I can get more done before I work on this year's language (which will probably be Erlang or Scheme).
A lot of what I've learned to do is quick one-liners with arrays, much like what Drew Olson [4] posted almost two years ago. (I love reinventing the wheel, don't you?) And then there have been neat numerical tricks.
For example, to find out if a number is prime with a somewhat naive algorithm:
class Fixnum
def prime?
return false if self < 2
return false if self == 2
return false if self % 2 == 0
i = 3
bound = Math.sqrt( self )
while i <= bound and i < self
return false if self % i == 0
i += 2
end
true
end
end
Monkeypatching this into Fixnum
is probably not the greatest idea to some people but it allows use of syntax like 31.prime?
(useful for testing) and ( n + 1 ).prime?
, which is theoretically useful. For example, to find if the Mersenne number [5] for a given power of two is prime, you could write: ( 2 ** n - 1 ).prime?
And, most importantly, I find n.prime?
to read better than prime?( n )
. Readability always trumps cleverness. Luckily, here, it's both readable and clever.
If you want to learn how to use a language better, I suggest you use it for the Project Euler problems. After a while, you'll find ways to do things you've probably not thought of before (or, possibly, ever needed to do before). And for Ruby fans, you can find a use for Array#each_cons
.
Links
[1] http://projecteuler.net
[2] http://www.ruby-forum.com/topic/177050#774885
[3] http://www.ruby-lang.org/en/community/mailing-lists/
[4] http://drewolson.wordpress.com/2007/03/23/5-things-you-can-do-with-a-ruby-array-in-one-line-plus-a-free-bonus/
[5] http://en.wikipedia.org/wiki/Mersenne_number
[6] https://www.ithiriel.com/taxonomy/term/5
[7] https://www.ithiriel.com/taxonomy/term/14