Help us understand the problem. What is going on with this article?

第一回 オフラインリアルタイムどう書くの解答例。Lua で。

More than 5 years have passed since last update.

Lua 5.2でビット演算ライブラリが追加されているのを思い出したので http://qiita.com/items/5dfd820a4047376c3bf3 をLuaで書いてみました。Lua 5.2用です。Lua 5.1では動作しませんのでご注意を。

C++版と違い、「o」「x」のそれぞれに16ビットを割り当てて32ビットで演算してます。反則の判定は32ビットの値を16ビット回転させ上位16ビットと下位16ビットを入れ替えて排他的論理和をとることでおこなっています。

a and b or ca ? b : c と、だいたい同じ意味です。

要素のインデクスが1から始まるとわかっていても一時はまりました。この仕様はもう変えようがないのかなぁ…。

Lua
zero = string.byte("0", 1)
side = { [0] = "x", [1] = "o" }

function ticktacktoe(s)
  local b   = { 0x00b600b6, 0x00ee00ee, 0x005e005e,
                0x00f500f5, 0x002d002d, 0x00dd00dd,
                0x00730073, 0x00eb00eb, 0x009b009b }
  for i = 1, 9 do
    n = s:byte(i) - zero
    if bit32.bxor(b[n], bit32.rrotate(b[n], 16)) ~= 0 then
      return "Faul: " .. side[(i + 1) % 2] .. " won."
    end
    b[n] = bit32.bor(b[n], ((i % 2) == 1) and 0x000000ff or 0x00ff0000)
    if bit32.band(table.unpack(b)) ~= 0 then
      return side[i % 2] .. " won."
    end
  end
  return "Draw game."
end

for s in io.lines() do
  print(ticktacktoe(s))
end
emattsan
ソフトウェアエンジニア、言語オタク
http://d.hatena.ne.jp/E_Mattsan/
esm
We build applications which work well and make customers happy.
http://www.esm.co.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした