/* https://www.hackerrank.com/contests/rookierank/challenges/magic-square-forming */ #include #include #include #include using namespace std; int getMatrixDifference(vector> a, vector> b) { vector> diff { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} }; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { diff[i][j] = abs(a[i][j] - b[i][j]); } } int total = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { total += diff[i][j]; } } //cout << total << endl; return total; } int main() { // 3x3 0 matrix. vector> square {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for (int i = 0; i <3; i++) { //cin >> square[i][1] >> square[i][2] >> square[i][3] for (int j = 0; j < 3; j++) { cin >> square[i][j]; } } /* To get all 8 magic squares of order 3, apply each element of D_4 to an arbitrary magic square of order 3. Or, do what I did and copy them all from http://www.jsoftware.com/papers/eem/magicsq.htm */ // A vector of EVERY SINGLE MAGIC SQUARE OF ORDER 3. vector>> loShu = { { {8,1,6}, {3,5,7}, {4,9,2} }, { {4,3,8}, {9,5,1}, {2,7,6} }, { {2,9,4}, {7,5,3}, {6,1,8} }, { {6,7,2}, {1,5,9}, {8,3,4} }, { {6,1,8}, {7,5,3}, {2,9,4} }, { {8,3,4}, {1,5,9}, {6,7,2} }, { {4,9,2}, {3,5,7}, {8,1,6} }, { {2,7,6}, {9,5,1}, {4,3,8} } }; vector scores; for (int i = 0; i < loShu.size(); i++) { scores.push_back(getMatrixDifference(loShu[i],square)); } cout << *min_element(scores.begin(), scores.end()); return 0; }