// Enter your code here import Foundation func magicCamperer (inout notMagicArr: [[Int]],inout magicArr: [[Int]]) -> Int { var curCost: Int = 0 for i in 0 ..< 3 { for j in 0 ..< 3 { curCost += abs(notMagicArr[i][j] - magicArr[i][j]) } } return curCost } var notMagic: [[Int]] = [] /*Reads in matrix*/ var strInput: String = readLine()! //Converts second line values to integers var firstRow: [Int] = strInput.componentsSeparatedByString(" ").map( { Int($0) ?? 0 }) strInput = readLine()! var secondRow: [Int] = strInput.componentsSeparatedByString(" ").map( { Int($0) ?? 0 }) strInput = readLine()! var thirdRow :[Int] = strInput.componentsSeparatedByString(" ").map( { Int($0) ?? 0 }) //Adds values to 2D Matrix notMagic.append(firstRow) notMagic.append(secondRow) notMagic.append(thirdRow) //According to how magic squares are formed, a 3 X 3 magic square can only have 8 possible configurations under the given limitations /* I: 8 1 6 3 5 7 4 9 2 II: 4 3 8 9 5 1 2 7 6 III: 2 9 4 7 5 3 6 1 8 IV: 6 7 2 1 5 9 8 3 4 V: 6 1 8 7 5 3 2 9 4 VI: 8 3 4 1 5 9 6 7 2 VII: 4 9 2 3 5 7 8 1 6 VIII: 2 7 6 9 5 1 4 3 8 */ //Create Magic Squares var sq1 = [[8, 1, 6], [3, 5, 7], [4, 9, 2]] var sq2 = [[4, 3, 8], [9, 5, 1], [2, 7, 6]] var sq3 = [[2, 9, 4], [7, 5, 3], [6, 1, 8]] var sq4 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]] var sq5 = [[6, 1, 8], [7, 5, 3], [2, 9, 4]] var sq6 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]] var sq7 = [[4, 9, 2], [3, 5, 7], [8, 1, 6]] var sq8 = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] var lowestCost: Int = 100 //Loops through all squares var tempCost: Int = lowestCost //Comparisons tempCost = magicCamperer(¬Magic, magicArr: &sq1) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq2) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq3) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq3) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq4) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq5) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq6) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq7) if tempCost < lowestCost {lowestCost = tempCost} // tempCost = magicCamperer(¬Magic, magicArr: &sq8) if tempCost < lowestCost {lowestCost = tempCost} print(lowestCost)