Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

The Towers of Hanoi in Ruby

   1  
   2  # based on: The shortest and "mysterious" TH algorithm,
   3  # http://hanoitower.mkolar.org/shortestTHalgo.html
   4  #
   5  # Further references:
   6  # - http://en.wikipedia.org/wiki/Tower_of_Hanoi
   7  # - http://hanoitower.mkolar.org/HTonWebE.html
   8  # - http://www.google.com/search?q=towers%20of%20hanoi%20Apostolos%20Syropoulos
   9  # - http://www.kernelthread.com/hanoi/
  10  # - http://www.kernelthread.com/hanoi/html/rb.html
  11  
  12  n = 5 
  13  x = 1
  14  
  15  ar = []
  16  
  17  start_time = Time.now
  18  
  19  while x < (1 << n)
  20        fr=(x&x-1)%3;
  21        to=((x|x-1)+1)%3;
  22        ar.push(fr,to)
  23        puts "move from pole #{fr} to pole #{to}"
  24        x += 1
  25  end
  26  
  27  p ar
  28  
  29  p Time.now - start_time

hanoi.scm

// Solves the Towers of Hanoi puzzle.

   1  
   2  ; Andrew Pennebaker
   3  ; 9 Feb 2007
   4  ; License: GPL
   5  ; URL: http://snippets.dzone.com/posts/show/3492
   6  
   7  (define *start* 0)
   8  (define *aux* 1)
   9  (define *end* 2)
  10  
  11  (define hanoi
  12  	(lambda (n start aux end)
  13  		(if (= n 1)
  14  			(list start end)
  15  			(append
  16  				(hanoi (- n 1) start aux end)
  17  				(list start aux)
  18  				(hanoi (- n 1) aux start end)))))
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS