Reading the Pragmatic Programmer's PragPub from March (I must admit I don't have/take the time to read them regularly enough) I stumbled upon Scala's sliding function on Arrays. This creates a sliding window of consecutive sub arrays of an array. So an Array(1,2,3,4).sliding(2) would produce an iterator of arrays (1,2), (2,3), and (3,4). Useful! While googling around to see if Ruby has something similar I stumbled across the windowed function in F# that pretty much works the same way, before finding Ruby's each_cons. The first thing I did to test this was to revisit an old (fairly obvious, brute force) seven line Ruby solution (from back in the day when I had just discovered the language) to an Euler problem, and replaced it with the following (admittedly still brute force) one liner (where 'number' is a 1000 character long string containing only numbers):
Unlike Scala where you would have the function sliding on string objects, we need to call chars on the string to get an array of the characters. What happens next is that I map the function to_i(nteger) on the resulting array to get an array of integers. And then each_cons enters! (The argument here is obviously the window size.) I then map the resulting enumerator (I could also have sent it to a block) to a simple anonymous function that multiplies all the elements together before returning the max value of this new array.
Voila, we have the largest product of five consecutive numbers within a 1000 digit number. Functional and concise. (I won't give you the number of the Euler problem, as that would probably break some (un)written rule...)
BTW: The article mentioned above is on the expressiveness of Java vs Scala and starts off on a reflection from the author on how he took a project from 2500 lines of Java code to 250 lines of Scala code after having programmed in Scala only 6 months.
Unlike Scala where you would have the function sliding on string objects, we need to call chars on the string to get an array of the characters. What happens next is that I map the function to_i(nteger) on the resulting array to get an array of integers. And then each_cons enters! (The argument here is obviously the window size.) I then map the resulting enumerator (I could also have sent it to a block) to a simple anonymous function that multiplies all the elements together before returning the max value of this new array.
Voila, we have the largest product of five consecutive numbers within a 1000 digit number. Functional and concise. (I won't give you the number of the Euler problem, as that would probably break some (un)written rule...)
BTW: The article mentioned above is on the expressiveness of Java vs Scala and starts off on a reflection from the author on how he took a project from 2500 lines of Java code to 250 lines of Scala code after having programmed in Scala only 6 months.
Comments
Post a Comment