Forming A Magic Square - HackerRank
Forming A Magic Square - HackerRank
We define a magic square to be an matrix of distinct positive integers from to where the sum of any row, column, or diagonal of length is always equal to the
same number: the magic constant.
You will be given a matrix of integers in the inclusive range . We can convert any digit to any other digit in the range at cost of . Given , convert
it into a magic square at minimal cost. Print this cost on a new line.
Note: The resulting magic square must contain distinct integers in the inclusive range .
Example
5 3 4
1 5 8
6 4 2
8 3 4
1 5 9
6 7 2
Function Description
Returns
int: the minimal total cost of converting the input square to a magic square
Input Format
Constraints
Sample Input 0
492
357
815
Sample Output 0
Explanation 0
If we change the bottom right value, , from to at a cost of , becomes a magic square at the minimum possible cost.
https://www.hackerrank.com/challenges/magic-square-forming/problem 1/3
26/11/24, 8:51 a.m. Forming a Magic Square | HackerRank
Sample Input 1
482
457
616
Sample Output 1
Explanation 1
-> at a cost of
-> at a cost of ,
1 #include <bits/stdc++.h>
2
3 using namespace std;
4
5 string ltrim(const string &);
6 string rtrim(const string &);
7 vector<string> split(const string &);
8
9 /*
10 * Complete the 'formingMagicSquare' function below.
11 *
12 * The function is expected to return an INTEGER.
13 * The function accepts 2D_INTEGER_ARRAY s as parameter.
14 */
15
16 int formingMagicSquare(vector<vector<int>> s) {
17
18 }
19
20 int main()
21 {
22 ofstream fout(getenv("OUTPUT_PATH"));
23
24 vector<vector<int>> s(3);
25
26 for (int i = 0; i < 3; i++) {
27 s[i].resize(3);
28
29 string s_row_temp_temp;
30 getline(cin, s_row_temp_temp);
31
32 vector<string> s_row_temp = split(rtrim(s_row_temp_temp));
33
34 for (int j = 0; j < 3; j++) {
35 int s_row_item = stoi(s_row_temp[j]);
36
37 s[i][j] = s_row_item;
38 }
39 }
40
41 int result = formingMagicSquare(s);
42
https://www.hackerrank.com/challenges/magic-square-forming/problem 2/3
26/11/24, 8:51 a.m. Forming a Magic Square | HackerRank
43 fout << result << "\n";
44
45 fout.close();
46
47 return 0;
48 }
49
50 string ltrim(const string &str) {
51 string s(str);
Line: 88 Col: 1
Upload Code as File Test against custom input Run Code Submit Code
Blog | Scoring | Environment | FAQ | About Us | Support | Careers | Terms Of Service | Privacy Policy
https://www.hackerrank.com/challenges/magic-square-forming/problem 3/3