Self Numbers In Jay Language

Following was one of the pre-interview puzzles for a famous software company.

When a natural number n is given, d(n) is defined as the number n itself added to the sum of n's digits.

For example, d(91) = 9 + 1 + 91 = 101

Here, n is called d(n)'s generator. In the example above, 91 is 101's generator. Some numbers have more than one generator; 101 has as generators not only 91 but also 100. On the other hand, there are numbers that do not have any generators and such numbers are called self-numbers by an Indian mathematician, D. R. Kaprekar (http://en.wikipedia.org/wiki/D._R._Kaprekar).

For example, 1, 3, 5, 7, 9, 20, 31 are self-numbers.

What is the sum of all self-numbers that are 1 or more, and less than 5000?


   base10=:10&#.               
   base10 1 2 3                         
 123                                 

inversed=:^:_1 digits=:base10 inversed digits 123 1 2 3

add=:+ over=:/ sum=:add over sum 123 1 2 3 129

of=:@ generate=: add sum of digits generate 123 129

foreach=:"0 geneach=:generate foreach geneach 123 456 129 471

except=:-. 1 2 3 4 except 2 4 1 3

lessthan=:>:@i.@<: lessthan 10 1 2 3 4 5 6 7 8 9

selfnum=: except geneach sum of selfnum lessthan 5000 1227365

Indented is what I typed in and unindented is the interpreter result.

The script above is an extended verbose version of what I actually stepped through when solving the puzzle for the first time. My original steps were close to the following:

   d=:10&#.^:_1
   g=:(+ +/@d)"0
   +/ (-. g) >:i.<:5000

I solved this puzzle with these steps in about 30 seconds(with runtime being about 0.1 sec) thanks to JayLanguage. Of course, the time spent in reading(and thinking simultaneously) the problem was not included in this short time. ;-)

--JuneKim


EditText of this page (last edited April 25, 2006) or FindPage with title or text search