免责声明:swift 新手。
我有一个简单的骰子游戏,需要将骰子上显示的数字与棋盘上剩余的方 block (整数)相匹配。我可以通过数组进行枚举以进行直接匹配,但是,如果骰子显示的数字大于单独的瓷砖,我需要检查这些瓷砖(整数)以任何组合是否也可以匹配显示的骰子上的数字。
for 循环、do-while、枚举.....脑袋开始爆炸了。下面的示例显示了我认为我要去的地方的浓缩版本。任何帮助都会很棒。
可变数组 = [1,2,3,4]
函数 roundOver(){
var ran = Int(arc4random_uniform(7) % 7 + 1)
for (index,value)in enumerate(array) {
if value == ran {
println("match")
} else if value != ran {
do {..........huh?
请您参考如下方法:
如果我正确理解你的问题,你需要解决 "Subset sum problem" :
Given a set
Sand a numberx, is there a subset ofSwhose sum is equal tox?
这个问题可以用“动态规划”有效地解决,如 维基百科文章。对于小集合,可以使用蛮力算法 简单地尝试所有可能的子集。这可以递归地写成
func isSummableTo(array: [UInt], _ value: UInt) -> Bool {
if value == 0 {
// We have reached the exact sum
return true
} else if array.count == 0 {
// No elements left to try
return false
}
// Split into first element and remaining array:
var array1 = array
let first = array1.removeAtIndex(0)
// Try to build the sum without or with the first element:
return isSummableTo(array1, value) || (value >= first && isSummableTo(array1, value - first))
}
(这里我假设你只使用非负整数。)
例如
isSummableTo([1, 3, 5, 10], 6) == true
因为 1 + 5 = 6,并且
isSummableTo([1, 3, 5, 10], 7) == false
因为没有数字 1、3、5、10 的子集总和为 7。
