Skip to content

Instantly share code, notes, and snippets.

@l0gicpath
Last active August 29, 2015 13:55
Show Gist options
  • Save l0gicpath/8733723 to your computer and use it in GitHub Desktop.
Save l0gicpath/8733723 to your computer and use it in GitHub Desktop.
One liner ruby solution for project euler problem #2 because ruby is hardcore
(l ,ss = 4000000, proc {|p, n, s| p >= l || n >= l ? s : n.even?? ss[n, n + p, s + n] : ss[n, n + p, s] })[1][1, 2, 0]
@l0gicpath
Copy link
Author

A highly-unrecommended way of doing ruby for a living:

Just a fun one-line solution to project euler problem #2 using parallel assignments and nested ternary operators(?:) with anonymous recursion in procs.

Preliminaries

The awkward syntax that seems to magically generate an array is a not so common parallel assignment technique that's not idiomatic.

(x, z = 1, 2) # => gives us  [1, 2]

Since we needed a reference to ourselves inside the proc for recursion and we needed the limit to be variable this prompted the notion described above

(l, ss = 4000000, proc {...}) # => gives us [4000000, #<Proc:...>]

This gave us a limit value and a Proc object that are bound to scoped variables and are accessible from within our proc

(l, # the limit
ss = 4000000, proc { |p, n, s| # just binding proc to a variable so we can recursively invoke it
  # Our heros, Prev value, Next value and the Sum
  p >= l || n >= l ? # Our base condition, check if we've reached our limit or not
    s # we have, so return the total sum
    : n.even? ? # we haven't, so let's check if Next is even
      ss[n, n + p, s + n] # Next is indeed even, so add it up and move onto the next fib value
      : ss[n, n + p, s] # nope, Next isn't even so we'll move on passing the total sum as is
})[1][1,2,0] # access the proc as the 2nd array element then invoke it, passing our initial three values

@emad-elsaid
Copy link

thanks for the explanation, i think the proc part and the multi assignment will help me alot with my scripts,
these are so little bits i miss while learning the language.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment