2025年10月13日 星期一

Lua裡, A and B or C, 即是C++的 A ? B : C

 7 kyu: Blowing Birthday Candles

這題很簡單,我在解這題時額外寫了一個簡單的函式,
後來發現用A and B or C的lua語法,就可以達成函式所做的事情,
這個語法,相當於C/C++裡的A ? B : C
也就是A的條件正確的話,回傳B,反則回傳C
用在Python 3的話,也相當於
B if A else C

完整程式碼如下:
local function blow_candles(str)
  local a = 0
  local i = 1
  local s = {}
  for i = 1, #str do
    s[i] = tonumber(str:sub(i, i))
  end
  i = 1
  while i <= #str do 
    local neg = s[i]
    if neg > 0 then
      for j = i, i+2 do
        if j > #str then
          break
        else
          s[j] = s[j] - neg > 0 and s[j] - neg or 0
        end
      end
      a = a + neg
    end
    i = i + 1
  end
  return a
end

return blow_candles

沒有留言:

張貼留言

Lua, 7 kyu, 排隊問題

 7 kyu,  Lost Lineup 這題很簡單,我一開始實作的方法是: local function find_lineup ( distances ) local a , d = {}, # distances for i = 1 , d do ...