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.
Forming a Magic Square
Forming a Magic Square
Sort by
recency
|
1242 Discussions
|
Please Login in order to post a comment
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')
I do like this. 1st. Unroll the input matrix to long list. (imagine the list 9 items was rolled in clockwise direction to create a 3x3 matrix),
2nd. Create the unrolled List of the Magic Square , since magic square can rotate or flip, so the List has some repeat pattern, and I have to create another reverse List.
Notice I have exclude the center number of magic square, number 5, since it's unchanged in every version of magic square 3x3.
3rd. Calculate the cost and compare. Here is the full code in C#
` 4th. It's easier to explain in image, but I don't know how to upload here. So I uploaded to this image hosting service https://ibb.co/sjwBpwZ
JS/Javascript solution:-