想象一下这种情况:
输入
数字数组和输出的边界范围:
numbers = [20, 50]
range = [0, 200]
的输出
所有可能的输入数组元素总和的组合限制在边界范围内:
output = [20, 40, 50, 70, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
所以我的问题是我如何实现这一目标?
答案 0 :(得分:1)
给定一个Int(s)
数组和一个封闭范围
let numbers = [20, 50]
let range: ClosedRange = 0...200
以下函数返回满足以下条件的每个可能整数的Set
:
numbers
func combs(range:ClosedRange<Int>, numers: [Int], value: Int = 0) -> Set<Int> {
guard value <= range.upperBound else { return [] }
return numbers.reduce(Set<Int>()) { results, num -> Set<Int> in
var results = results
let newValue = value + num
if range ~= value {
results.insert(value)
}
return results.union(combs(range: range, numers: numbers, value: newValue))
}
}
let nums = Array(combs(range: range, numers: numbers)).sorted()
[0,20,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200]
答案 1 :(得分:1)
这是一种可能的方法,它以递增的顺序给出数字。 它使用两个数组(&#34;队列&#34;)来跟踪仍然必须的值 被添加到输出序列。 (这基本上与方法相同 &#34;动态编程方法&#34;在"Ugly Numbers"中生成所谓的汉明数字。)
let x = 20
let y = 50
let limit = 200
var xq: [Int] = []
var yq: [Int] = []
var current = 0
while current <= limit {
print(current, terminator: ", ")
xq.append(current + x)
yq.append(current + y)
current = min(xq[0], yq[0])
if xq[0] == current { xq.remove(at: 0) }
if yq[0] == current { yq.remove(at: 0) }
}
print()
输出:
0, 20, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200,