samedi 26 mars 2016

Create, random fill and search element on 2d array NxN Swift

I create an array of numbers, trying to fill in their rule or random size NxN, then looking for the amount in each of the diagonals and deduce it. Help to understand the errors that I noted in the comments. What am I doing wrong? Thank you!

func diagonals (n:Int) -> String{
        var sumFirst: Int
        var sumSecond: Int

        var multArray = Array(count: n, repeatedValue: Array(count: n, repeatedValue: 0))
                print(multArray) //create 2d array NxN with Initialisation

        for var i in multArray {
            for var k in multArray {
                multArray[i][k] = i+k // fill array elements the sum of the indices (error line) or we can fill it random, but how?
                if i==k { //check element on the main diagonal
                     sumFirst += multArray[i][k]  // do sum (error line)
                }
                if (i+k) == n  { //check element on secondary diagonal (error line)
                    sumSecond += multArray[i][k] // do sum (error line)
                }
            }
        }

        return "Sum elemets on main diagonal =\(sumFirst) and second =\(sumSecond)"
    }

    diagonals(3)




Aucun commentaire:

Enregistrer un commentaire