LoginSignup
0

More than 5 years have passed since last update.

オフラインリアルタイムどう書く第三回の参考問題解答(Lua)

Posted at

オフラインリアルタイムどう書く第三回の参考問題
http://qiita.com/items/ebd8a56b41711ba459f9

…のgroovyでの回答例
https://gist.github.com/3381668

…をLuaに翻訳してみました。

Baseball = 
{
    s = function(self)
        self.strike = self.strike + 1
        if 2 < self.strike then
            self.strike = 0
            self:o()
        end
    end,

    b = function(self)
        self.ball = self.ball + 1
        if 3 < self.ball then
            self:h()
        end
    end,

    o = function(self)
        self.out = self.out + 1
        if 2 < self.out then
            self.strike = 0
            self.ball   = 0
            self.out    = 0
        end
    end,

    f = function(self)
        if self.strike < 2 then
            self:s()
        end
    end,

    h = function(self)
        self.strike = 0
        self.ball   = 0
    end,

    p = function(self)
        self:h()
        self:o()
    end,

    resolve = function(self, it)
        self.strike = 0
        self.ball   = 0
        self.out    = 0
        local result = ""
        for i = 1, #it do
            self[it:sub(i, i)](self)
            result = result .. "," .. self.out .. self.strike .. self.ball
        end
        return result:sub(2)
    end
}

test =
{
    ["sss"] = "010,020,100",
    ["bbbb"] = "001,002,003,000",
    ["ssbbbb"] = "010,020,021,022,023,000",
    ["hsbhfhbh"] = "000,010,011,000,010,000,001,000",
    ["psbpfpbp"] = "100,110,111,200,210,000,001,100",
    ["ppp"] = "100,200,000",
    ["ffffs"] = "010,020,020,020,100",
    ["ssspfffs"] = "010,020,100,200,210,220,220,000",
    ["bbbsfbppp"] = "001,002,003,013,023,000,100,200,000",
    ["sssbbbbsbhsbppp"] = "010,020,100,101,102,103,100,110,111,100,110,111,200,000,100",
    ["ssffpffssp"] = "010,020,020,020,100,110,120,200,210,000"
}

for k, v in pairs(test) do
  local r = Baseball:resolve(k)
  print("source   = " .. k)
  print("expected = " .. v)
  print("actual   = " .. r)
  print(r == v)
  print()
end

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
0