Code Abbey -- Collatz sequence

Oforth examples. Feel free to post your own code.

Code Abbey -- Collatz sequence

Postby sotolf » 11 Sep 2015 09:01

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.
sotolf
 
Posts: 55
Joined: 30 Jul 2015 15:53

Return to Oforth examples

Who is online

Users browsing this forum: No registered users and 1 guest

cron