ShareMyScreen/ProjectEuler/0004
Jump to navigation
Jump to search
As the problem description states, a palindrome is a string that reads the same both ways. The simplest way in J to describe this is y -: |. y, which evaluates if the input matches the reversed input entirely. Since the search space is relatively small, I will check every possible number. J will have no problem giving a quick answer.
J has a primitive called table with the form x u/ y that will compute a u b for every a in x and b in y if the dyadic rank of u is 0. Every possible product of two 3-digit numbers can be computed easily by supplying * as the dyadic verb.
NB. ~. , flattens the resuting table and uniquifies it to remove unnecessary checks later 0 _1 { products =. ~. , */~ 100 + i.900 NB. 100 * 100 and 999 * 999 10000 998001
To find the maximum palindrome, it is sufficient to filter out each palindrome by checking each number in products for the property and computing the max by >./.
+/ (-:|.)@":"0 products NB. count number of palindromes, note (-:|.) is a monadic hook and is the same as y -: |. y 655 # products #~ (-:|.)@":"0 products NB. a boolean list as the left arg for # acts as a filter 655 >./ products #~ (-:|.)@":"0 products NB. finally, the answer 906609