I wanted to make a magic square, where I put 9 numbers, and the sum of them has to result 15 (in the horizontal and vertical)

-1

Good evening guys, I have this array:

Ineedtheaddedarraynumberstoall15.Bothverticallyandhorizontally.

Code:

importnumpyasnpimportrandomfromtabulateimporttabulatea=[1,2,3,4,5,6,7,8,9]random.shuffle(a)data=np.reshape(a,(3,3))soma_horizontal=[]forlistaindata:soma_horizontal.append(sum(lista))soma_vertical=[]forxinrange(len(data)):soma=0forlistaindata:soma+=lista[x]soma_vertical.append(soma)indice=0forlistaindata:lista.extend(['\u2192',soma_horizontal[indice]])indice+=1setas_cima=['\u2191']*3data=[soma_vertical]+[setas_cima]+dataprint(tabulate(data,tablefmt="grid", stralign='center', numalign='center'))

The program running on repl:

link

    
asked by anonymous 25.12.2017 / 01:36

1 answer

0

Your question is not very clear, if you want a solution to this magic square (which is unlikely), or an algorithm that solves such a case.

  • If you want a solution, it's easy to find it on the internet link
  • If it is an algorithm to solve on Wikipedia it shows one for the 3x3 solution that is your case, if you want to extrapolate I believe that with an internet search it is simple to find.

The algorithm shown is as follows

  

Tips for solving the magic square 3x3:

     
  • The total you want to get in all directions should be divided by 3. Which will result in the number being placed in the center of the square.
  •   
  • The numbers to be placed in the corners should be even if the center is odd, or vice versa.
  •   
  • The last number to be placed should be the center plus 4.
  •   

    These rules are only valid if the numbers are multiples of 3. Eg 15, 18,   21, 24, 27, 30 etc.

    From this you just have to implement it.

    References

    26.12.2017 / 07:10