sum a diagonal array

how can i possible sum in diagonal 3 arrays?


example:


[6, 6, 5]

[10, 5, 10]

[3, 20, 1]


from left to right, and right to left


6 + 5 + 1 = 12

3 + 5 + 5 = 13



my code:


import UIKit


class exerViewController: UIViewController {
    @IBOutlet weak var num1: UITextField!
    @IBOutlet weak var num2: UITextField!
    @IBOutlet weak var num3: UITextField!
    @IBOutlet weak var num4: UITextField!
    
    @IBOutlet weak var num5: UITextField!
    @IBOutlet weak var num6: UITextField!
    
    @IBOutlet weak var num7: UITextField!
    @IBOutlet weak var num8: UITextField!
    
    @IBOutlet weak var num9: UITextField!
    
    
    
    
    @IBOutlet weak var result: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    @IBAction func leftTOright(_ sender: UIButton) {
        if num1.text == "" || num5.text == "" || num9.text == ""{
            
            displayAlert(title: “USER”, message: “FIELDS 1/5/9ARE EMPTY“)
        }
        else{
            
        // 1 array
        let a:Int? = Int(num1.text!)
        let b:Int? = Int(num2.text!)
        let c:Int? = Int(num3.text!)
            
            // 2 array
        let d:Int? = Int(num4.text!)
        let e:Int? = Int(num5.text!)
            let f:Int? = Int(num6.text!)
            
            //3 array
            let g:Int? = Int(num7.text!)
            let h:Int? = Int(num8.text!)
            let i:Int? = Int(num9.text!)
        
        
        let oddNumbers = [a, e, i]
        let numberSum = oddNumbers.reduce(0, { x, y in
            x + y!
        })
        resultado.text = “result: left to right \(numberSum)"
   
        }

    }
    
    
    
    
    
    
    @IBAction func rightTOleft(_ sender: UIButton) {
        if num3.text == "" || num5.text == "" || num7.text == ""{
            
            displayAlert(title: “USER”, message: “FIELDSS 3/5/7 ARE EMPTY“)
        }
        else{
            
            // 1 array
            let a:Int? = Int(num1.text!)
            let b:Int? = Int(num2.text!)
            let c:Int? = Int(num3.text!)
            
            // 2 array
            let d:Int? = Int(num4.text!)
            let e:Int? = Int(num5.text!)
            let f:Int? = Int(num6.text!)
            
            //3 array
            let g:Int? = Int(num7.text!)
            let h:Int? = Int(num8.text!)
            let i:Int? = Int(num9.text!)
            
            
            let oddNumbers = [c, e, g]
            let numberSum = oddNumbers.reduce(0, { x, y in
                x + y!
            })
            resultado.text = “result right to left \(numberSum)"
            
        }
        
    }
    
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func displayAlert (title:String, message:String){
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
        
    }
    /*
     @IBAction func dereAizquie(_ sender: Any) {
     }
     // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


i have 9 numbers and i only use

numbers 1,5,9 to make the left to right diagonal sum


      let a:Int? = Int(num1.text!)
 let e:Int? = Int(num5.text!)
 let i:Int? = Int(num9.text!)


        let oddNumbers = [a, e, i]
        let numberSum = oddNumbers.reduce(0, { x, y in
            x + y!
        })
        resultado.text = “result: left to right \(numberSum)"


as you can see i'm not displaying my array's im only taking the value that i need

like this


   
            let oddNumbers = [c, e, g]
            let numberSum = oddNumbers.reduce(0, { x, y in
                x + y!
            })
            resultado.text = “result right to left \(numberSum)"



is there a smart way to do it?, by taking the completly array and take the values that i need?

You have two different problems here:

  • How do I sum the diagonals of a two-dimensional array?

  • How do I build that array from a bunch of

    UITextFields
    ?

These are separate issues and I recommend that you treat them separately. Putting all of this code into your view controller makes it very hard to wrangle.

For the first problem, you can write a simple function to do that job:

func sumDiagonals(matrix: [[Int]]) -> Int {
    var result = 0
    for i in 0..<matrix.count {
        precondition(matrix.count == matrix[i].count)
        result += matrix[i][i]
    }
    return result
}

You can make this as fancy as you want. For example, you could the whole ‘no loops’ thing:

func sumDiagonals(matrix: [[Int]]) -> Int {
    return (0..<matrix.count).reduce(0) {
        $0 + matrix[$1][$1]
    }
}

Or create a custom type for your matrix:

struct SquareMatrix {
    let size: Int
    private var elements: [Int]
    init(size: Int) {
        self.size = size
        self.elements = [Int](repeating: 0, count: size * size)
    }
    subscript(row: Int, _ col: Int) -> Int {
        get {
            return self.elements[row * self.size + col]
        }
        set {
            self.elements[row * self.size + col] = newValue
        }
    }
}

and implement a

diagonalSum
method on that.

The point here is that by separating out this code you can keep it simple and test it in isolation.

For your second problem, you need to look at outlet collections. If you declare your outlets as an array:

@IBOutlet var numberFields: [UITextField]!

Xcode will let you wire up multiple items to the outlet. You can then write code to build a matrix based on the text in these fields:

extension SquareMatrix {
    init?(size: Int, numberFields: [UITextField]) {
        precondition(numberFields.count == size * size)
        var tmp = SquareMatrix(size: size)
        for row in 0..<size {
            for col in 0..<size {
                let field = numberFields[row * size + col]
                guard let e = field.text.flatMap({ Int($0) }) else {
                    return nil
                }
                tmp[row, col] = e
            }
        }
        self = tmp
    }
}

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

Here is a slightly different way:


let anArray = [[1, 6, 9],[8, 2, 10],[9, 5, 2]]

let size = anArray.count

for i in 0..<size {

if anArray[i].count != size {

print("error") // should give up computation

}

}


var diagSum = 0

for i in 0..<size {

for j in 0..<size where i == j {

diagSum += anArray[i][j]

}

}

print(diagSum)


var antidiagSum = 0

for i in 0..<size {

for j in 0..<size where i + j == size-1 {

antidiagSum += anArray[i][j]

}

}

print(antidiagSum)


Adapting the where clause let you compute any diagonal ; for instance, foe the subDiagonale : 8, 5, 9

[1, 6, 9]

[8, 2, 10]

[9, 5, 2]


var subdiagSum = 0

for i in 0..<size {

for j in 0..<size where j == (i + size-1) % size {

subdiagSum += anArray[i][j]

}

}

print(subdiagSum)

sum a diagonal array
 
 
Q