We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
import math
import os
import random
import re
import sys
import itertools
#
Complete the 'formingMagicSquare' function below.
#
The function is expected to return an INTEGER.
The function accepts 2D_INTEGER_ARRAY s as parameter.
#
def formingMagicSquare(arr):
all_val = []
for row in arr:
for col in row:
all_val.append(col)
const = list(range(1, 10))
all_comb_r = list(itertools.permutations(const, 9))
all_valid_comb = []
for comb in all_comb_r:
c = list(comb)
temp = []
curr = []
curr_col = []
curr_d = []
for val in c:
temp.append(val)
if len(temp) == 3:
curr.append(temp)
temp = []
temp = []
for i in range(len(curr)):
for j in range(len(curr[i])):
temp.append(curr[j][i])
if len(temp) == 3:
curr_col.append(temp)
temp = []
temp = []
for i in range(len(curr)):
temp.append(curr[i][i])
if len(temp) == 3:
curr_d.append(temp)
temp = []
s = 0
e = 2
for i in range(len(curr)):
temp.append(curr[s][e])
if len(temp) == 3:
curr_d.append(temp)
temp = []
s += 1
e -= 1
sum_curr = [sum(i) for i in curr]
sum_curr_col = [sum(i) for i in curr_col]
sum_curr_d = [sum(i) for i in curr_d]
all_val = []
for num in range(3):
all_val.append(sum_curr[num])
all_val.append(sum_curr_col[num])
if num != 2:
all_val.append(sum_curr_d[num])
if all(i == all_val[0] for i in all_val):
all_valid_comb.append(curr)
all_ans = []
for i in range(len(all_valid_comb)):
curr_ans = 0
for j in range(len(all_valid_comb[i])):
for a in range(len(all_valid_comb[i][j])):
if all_valid_comb[i][j][a] != arr[j][a]:
curr_ans += abs(all_valid_comb[i][j][a] - arr[j][a])
all_ans.append(curr_ans)
return min(all_ans)
if name == 'main':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = []
for _ in range(3):
s.append(list(map(int, input().rstrip().split())))
result = formingMagicSquare(s)
fptr.write(str(result) + '\n')
fptr.close()
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forming a Magic Square
You are viewing a single comment's thread. Return to all comments →
This is my solution (python):
!/bin/python3
import math import os import random import re import sys import itertools
#
Complete the 'formingMagicSquare' function below.
#
The function is expected to return an INTEGER.
The function accepts 2D_INTEGER_ARRAY s as parameter.
#
def formingMagicSquare(arr): all_val = [] for row in arr: for col in row: all_val.append(col)
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')