2025年10月20日 星期一

Lua, 使用string:gsub("%b()", "")

7kyu, Valid Parentheses

 7kyu的題目,一樣不難。

是求Parentheses是否balanced?

我採用最基本的解法,如下:
local function valid_parentheses(paren_str)
  local s = 0
  for i = 1, #paren_str do
    local p = paren_str:sub(i, i)
    if ")" == p then
      s = s - 1
    elseif "(" == p then
      s = s + 1
    end
    if s < 0 then
      return false
    end
  end
  if 0 == s then
    return true
  else
    return false
  end
end

return valid_parentheses

別人是用string:gsub("%b()", "")來解,滿精簡的:

local function valid_parentheses(paren_str)
  return paren_str:gsub("%b()", "") == ""
end

return valid_parentheses

Note:

a pattern is the '%b', that matches balanced strings. Such item is written as '%bxy', where x and y are any two distinct characters; the x acts as an opening character and the y as the closing one. For instance, the pattern '%b()' matches parts of the string that start with a `(´ and finish at the respective `)´


Lua, 使用string.match的精簡解法

7 kyu: Regex validate PIN code

這題算很簡單,題目是求PIN碼是否正確,
PIN碼格式需為數字且長度為4或6個字元。
我的寫法如下:
local function validate_pin(pin)
  for i = 1, #pin do
    local s = pin:sub(i, i)
    if nil == tonumber(s) then
      return false
    end
  end
  if 4 == #pin or 6 == #pin then
    return true
  else
    return false
  end
end

return validate_pin

但是別人用string.match,可以很精簡就解出來了,

如下:

local function validate_pin(pin)
  return pin:match("^%d%d%d%d$") ~= nil or pin:match("^%d%d%d%d%d%d$") ~= nil
end
 

return validate_pin 


2025年10月19日 星期日

Lua, Set處理

7 kyu: Operations With Sets

這題不難,是要求兩個Set結構,
相同和不同部份的相關數量,
我簡單寫了一個沒效率的程式:
local function bfind(value, arr2)
  for i, v in ipairs(arr2) do
    if v == value then
      return i
    end
  end
  return nil
end
  
local function process_2arrays(arr1, arr2)
  local b = {}
  for i = 1, #arr1 do
    local j =  bfind(arr1[i], arr2)
    if j ~= nil then
      b[#b + 1] = arr1[i]
      table.remove(arr2, j)
    end
  end
  return {#b, #arr1 - #b + #arr2, #arr1 - #b, #arr2}
end

return process_2arrays

別人寫的比較有效率的程式如下:
local function process_2arrays(arr1, arr2)
  local n, s2 = 0, {}
  for _, x in pairs(arr2) do
    s2[x] = true
  end
  for _, x in pairs(arr1) do
    if s2[x] then n = n + 1 end
  end
  local n1, n2 = #arr1 - n, #arr2 - n
  return {n, n1 + n2, n1, n2}
end

return process_2arrays
Note:
  • Truthiness in Lua: 
    In Lua, false and nil are considered falseAll other values, including 0 and empty strings, are considered true.

或是直接使用第三方的Set API:
Set = require 'pl.Set'
local function process_2arrays(arr1, arr2)
  local s1 = Set(arr1)
  local s2 = Set(arr2)
  return { #(s1*s2), #(s1^s2), #(s1-s2), #(s2-s1) }
end

return process_2arrays

Lua, 使用string:gsub("%b()", "")

7kyu, Valid Parentheses  7kyu的題目,一樣不難。 是求Parentheses是否balanced? 我採用最基本的解法,如下: local function valid_parentheses ( paren_str ) local s =...