2005-12-09

J The sum of ajacent numbers

Problem: Find the sum of adjacent twos, triples and so on in array. The result should be in ascending order.

After having dificulties and learned a lot of stuff, I've written:

diff=: 4 : 0
| (#x.) - #y.
)

summ=:(>:@:diff }. [) + (_1&}.@:])

allsums=: 3 : 0
x =. ''
m =. y.
while. #m ~: 0 do.
m=.y. summ m
x =. x,m
end.
/:~x
)


The usage:

summ^:2~ 2 _3 7 4 0 6 NB. Сумма смежных троек
6 8 11 10
allsums 2 _3 7 4 0 6 NB. Все возможные суммы
_1 4 4 6 6 8 8 10 10 10 11 11 14 16 17


It seems, I heard that it is possible to have your own participles in J. IMHO, to make the solution more beautiful, the verb 'allsums' should be transformed into a participle 'collect' so that one can use any other verb instead of 'summ'.

No comments:

Post a Comment