【问题标题】:How to fill 2dimensional array with custom objects? swift如何用自定义对象填充二维数组?迅速
【发布时间】:2019-06-26 08:19:51
【问题描述】:

我尝试在有网格板和鱼和逆戟鲸等角色的地方制作项目。我创建了 Animal 父类和两个继承动物的子类。我想用 5% 的逆戟鲸和 35% 的鱼来填充板 (n * m)。如何用逆戟鲸和鱼填充网格?在这里,我尝试用数字填充板子。

class Animal {


}
class Fish: Animal{
}
class Orca:Animal{
}
class Board{
private var content: [[Int?]]
private static func setupForNewGame(width: Int,height: Int)->[[Int]]{

    var matrix:[[Int]] = Array(repeating: Array(repeating: 0, count: width), count: height)
    let cellCount = width * height

    var penguinCount = Double(round(Double(cellCount) * 50.0 / 100.0))
    var grampusCount = Double(round(Double(cellCount) * 5.0 / 100.0))

    var arr:[Int] = Array(repeating: 0, count: cellCount)
    for i in 0...cellCount - 1{
        if (penguinCount > 0){
            arr[i] = 1
            penguinCount = penguinCount - 1
        }else if (grampusCount > 0){
            arr[i] = 2
            grampusCount = grampusCount - 1
        }else{
            arr[i] = 0
        }
    }
    let shuffledArr = arr.shuffled()
    var counter = 0
    for i in 0...width - 1{
        for j in 0...height - 1{
           matrix[i][j] = shuffledArr[counter]
            counter = counter + 1
        }

    }

    return matrix

}
}

【问题讨论】:

  • 用自定义对象填充二维数组需要check this link
  • 注意:0...width - 1 在 Swift 中最好写成 0 ..< width

标签: arrays swift oop grid


【解决方案1】:

声明[[Animal?]]类型的matrix数组并使用nil而不是0

class Board {
    private var content: [[Animal?]] = []
    private static func setupForNewGame(width: Int,height: Int)->[[Animal?]] {

        var matrix:[[Animal?]] = Array(repeating: Array(repeating: nil, count: width), count: height)
        let cellCount = Double(width * height)

        let fishCount = Int(cellCount * 35.0 / 100.0)
        let orcaCount = Int(cellCount * 5.0 / 100.0)

        var arr:[Animal?] = Array(1...fishCount).map { _ in Fish() } + Array(1...orcaCount).map { _ in Orca() } + Array(repeating: nil, count: Int(cellCount)-fishCount-orcaCount)
        arr = arr.shuffled()

        var counter = 0
        for i in 0...width - 1{
            for j in 0...height - 1{
                matrix[i][j] = arr[counter]
                counter = counter + 1
            }
        }
        return matrix
    }
}

【讨论】:

  • arr 将没有足够的项目来填充 matrix,因为它只有 40% 大。
  • @vacawama 是的。其他元素将为 nil
  • 但是在填充矩阵时会不会用完元素导致索引超出范围错误?
  • 现在你的生物被卡在矩阵的开始处。将足够多的 nil 放入 arr 并重新洗牌怎么样?
  • OP 的 arr 在洗牌前有 width * height 元素,因此足以用均匀分布的动物填充 matrix
猜你喜欢
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2018-01-27
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多