Hi all!

 

            I'm a J newbie and have a quick programming question.

 

            But first, as a way of introduction, my name is Glenn Lewis
and I am the son of Charles Lewis, who co-authored a book called
something like "A Journey Into APL by Lewis and Clark: An Interactive
Approach", many years ago.  A friend of mine knew that APL was the first
language that I ever programmed in, so he pointed me to J, and I'm
giving it a whirl.  That same friend pointed out Project Euler
(http://projecteuler.net/) which appears to be an excellent launch pad
for learning a new language.

 

            So I was working on Problem # 58, and got stuck.  I've
worked my way through the primer, but J is still quite fuzzy in my head.
Here's what I have so far:

 

NB. Euler58.ijs

NB.

NB. Starting with 1 and spiraling anticlockwise in the following way, a
square spiral with side length 7 is formed.

NB.

NB. 37 36 35 34 33 32 31

NB. 38 17 16 15 14 13 30

NB. 39 18  5  4  3 12 29

NB. 40 19  6  1  2 11 28

NB. 41 20  7  8  9 10 27

NB. 42 21 22 23 24 25 26

NB. 43 44 45 46 47 48 49

NB.

NB. It is interesting to note that the odd squares lie along the bottom
right diagonal, but what is more interesting is that 8 out of the 13
numbers lying along both diagonals are prime; that is, a ratio of 8/13
62%.

NB.

NB. If one complete new layer is wrapped around the spiral above, a
square spiral with side length 9 will be formed. If this process is
continued, what is the side length of the square spiral for which the
ratio of primes along both diagonals first falls below 10%?

 

brds =: 3 : 0 NB. Calculates the numbers in the bottom right diagonal
(0=center)

*: 1 + 2 * y

)

 

diagonals =: 3 : 0 NB. Calculates all the numbers on the diagonals of
the spiral at level 'y'

t1 =. 4 $ brds y

t2 =. 0 2 4 6 * y

t1 - t2

)

 

 

            If I run 'brds', like so...

 

   brds i. 10

1 9 25 49 81 121 169 225 289 361

 

it seems to work fine.  And if I run 'diagonals' with just a scalar, it
works fine:

 

   diagonals 0

1 1 1 1

   diagonals 1

9 7 5 3

   diagonals 2

25 21 17 13

 

   But if I try to get all diagonals from the first 10 rings of the
spiral, I get:

 

   diagonals i. 10

|length error: diagonals

|   t2=.0 2 4 6    *y

 

   I understand what the problem is (the length mismatch), but don't
know how to fix it...  I need to take each scalar in y one-at-a-time...
and I tried all sorts of combinations of " (double quote) to treat the
right hand side like a rank 0 input, but couldn't get it to work.

 

            Any ideas?

 

            Thanks!

-- Glenn Lewis

 

----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to