Tuesday, May 27, 2008

Learning J language - euler problem36

Project euler problem 36 definition:
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)

So, I has some interest in array programming language J. I try to learn it a bit. And as such, I tried to solve this euler problem with the help of J language. What I learned is that this J language is VERY powerful and also it`s programs is very short, but also it is very hard to learn this language and of course - hard to understand the code (if you don`t know the language). But as soon as you proceed - more things are showing up from the fog :-).

So this is the solution:


One shot - One Kill, oh sorry, I mean: One line - One Goal :-)

As you see this code is not much understandable, but I have a little bit more readable code, acctually code is the same- just with defined function names.
This is it:

equalbits=: +/@:(=|.)
decpalind =: (equalbits=#)@:":
binpalind =: (equalbits=#)@:#:
bothpalind =: (decpalind*.binpalind)"0
palindsum =: +/@:((0:`(0&+))@.bothpalind)
palindsum i.1000000

Also just 6 lines of code. And a bit more readable, but not more if you don`t know some J basics. This language is very powerfull - especially at data processing.
If you want to learn J some basics, I would recommend this online book (also comes for free as documentation in J installation pack). Note - J interpreter is also free. This book is very good introduction, without it I would not take a look at J.
So all in all J - powerfull,interesting,strange,hard language in the same time, IMHO.
Have fun !!

1 comment:

  1. kudos !
    You write handsome code . Never heard of j-language before ! Keep it up


Comment will be posted after comment moderation.
Thank you for your appreciation.