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.
#python 3 solution to find all possible solutions to 3x3 square first and then find the min cost. Probably not the cleanest way to do it but doesn't run into time issues and gets around needing to google the solutions firstimportitertoolsints=[1,2,3,4,5,6,7,8,9]constant=15first_check=[]second_check=[]third_check=[]cost=[]cost_holder=0#first step: find all permutations of 3 numbers that sum to 15 (valid rows)test=list(itertools.permutations(ints,3))[first_check.append(vals)forvalsintestifsum(vals)==constant]#second step: create 3x3 matrix and make sure there are no repeated numbers test2=list(itertools.permutations(first_check,3))[second_check.append(list(row))forrowintest2iflen(set([xfortinrowforxint]))==9andrownotinsecond_check]#third step: transpose 3x3 matricies from second check and do last round of checks (make sure cols = 15 and diagonals = 15) forvals2insecond_check:z=list(zip(*vals2))ifsum(vals2[0])==constantandsum(z[1])==constantandsum(z[2])==constantandz[0][0]+z[1][1]+z[2][2]==constantandz[0][2]+z[1][1]+z[2][0]==constant:third_check.append(z)#last step: calculate min cost for each 3x3 matrix vs given matrix and return the minimumforvals3inthird_check:forrow2inrange(0,3):forcolinrange(0,3):cost_holder+=abs(vals3[row2][col]-s[row2][col])cost.append(cost_holder)cost_holder=0return(min(cost))
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 →