Page 1 of 1

Code Abbey -- Collatz sequence

PostPosted: 11 Sep 2015 09:01
by sotolf
This is one of the classics, I have done it in a lot of languages by now. Find the length of a collatz sequence.
We start out with a number and if it's even it gets devided by 2 if it's odd it gets multiplied with 3 and one is added.
This then gets repeated until the number is 1, and we count how many steps it took to get there.

Code: Select all
: getLn { System.Console askln }                                               
: pprint { apply(#.) printcr }                                                 
: getInput { getLn drop getLn }                                 
: parseLine { words map(#asInteger) }                                           

: clzStep { dup isEven ifTrue: [ 2 / ] else: [ 3 * 1 + ] }
: lenClz { |len| 0 ->len while(dup 1 <>) [ clzStep len 1 + -> len ] drop len }

getInput parseLine map( #lenClz ) pprint


Works quite nicely.