2025年10月15日 星期三

7 kyu: Ordered Count of Characters using Lua

 7 kyu: Ordered Count of Characters

這題很簡單,要做的只是計算string中各字元出現的次數。
我一開始寫的code如下:
local solution = {}

function solution.ordered_count(inp)
  local a, aa, orderkey = {}, {}, {}
  for i = 1, #inp do
    local c = inp:sub(i, i)
    if nil == a[c] then
      a[c] = 1
      table.insert(orderkey, c)
    else
      a[c] = a[c] + 1
    end
  end
  for i, v in ipairs(orderkey) do
    table.insert(aa, {orderkey[i], a[orderkey[i]]})
  end
  return  aa
end

return solution

後來看了別人的寫法後,
發現可以寫的更精簡一點,
只要宣告兩個table結構即可。
一個table aa存答案,
一個table a, key存字元,value存table aa的index.
改寫如下:
local solution = {}

function solution.ordered_count(inp)
  local a, aa = {}, {}
  for i = 1, #inp do
    local c = inp:sub(i, i)
    if nil == a[c] then
      table.insert(aa, {c, 1})
      a[c] = #aa
    else
      aa[a[c]][2] = aa[a[c]][2] + 1
    end
  end
  return  aa
end

return solution

2025年10月14日 星期二

Lua, table[-1] 並不像Python可以存取最後一個元素

 7 kyu: Pull your words together, man!

這題很簡單,但是我在寫code時,
想存取table資料結構的words裡面的最後一個元素,
發現不能用words[-1] (words[-1] 為 nil)
這點跟Python 3的list不同,
可行的替代寫法是
words[#words]

我寫的完整code如下:
return {
  sentencify = function(words)
    words[#words] = words[#words] .. "."
    words[1] = string.upper(string.sub(words[1], 1, 1)) .. string.sub(words[1], 2)
    return table.concat(words, " ")
  end
}
別人寫的比較精簡,如下:
return {
  sentencify = function(words)
    return table.concat(words, ' '):gsub('^.', string.upper)..'.'
  end
}

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

7 kyu: Ordered Count of Characters using Lua

 7 kyu: Ordered Count of Characters 這題很簡單,要做的只是計算string中各字元出現的次數。 我一開始寫的code如下: local solution = {} function solution.ordered_count ( in...