分类: WINDOWS
2008-08-25 22:50:44
class Ant attr_reader:posi def initialize(direction,position,speed) ##direction must be 1 or -1 @direct = direction @posi = position @spd = speed @tmintval = 1 end def getpposition() return @posi end def getdirect() if @direct == -1 return "<-" else return "->" end end def move() @posi += @spd*@tmintval*@direct end def turnback() @direct *= -1 end end |
require"ant_class" class Stick def initialize(length) @sticklen = length @Ants = Array.new() end def putants(directs,posits) for i in 0...posits.size() @Ants = Ant.new(directs,posits,5) end end ##因为蚂蚁的移动速度是5,所以相对和相背移动两种情况中, ##任何两个蚂蚁之间的相对速度都是10,又任何两只蚂蚁的开始距离间隔是10的倍数。 ##所以蚂蚁之间的距离只能是10的倍数。我们判断碰撞的方法就简单了 ##只需要判断坐标相同就是了。 def anymeet() for i in () if (i+1) == @Ants.size() break elsif (@Ants).getposition == @Ants[i+1].getposition @Ants.turnback() @Ants[i+1].turnback() puts "ant"+i+"meet"+"ant"+(i+1)+"at"+ @Ants.getposition else print "." end end end def anyout() for i in () if (@Ants).getposition >= @sticklen @Ants.delete_at(i) print "ant #{i} out" end if @Ants.getposition <= 0 @Ants.delete_at(i) print "ant #{i} out" end end end def isallout() if @Ants.size() == 0 return true else return false end end def showdirects() puts "directions:" @Ants.each do |ant| print ant.getdirect()+" " end puts "" end def showpositions() puts "positions:" @Ants.each do |ant| print ant.posi.to_s + " " end end def run() @time = 0 self.showdirects() self.showpositions() while !self.isallout @time += 1 puts @time @Ants.each {|ant| ant.move()} self.anymeet() self.anyout() end puts "========" puts "time = #{@time}" end end |
##### ##### require "stick_class" ###begin if __FILE__ == $0 directs = [-1,-1,-1,-1,-1] positions = [30,80,110,160,250] time = 0 st = Stick.new(300) #I hate this for i in 0...(2**5) if 0x10 & i == 0 directs[0]= -1 else directs[0] = 1 end if 0x08 & i == 0 directs[1]= -1 else directs[1]= 1 end if 0x04 & i == 0 directs[2] = -1 else directs[2] = 1 end if 0x02 & i == 0 directs[3] = -1 else directs[3] = 1 end if 0x01 & i == 0 directs[4] = -1 else directs[4] = 1 end puts "case #{i}" st.putants(directs,positions) st.run() end end |