字典数组中的增量值

时间:2019-02-19 23:27:06

标签: arrays swift dictionary

我正在尝试计算特定数字在一组六个六面骰子中掷出的次数,以确定是否有3种,4种,等等。

我可以拉出每个滚动模具的面值,并将其与6面模具的面进行比较,但是无法获得“ qtyRolled”键/值来递增。

    func rollDice() {
    currentRoll.removeAll()

    for _ in currentDiceArray {
        let num: UInt32 = arc4random_uniform(UInt32(currentDieFaceArray.count))
        let currentDieData = currentDieFaceArray[Int(num)]
        let faceValue = currentDieData["faceValue"]
        currentRoll.append(faceValue as! Int)
    }
    print(currentRoll)
    getQtyOfDieFaces()
    //checkForScoringCombos()
}

func getQtyOfDieFaces() {
    for die in currentRoll {
        for dieData in currentDieFaceArray {
            var currentDieData = dieData
            let qtyRolled = currentDieData["qtyRolled"] as! Int
            let faceValue = currentDieData["faceValue"] as! Int
            print("faceValue: \(faceValue)")
            print("Die: \(die)")
            if faceValue == die {
                currentDieData["qtyRolled"] = qtyRolled + 1 as AnyObject
            }
        }
    }
    for currentDieData in currentDieFaceArray {
        print(currentDieData["qtyRolled"]!)
    }
}

这是我的数据结构

var currentDieFaceArray = [[String:AnyObject]]()
var currentDiceArray:[[String:AnyObject]] = [[:]]
var currentRoll: [Int] = []

1 个答案:

答案 0 :(得分:1)

除非您确实需要字典,否则我建议您放弃字典,因为您实际上只是在处理结构/类的属性。我将假设您正在使用currentDieFaceArray方法,以便可以将此泛型用于其他尺寸的非线性骰子面(例如,您可以使用面值为[1、4、6、4的四面骰子8])。如果不是这种情况,您可以通过简单的计数数组来进一步简化。但这是您的方法的一个示例(可能还有其他可能的优化方法)。

class DieFaceDefn
{
  let faceValue : Int
  var countThisRoll : Int = 0

  init(faceValue: Int)
  {
    self.faceValue = faceValue
  }
}


var diceFaces: [DieFaceDefn] = []
let numberOfCurrentDice = 5

func setupDice()
{
    diceFaces.append(DieFaceDefn(faceValue: 1))
    diceFaces.append(DieFaceDefn(faceValue: 2))
    ...
}

var currentRoll: [Int] = []
func rollDice()
{
  currentRoll.removeAll()
  diceFaces.forEach { $0.countThisRoll = 0 }

  for _ in 0..<numberOfCurrentDice
  {
    let num: UInt32 = arc4random_uniform(UInt32(diceFaces.count))
    let currentDieData = diceFaces[Int(num)]
    let faceValue = currentDieData.faceValue
    currentRoll.append(faceValue)
    currentDieData.countThisRoll += 1
  }
  print(currentRoll)
  diceFaces.forEach { print("\($0.faceValue): \($0.countThisRoll)") }
}