*collatz=:(1 0=2|])#(3*1+]),2%~]**
*
collatz 4
2
collatz 5
18
collatz _4
_2
collatz _5
_12
Test for odd/even is *2|n* returning 1 for odd and 0 for even 1 0=2|n
will return 1 0 for odd and 0 1 for even
The (3*1+n) and n%2 terms are a two element result vector
if odd, *1 0 *# returns the odd result and if even *0 1 #* returns the
even result.
In this case I started with the basic *(3*n+1),n%2* vector and then
used *1 0= 2|n* times this(residue is 1 for odd and 0 for even numbers)
the result is*(1 0=2|y) # (3*1+y),y%2* which works
I wrote this as an explicit verb *s=: 13 : '(1 0=2|y)#(3*1+y),y%2'
*and typed *s* to get a tacit form *(1 0 = 2 | ]) # (3 * 1 + ]) , 2 %~ ]
*generated by J*
*
attached *collatz=:* to the front and that was it.
note that the *y* is replaced by *]* and the *y%2* is expressed
using*2%~] *J wants the*]* on the right of this operation and *~*does this
There are other variations on this but this is the simplest I came up with.
I classify myself as a beginner but I have an APL background and long
ago found C and relatives awkward I do think it is harder to come from
C/C++/Java to J than from APL to J - the thinking is different To me
C++ is oriented towards detailed instructions for the compiler (much of
this is done by the interpreter in J or APL) The problem comes first
in J and more times than not - use of arrays can eliminate a lot of if's
and loops.
Don Kelly
On 03/03/2014 8:30 AM, Jon Hough wrote:
Beginner question again.I quick task I set myself was to write ONE ITERATION of
the Collatz function for a given positive
integer.http://en.wikipedia.org/wiki/Collatz_conjecture
So my verb is supposed to do 3*n+1 if n is odd and n/2 if n is even.In a more
imperative/OOE based language (C/C++/Java) I could write this in less than a
minute. Unfortunately, I fell at the very first hurdle in J.
I originally wrote my tacit verb for even ints:collatz_even =.2&(%~)
collatz_even 4
2
This works, but I had a terrible time trying to put the brackets in the right place. I am
not sure why %~ needs to be bracketed. Won't J parse %~ as dyadic and "know"
that the left operand is 2?
Next I tried to do the case for odd n:
collatz_odd =. 1&+@(3&*) collatz_odd 3
10
That seems to work ok.Now I am not sure how to do an if statement in J. In plain English
I want "If n is even do collatz_even else do collatz_odd".The verb I wrote to
test for even-ness is
ones =. {:@#: NB. Finds the ones column values. 1 => odd, 0=> even
1 = ones 2
0
So I have a test but I am not sure how to utilize this test. How should I go about
doing:"If n is even do collatz_even else do collatz_odd"?
Thanks and regards,Jon
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm