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


問題は
http://nabetani.sakura.ne.jp/hena/ord28spirwa/

def solve(q)
  ds,days = q.split(':')
  n,e,s,w = ds.split(',').map(&:to_i)
  done = [[0,0]]
  n.times{|i| done << [0,i+1]}
  e.times{|i| done << [i+1,0]}
  s.times{|i| done << [0,-i-1]}
  w.times{|i| done << [-i-1,0]}
  x,y = 1,1
  done << [1,1]
  d = :E
  days.to_i.times{
    case d
    when :E
      x += 1
      d = :S unless done.include?([x,y-1])
      d = :N if done.include?([x+1,y])
    when :S
      y -= 1
      d = :W unless done.include?([x-1,y])
      d = :E if done.include?([x,y-1])
    when :W
      x -= 1
      d = :N unless done.include?([x,y+1])
      d = :S if done.include?([x-1,y])
    when :N
      y += 1
      d = :E unless done.include?([x+1,y])
      d = :W if done.include?([x,y+1])
    end  
    done << [x, y]
  }
  d.to_s
end

DATA.readlines.each do |line|
  no,q,a = line.strip.split(/\s+/)
  ans = solve(q)
  print no + "\t" + ans
  puts ans == a ? ' o' : ' x'
end
__END__
0   2,3,5,4:85  S    
1   1,2,3,4:1   E    
2   1,2,3,4:2   S    
3   1,2,3,4:3   S    
4   1,2,3,4:4   W    
5   1,2,3,4:27  E    
6   1,2,3,4:63  E    
7   1,2,3,4:40  W    
8   1,4,3,2:40  S    
9   3,3,3,3:30  S    
10  3,3,3,3:31  E    
11  3,3,3,3:32  E    
12  3,3,3,3:70  S    
13  3,3,3,3:71  E    
14  3,3,3,3:72  E    
15  1,1,1,1:7   N    
16  1,2,1,1:7   W    
17  1,6,1,1:7   S    
18  1,8,1,1:7   E    
19  1,1,1,1:30  N    
20  1,2,1,1:30  W    
21  1,5,1,1:30  S    
22  1,8,1,1:30  E    
23  9,9,9,9:99  W    
24  5,6,3,8:3   E    
25  5,8,1,1:11  W    
26  2,8,1,2:18  S    
27  3,2,3,1:20  N    
28  3,3,8,1:28  N    
29  2,5,1,2:32  E    
30  2,5,1,6:33  E    
31  1,2,5,7:34  N    
32  3,6,5,6:36  E    
33  6,2,8,1:39  S    
34  3,1,2,3:41  W    
35  1,1,3,4:45  W    
36  1,3,1,2:46  N    
37  4,4,4,4:49  W    
38  3,1,4,4:55  N    
39  6,6,2,1:56  W    
40  3,2,1,2:59  S    
41  2,7,7,1:60  S    
42  3,1,1,1:63  N    
43  4,6,4,1:78  E    
44  7,5,3,6:79  W    
45  7,8,3,1:81  E    
46  3,2,5,2:82  S    
47  1,1,3,4:84  N    
48  7,4,1,5:88  S    
49  3,6,5,3:89  S    
50  1,4,2,3:92  N    
51  1,3,4,5:93  W    
52  2,4,8,1:94  W    
53  3,6,1,7:99  S