如何用自定义对象填充2维数组?迅速



我试图在我的网格板和诸如鱼类和逆戟鲸之类的角色的地方制作项目。我创建了动物父母班级和两个继承动物的孩子班。我想用5%的Orca和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
}
}

声明类型[[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
    }
}

最新更新