Skip to content

Instantly share code, notes, and snippets.

@alexnikol
Created Jun 29, 2020
Embed
What would you like to do?
Magic Square HackerRank - Solving
let magic1 = [[8, 1, 6], [3, 5, 7], [4, 9, 2]]
let magic2 = [[6, 1, 8], [7, 5, 3], [2, 9, 4]]
let magic3 = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]
let magic4 = [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
let magic5 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]]
let magic6 = [[4, 3, 8], [9, 5, 1], [2, 7, 6]]
let magic7 = [[6, 7, 2], [1, 5, 9], [8, 3, 4]]
let magic8 = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
let posibleMagicSquares = [magic1, magic2, magic3, magic4, magic5, magic6, magic7, magic8]
var allPosibleAnswers: [Int] = []
for square in posibleMagicSquares {
var currentAnswer = 0
for i in 0...2 {
for j in 0...2 {
currentAnswer += abs(square[i][j] - s[i][j])
}
}
allPosibleAnswers.append(currentAnswer)
}
return allPosibleAnswers.min() ?? 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment