1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オフラインリアルタイム - Tick-Tack-Toe(2012.7.6の過去問)

Last updated at Posted at 2015-03-27

http://nabetani.sakura.ne.jp/hena/1/
オフラインリアルタイムの問題を Ruby で挑戦。

# https://yhpg.doorkeeper.jp/
# http://nabetani.sakura.ne.jp/hena/1/

RULES = [
  '...******',
  '***...***',
  '******...',
  '.***.***.',
  '**.*.*.**',
  '.**.**.**',
  '*.**.**.*',
  '**.**.**.'
]

FIRST_PLAYER = 'o'
SECOND_PLAYER = 'x'

def buttle(cell_list)
  [].tap { |tmp| cell_list.chars.each.with_index { |cell, index|
    player = index % 2 == 0 ? FIRST_PLAYER : SECOND_PLAYER
    sub_player = player == FIRST_PLAYER ? SECOND_PLAYER : FIRST_PLAYER

    return "Foul : #{sub_player} won." if tmp.include? cell

    tmp << cell
    player_tmp = tmp.select.with_index { |_cell, idx| idx % 2 == (index % 2 == 0 ? 0 : 1) }

    RULES.each do |rule|
      rule_index = rule.chars.map.with_index { |c, i| i if c == '.' }.compact
      player_index = player_tmp.map { |_tmp| _tmp.to_i - 1 }

      return "#{player} won." if (rule_index - player_index).size.zero?
    end

    return "Draw game." if tmp.size == 9
  }}
end

cell_list = [
  79538246,
  35497162193,
  61978543,
  254961323121,
  6134278187,
  4319581,
  9625663381,
  7975662,
  2368799597,
  18652368566,
  965715,
  38745796,
  371929,
  758698769,
  42683953,
  618843927,
  36535224,
  882973,
  653675681,
  9729934662,
  972651483927,
  5439126787,
  142583697,
  42198637563,
  657391482,
]

result_list = [
'x won.',
'x won.',
'x won.',
'x won.',
'x won.',
'Foul : x won.',
'Foul : x won.',
'Foul : x won.',
'Foul : x won.',
'Foul : x won.',
'o won.',
'o won.',
'o won.',
'o won.',
'o won.',
'Foul : o won.',
'Foul : o won.',
'Foul : o won.',
'Foul : o won.',
'Foul : o won.',
'Draw game.',
'Draw game.',
'Draw game.',
'Draw game.',
'Draw game.',
]

#cell_list = '42198637563'
#buttle(cell_list)
cell_list.each.with_index do |cell, index|
  p buttle(cell.to_s) == result_list[index]
end

オフラインリアルタイムは正規表現とか使うと短くなったり、早く実装できたりするみたい。次から頑張ろう

ソースコード

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?