From: Sebastian Hungerecker Date: 2009-09-23T20:30:00+09:00 Subject: Re: Mini Parser Am Mittwoch 23 September 2009 11:55:24 schrieb Karthikeyan Balasubramanian: > WRITE basically write's string after the command and UNDO will undo N > number of line preceding it. Complexity here is last UNDO has to UNDO > the previous undo's work. Obviously you need to find out which WRITEs actually execute, before producing any output, since it's hard to undo output that's already been printed to the screen. Since there are no conditional statements, you know that all the UNDOs will execute, so you can execute all the UNDOs in phase 1 and then execute the WRITEs that haven't been UNDOne in PHASE 2. The problem of UNDOing UNDOs can be solved by simply going through the UNDOs in reverse order. This should work: commands = File.readlines(sourcefile).map {|line| line.chomp.split(/\s+/, 2)} commands.reverse! undos = 0 commands.reject! do |command, argument| if undos > 0 undos -= 1 true elsif command == "UNDO" undos = argument.to_i true else false end end commands.reverse! commands.each do |command, argument| print argument, " " end