Lindenmayer with ruby

  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.
  • warning: realpath() [function.realpath]: SAFE MODE Restriction in effect. The script whose uid is 1005 is not allowed to access /tmp owned by uid 0 in /var/www/sites/sugree/codenone.com/subdomains/www/html/includes/file.inc on line 190.

โจทย์
http://www.codenone.com/node/242

ตึความ depth แบบนี้
สมมติ rules คือ
Axiom: B
Rules:
B -> F[-B]+B
F -> FF

depth == 0 -> result = B
depth == 1 -> result = F[-B]+B
depth == 2 -> result = FF[-F[-B]+B]+F[-B]+B
depth == 3 -> result = FFFF[-FF[-F[-B]+B]+F[-B]+B]+FF[-F[-B]+B]+F[-B]+B

class Linden
 
  attr_reader :axiom
 
  def initialize(axiom,rulesMap,length,angle)
    @axiom = axiom
    @rulesMap = rulesMap
    @angle = angle
    @length = length
  end
 
  def transform(str, depth)
    return str if depth == 0
    ret = ""
    str.each_byte do |b| 
      chr = b.chr
      if @rulesMap.key? chr
        ret << transform(@rulesMap[chr], depth-1)
      else
        ret << chr
      end
    end
    ret
  end
 
  def run(depth)
    @axiom = transform @axiom, depth
  end  
 
  def translate()
    ret = ""
    current_length = @length
    stack = []
    @axiom.each_byte do |c|
      case c.chr
        when 'F'
          ret << "DRAW_FORWARD #{current_length} "
        when 'G'
          ret << "MOVE_FORWARD #{current_length} "
        when '+'
          ret << "ROTATE CLOCKWISE #{@angle} "
        when '-'
          ret << "ROTATE COUNTERCLOCKWISE #{@angle} "
        when '['
          ret << "SAVE_STATE "
          stack.push current_length
        when ']'
          ret << "RECOVER_STATE "
          current_length = stack.pop
        when '|'
          current_length = current_length * 65 / 100
          ret << "DRAW_FORWARD #{current_length} "
      end
    end
    ret
  end
end

เวลา run ก็

linden = Linden.new('F',{'F'=>'|[-F]|[+F]F'},150,25)
linden.run(4)
puts linden.translate

แล้วเอา output ไป feed ให้โปรแกรม turtle

ย้าย Codenone

ประกาศย้าย Codenone ไปใช้ Forum ของ Blognone แทนครับ ตามไปตั้งกระทู้ต่อได้ที่ Codenone Forum (รายละเอียดอ่านจากกระทู้ ย้าย Codenone ไปรวมกับ Blognone)

กระทู้เก่าๆ จะย้ายตามไปในภายหลัง ตอนนี้ปิดการโพสต์กระทู้ไว้ เหลือไว้เฉพาะอ้างอิงเท่านั้น