Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

[REBOL] Re: "Towers of Hanoi" : Comments please

From: dockimbel:free at: 19-Feb-2001 19:49

Hi Renaud, Don't know if i have the "rebol coding spirit" :) but this is how i would write some parts of your script :
> init: func [ > "Initialisation of the hanoi block" > n [integer!] "Number of disc to use" > /local tmp > ][ > count: make integer! 0; > tmp: make block! [] > hanoi: make block! [] > for i 1 n 1 [tmp: append tmp i] > hanoi: reduce [tmp make block! 0 make block! 0] > ]
; /local tmp i [ i: count: 0 ; "make integer!" is not necessary. tmp: make block! n ; pre-allocate n item for the new block. loop n [ ; 'loop is easier to read and much faster. append tmp i ; tmp will be modify, no need to re-assign. i: i + 1 ] hanoi: reduce [tmp copy [] copy []] ]
> first2: func [ > "Return first item, otherwise 99999" > blk [block!] > ][ > if (length? blk) = 0 [return 99999] > return first blk > ]
[ either empty? blk [99999][first blk] ; you can see 'empty? as a shortcut to 'zero? 'length? ]
> move: func [ > "Move one disc from one stick to another - does not care of game's rules" > from [integer!] > to [integer!] > /local temp tmp > ][ > temp: make block! [[][][]]
you could also use : array/initial [3 1] []
> tmp: first pick hanoi from > for i 1 3 1 [ > poke temp i head either i = from [remove hanoi/:i] [either i = to [insert > head hanoi/:i tmp][hanoi/:i]] > ] > count: count + 1 > hanoi: copy temp > print [count ": move from" from "to" to " : " mold hanoi] > ]
Your code is a little hard to read here. You should indent it after reading the "Style Guide" part of the Rebol manual. (also, not sure that 'head is needed here.)
> play: func [ > "Play nb disc from one place to an other" > from [integer!] "Place to start from" > to [integer!] "Place to go to" > nb [integer!] "How many disc to move" > /local from_state to_state tmp n > ][ > tmp: pick [0 0 3 2 1] (from + to) > either ((length? pick hanoi from) > 0) [
either not empty? pick hanoi from [
> either nb = 1 [ > from_state: pick hanoi from > to_state: pick hanoi to > either (first2 from_state) < (first2 to_state) > > move from to > ][ > move to from > play from to 2 > ] > > play from tmp (nb - 1) > play from to 1 > play tmp to (nb - 1) > ] > ][ > print "Can't do that: nothing to move" > ] > ] > > ; init a game with 4 discs > init 4 > > ;play the game > play 1 3 4 >
Pretty good script for learning Rebol. (A quand une version /View ? ;) ) HTH, DocKimbel.