I'm newbie to Swift and I got a problem with Swift language.
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.
That's my code:
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)
}
It doesn't work.
So I'm looking forward for your help.
@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)
}
Using it:
diagonal(2)
// [[40, 58], [44, 83]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With