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

沒有留言:

張貼留言

Basic Blind Chess的兩大問題

 Basic Blind Chess已經好久沒更新了, Windows版可以獲得最好的遊戲体驗, 但是Android版的,不只是比較舊, 它其實存在兩大問題: 1. 拿子移動時,顯示怪怪的,只顯示前幾個移動的殘影。 這個只有在最早的版本,沒有這個問題, 但是最早的版本實機測試時,...