在Swift中填充多维数组 [英] Filling the Multidimensional Array in Swift
问题描述
我是Swift的新手,我遇到了Swift语言方面的问题.
I'm newbie to Swift and I got a problem with Swift language.
我应该做一个函数,该函数创建一个二维矩阵NxN并找到对角线放置的元素的总和. 用随机值填充数组时出现了一些问题.
I should make a function, which creates a 2-dimensional matrix NxN and finds sum of diagonally situated elements. I've got some problem with filling an array with random values.
那是我的代码:
import Foundation
func diagonal (N:Int) {
var array: [[Int]] = [[0],[0]]
for row in 0...N {
for col in 0...N {
var z = Int(arc4random_uniform(100))
array[row][col] = z
}
}
println (array)
}
它不起作用.
因此,我期待您的帮助.
So I'm looking forward for your help.
推荐答案
@matt的答案为您当前的代码提供了一些好处,并突出显示了您需要修复的问题.我想提供一个替代的答案来填充二维数组.您可以使用append
添加新值,而不是使用零填充数组,然后设置每个行/列值,例如:
@matt's answer makes some good points about your current code and highlights the things you need to fix. I wanted to provide an alternative answer to filling the two-dimensional array. Instead of populating the arrays with zeros and then setting each row/column value, you could use append
to add new values, for example:
func diagonal (N:Int) {
var array: [[Int]] = []
for row in 0..<N {
// Append an empty row.
array.append([Int]())
for _ in 0..<N {
// Populate the row.
array[row].append(Int(arc4random_uniform(100)))
}
}
println(array)
}
使用它:
diagonal(2)
// [[40, 58], [44, 83]]
这篇关于在Swift中填充多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!