Loading...
 

lang5 Blog

Brain teaser

Published by ulmann on 2011-09-08
The examples collection now contains a true brain teaser - a small lang5-program that generates a Ulam-spiral. :-) Can you figure out how it works?
: ulam_spiral
  : seq
    : zip(*,*) 2 compress " " join ;
    : subsubseq swap 2 2 compress reshape ;
    : subseq
      0 pick     [0 1]  subsubseq 1 pick     [1 0]  subsubseq 
      2 pick 1 + [0 -1] subsubseq 3 pick 1 + [-1 0] subsubseq 
      5 roll drop append append append
    ;

    dup 2 reshape 1 compress
    over iota 2 * 1 + "subseq append" 3 pick reshape zip execute
    over 2 * [0 1] subsubseq append '+ spread
  ;

  : print_line(*)
    : rpl(*) dup not if drop "" then ;
    rpl "\t" join . "\n" .
  ;

  seq swap 2 * 1 + 2 ** iota 1 + dup prime swap and swap scatter
  'print_line apply drop
;

4 ulam_spiral


The output of this program looks like this (the tricky part of the program is the generation of the number spiral - please note the use of the and in the second last line of the main function to select only prime numbers in the array):
73						79		
	43				47			
71				23				
	41		7					
		19			2	11		53
			5		3		29	
67		17				13		
	37						31	
				61		59