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: Dot Calculator 這題是用"."點的數目表示數字,並給operator做運算。 我的寫法是: return function ( equation ) local temp , s1 , s2 , op = 0 , 0...