Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling the Multidimensional Array in Swift

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.

like image 393
eserdk Avatar asked Dec 20 '22 04:12

eserdk


1 Answers

@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]]
like image 90
ABakerSmith Avatar answered Dec 21 '22 23:12

ABakerSmith