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:
- In Lua,
false
andnil
are consideredfalse
. All other values, including0
and empty strings, are consideredtrue
.
或是直接使用第三方的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
沒有留言:
張貼留言