list - 检查多个位置的值并仅在源唯一时返回匹配项
问题描述
假设我有一个供应商列表:Asda、Tesco、Spar。
我有一个来源列表(或类似的供应商):家乐氏、吉百利、雀巢、强生、帮宝适、Simple 等(有大约 20 个定义的列表)。
数据流的其他地方。对于多个不同的事情,我返回一个结果,对于每个供应商来说是/否。
例如:阿斯达:ukOnly = “是”;晶石:ukOnly =“否”等。
在这个特定的部分,我正在整理结果。
大多数情况下,供应商的来源是否重叠并不重要。所以我只能说:
function concatResults(x) -- concats the result of "x" for each vendor
local pathAsda = *this is where I call the path location specific to Asda*
local pathTesco = *this is where I call the path location specific to Tesco*
local pathSpar = *this is where I call the path location specific to Spar*
if (pathAsda == "Yes" or pathTesco == "Yes" or pathSpar == "Yes") then
return "Yes"
else
return "No"
end
end
ukOnlyAgr = concatResults("ukOnly")
伟大的!
现在,假设我想做一些更复杂的事情。
我想知道有多少独特的供应商提供巧克力和麦片。下面的示例正在进一步用于生成事实的过程,前提suppliesSweet
是至少涉及两个来源(供应商)并且他们必须至少提供巧克力。这将分别为每个供应商完成(请假设我已经根据输入数据定义了我的变量:
if (suppliesChoc > 0 and suppliesCereal > 0 and numSources > 1) or (suppliesChoc > 1) then
then suppliesSweet = "Yes"
else suppliesSweet = "No"
end
还不是问题。
当我尝试跨供应商汇总这些结果时,问题就出现了(就像我之前所做的那样ukOnly
)。
我已经使用了以下功能:
table.contains = function(t, value) -- Finds if "value" exists inside the table "t"
for index = 1, #t do
if t[index] == value then
return index
end
end
end
并正在考虑创建这个:
table.overlap = function(t,g) -- Finds if tables "g" and "t" have any overlapping values
for i=1,#t do
if table.contains(g,t[i]) then
return true
else
return false
end
end
end
但我只是不确定从那里去哪里。
您可以假设我已经获得了每个供应商的唯一来源列表,我不介意我们是否过于严格。即,如果两个供应商之间有任何来源重叠,这将使整个结果无效。
您还可以假设我有每个“事实”:suppliesChoc
、、suppliesCereal
和分别返回numSources
的suppliesSweet
每个供应商。
解决方案
I believe your looking for the intersection of two sets.
One set being your vendor's suppliers and the other being the suppliers who supply sweets.
local vendors = {
Asda = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true, Pampers = true, Simple = true},
Tesco = {Kellogg = true, Cadbury = true, Nestle = true, Johnsons = true},
Spar ={Nestle = true, Johnsons = true, Pampers = true, Simple = true}
}
function intersection(s1, s2)
local output = {}
for key in pairs(s1) do
output[#output + 1] = s2[key]
end
return output
end
local sweetSuppliers = {Kellogg = true, Cadbury = true, Nestle = true}
for name, suppliers in pairs(vendors) do
local result = intersection(sweetSuppliers, suppliers)
print(name .. " has " .. #result .. " sweets suppliers")
end
Here are some examples of a libraries for handling sets:
Both can give you an idea of how you can use sets to accomplish things like intersection, and much more
推荐阅读
- sql - SQL 排除条件值
- spring-boot - Spring 如何知道在哪里搜索组件或 Bean?
- java - 在线程“main”java.lang.NoClassDefFoundError:scala/Function1$class 中获取 Akka 流代码时出错
- python - 创建一个可以创建多个类的python脚本
- python - 旋转的图片不显示在烧瓶中
- python - 当我打开 Jupyter 时,如何将 Anaconda 中的不同环境设置为默认使用不同版本的 Python?
- spring-boot - 记录 Web 依赖的条件评估报告
- java - JavaFx:如何拆分字符串并在 UI 上显示拆分字符(“:”)
- typescript - 如何测试已被调用或未调用的函数
- android - React - 错误:包 expo.modules.updates 不存在