Clojure Euler: Problem 008

Find the greatest product of five consecutive digits in the 1000-digit number.


Large number under the cut.


Idea behind this problem is pretty straightforward:

  1. Init maximum with some small value, zero would be good.
  2. Take first 5 digits, calculate the product.
  3. If product is greater than our current maximum, reassign it.
  4. Shift, to take other 5 digits, and back to the step 1.

A simple optimization can be applied: if our last element of 5 digit group is zero, then skip 5 shifts. But it’s details.

Let’s make our problem little harder to get more from clojure.

Assume that these digits stored in the file. First thing we need: to read the file.

(slurp "path/to/the/file")

slurp is the simplest function to read file content (In fact, not only files). It just returns string representation of the whole file.

Then we need to break one large string into symbols.

(seq "helloyo") => (\h \e \l \l \o \y \o)

seq return a sequence with linear access to collection. If applied to string, return sequence of characters.

But, there are some garbage in the file we don’t want, new lines for example.

(remove #(= \newline %) [\h \e \l \l \o \newline \y \o])

(slash) + something - represents character in clojure. \newline is a new line, known as \n in other languages.

Now we have long sequence with all digits from file. Need to get all consecutive groups with 5 letters.

(partition 5 1 [\h \e \l \l \o \y \o]) => [[\h \e \l \l \o] [\e \l \l \o \y] ... ]

partition is an excelent function for such tasks. We specify 5 - size of partition, and 1 shift size. It generates all consecutive groups with 5 elements till the end.

Calulating the product for each group gives us the solution.

(reduce * [1 2 3 4])

Not so fast.

You, probably, get ClassCastException.

After reading the file, we just get bunch of characters, instead of digits in mathematical sense. And applied mathematical operation * to them. So, simply speaking, \1 is not 1.

That’s why we need to transform every digit character to it’s actual digit value.

(map #(- (int %) 48) [\1 \2 \3]) => [1 2 3]

This awful implementation do the work.

Applying product of digits defined earlier we get solution to this problem.

Again, full code on GitHub.

P.S. slurp function very powerful and has may applications. You can specify encoding for reading as you want or read whole html page by url. But it is also very dangerous function, because reads all file contents to the memory and can take considerable amount of time. If you have a large file, say 15GB, read it line by line with buffered reader. Also, note spit function. It is opposite to slurp - writes string to the file.

mishadoff 27 November 2012
blog comments powered by Disqus