views:

106

answers:

1

I've solved 84 of the Project Euler problems, mostly in Haskell. I am now going back and trying to solve in J some of those I already solved in Haskell, as an exercise in learning J.

Currently, I am trying to solve Problem 56. Let me stress that I already know what the right answer is, since I've already solved it in Haskell. It's a very easy, trivial problem. I will not give the answer here.

Here is my solution in J:

digits =: ("."0)@":"0
eachDigit =: adverb : 'u@:digits"0' NB. I use this so often I made it an adverb.
cartesian =: adverb : '((#~ #) u ($~ *:@#))'
>./ +/ eachDigit x: ^ cartesian >: i. 99

This produces a number less than the desired result. In other words, it's wrong somehow. Any J-ers out there know why? I'm baffled, since it's pretty straightforward and totally brute force.

+4  A: 

The reason is that you are applying extended precision (x:) too late in the game. Switch to extended precision the very first thing you do (e.g. i. x: 99) and your should be all set.

One other note, regarding your cartesian. You might want to have a look at J's built-in "table" adverb (/):

   ^/~ >: i.5
1  1   1   1    1
2  4   8  16   32
3  9  27  81  243
4 16  64 256 1024
5 25 125 625 3125

   , ^/~ >: i.3
1 1 1 2 4 8 3 9 27
earl
That fixed it! It also fixed a few other Project Euler problems I was working on. I'm investigating the table adverb at the moment.
Gregory Higley
I just realized I'm already familiar with the table adverb, but didn't realize you could use it for cartesian operations.
Gregory Higley
Oh! When it's used dyadically! I get it. Very nice!
Gregory Higley
I could have defined my `cartesian` as `cartesian =: adverb : ',@(u/~)'`.
Gregory Higley