[Jprogramming] New to J, Problem 28

Ralph G Selfridge selfrid at cns.ufl.edu
Sun Dec 9 00:58:06 HKT 2007


If you wish a J solution, not a cubic, try

LP=: 13 : '_3++/+/\4,_12+32*>:i.<.-:y'

y is some odd integer

Ralph Selfridge


On Fri, 7 Dec 2007, Zsbán Ambrus wrote:

> On Dec 3, 2007 1:38 AM, Roger Hui <rhui000 at shaw.ca> wrote:
>> FYI: Problem 28 in www.ProjectEuler.net is as follows:
>>
>> Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
>>
>> 21 22 23 24 25
>> 20  7  8  9 10
>> 19  6  1  2 11
>> 18  5  4  3 12
>> 17 16 15 14 13
>>
>> It can be verified that the sum of both diagonals is 101.
>>
>> What is the sum of both diagonals in a 1001 by 1001 spiral formed in the same way?
>
> Let me reuse the code I posted on "http://www.perlmonks.com/?node_id=487200".
>
>> From improving the first version (the one that uses sort), we get:
>
>   (spiral1 =: - ]\ >:@:i.@:*: [`]`[} [: /: [: ,/ [: (>.&| ,
> (12&o.)@:(1j_1&*)@:j.)"0/~ i. - -:@:<:) 5
> 25 24 23 22 21
> 10  9  8  7 20
> 11  2  1  6 19
> 12  3  4  5 18
> 13 14 15 16 17
>   (~.@:(<"1)@:(,.~,],.|.)@:i. { spiral1) 5
> 25 9 1 5 17 21 7 3 13
>   +/ (~.@:(<"1)@:(,.~,],.|.)@:i. { spiral1) 5
> 101
>   +/ (~.@:(<"1)@:(,.~,],.|.)@:i. { spiral1) 1001
> 669171001
>
> The third solution (the one that builds the spiral recursively from
> inside out) turns out to be much slower because of the lots of array
> reallocations and copying it has to use:
>
>   spiral2h =: (,:@i. , ] + [: |:@|. spiral2s) ` ((1 0$0)"_) @. (<:&0)
>   spiral2s =: ,:@i. , ] + [: |:@|. [: spiral2h <:
>   (spiral2 =: (*: - spiral2s)"0) 5
> 25 24 23 22 21
> 10  9  8  7 20
> 11  2  1  6 19
> 12  3  4  5 18
> 13 14 15 16 17
>   +/ (~.@:(<"1)@:(,.~,],.|.)@:i. { spiral2) 1001
> 669171001
>
> I posted the second solution (the arithmetic one) in perl only, so I
> have to translate it to J now.  This translation is very efficent
> because we don't compute all elements of the big spiral, only the
> diagonal ones.  (It's also a very fast way to compute the whole
> spiral.)
>
>   spiral3c =: 4 9 $ 4 0 _4 0 1 _1 1 0 0 0 4 0 _4 _1 5 1 _2 2 0 4 0 _4
> 1 7 1 _4 4
>   spiral3a =: 3 :0
> 'i j n' =: y
> g =: (*:i),(*:j),(n*i),(n*j),i,j,(*:n),n,:1$~$i
> t =: +/"_1 spiral3c *"1 _ g
> p =: (n<>:i+j) ++: i>j
> p} t
> )
>   spiral3 =: [: spiral3a (["0/~@:i. ; ]"0/~@:i. ; ])
>   spiral3d =: [: spiral3a (<"1@:|:@:~.@:(,.~,],.|.)@:i. , <)
>   spiral3 5
> 25 24 23 22 21
> 10  9  8  7 20
> 11  2  1  6 19
> 12  3  2  5 18
> 13 12 11 10 17
>   spiral3d 5
> 25 9 1 5 17 21 7 3 13
>   +/ spiral3d 5
> 101
>   +/ spiral3d 1001
> 669171001
>
>
> Ambrus
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>


More information about the Programming mailing list