第18回オフラインリアルタイムどう書くの参考問題をRubyで解く


問題はこちら。
http://nabetani.sakura.ne.jp/hena/ord18mafovafo/

def solve(q)
  h1 = {'L'=>'V','J'=>'V','Z'=>'mV','U'=>'VV','S'=>'Vm'}
  h2 = {'L'=>'m','J'=>'m','Z'=>'mV','U'=>'mm','S'=>'Vm'}
  folds = ''
  isLeft = true
  q.chars.each{|c|
    fw = (isLeft ? h1 :  h2)[c]
    folds.chars.each_with_index{|fold, i|
      fw += fold
      if ((isLeft and i.odd?) or (!isLeft and i.even?))
        fw += h1[c]
      else
        fw += h2[c]
      end
    }
    folds = fw
    case c
    when 'L'
      isLeft = false if isLeft
    when 'J'
      isLeft = true unless isLeft
    when 'U'
      isLeft = !isLeft
    end
  }
  folds
end

DATA.readlines.each do |line|
  no,q,a = line.chop.split(/\s+/)
  ans = solve(q)
  print no + "\t" + ans
  puts ans == a ? ' o' : ' x'
#break
end
__END__
0   JZ  mVVmV
1   J   V
2   L   V
3   Z   mV
4   U   VV
5   S   Vm
6   JL  VVm
7   JS  VmVVm
8   JU  VVVmm
9   LU  mmVVV
10  SL  VVmmV
11  SS  VmVVmmVm