// read array and map the elements to integer var arr1 = readLine()!.characters.split(" ").map{Int(String($0))!} var arr2 = readLine()!.characters.split(" ").map{Int(String($0))!} var arr3 = readLine()!.characters.split(" ").map{Int(String($0))!} var arr = arr1 + arr2 + arr3 // All magic squares var mags = [ [6, 1, 8, 7, 5, 3, 2, 9, 4], [6, 7, 2, 1, 5, 9, 8, 3, 4], [2, 7, 6, 9, 5, 1, 4, 3, 8], [2, 9, 4, 7, 5, 3, 6, 1, 8], [4, 9, 2, 3, 5, 7, 8, 1, 6], [4, 3, 8, 9, 5, 1, 2, 7, 6], [8, 3, 4, 1, 5, 9, 6, 7, 2], [8, 1, 6, 3, 5, 7, 4, 9, 2]] // variable to hold the sum of the array elements var sum = 9999999 for (var i = 0; i < 8; i++) { var cost = 0 for (var j = 0; j < 9; j++) { cost = cost + abs(arr[j] - mags[i][j]) } if (cost < sum) { sum = cost } } // print the array elements print(sum)