Thursday, August 9, 2018

Solving A Magic Square

You've probably heard of this puzzle. I read about it in a book and it's quite challenging. The goal is to fill a tic tac toe square with number 1-9 in a way that every row, column and diagonal add up to 15. if you think this is a piece of cake you are probably mistaken. I thought it would be fun to solve it, but it would be more fun to have a computer solve it for me.

At first I experimented with Apple code which is very easy to work with, but it wasn't really designed for this sort of operation. I started learning Python on a web sight called solo learn(it's not that hard, it's still english). I chose python mainly because it sounded like the coolest programing language.

My Dad and I discussed for a while and I couldn't find any systematic ways for rearranging the places in a way that would be sure to find all combinations except this method.

You change the places in the square to a list so that the computer can deal with it. We created 18 checks for the list to make sure it was a working combination and then it is added to the list of answers.

The program started at [0,0,0,0,0,0,0,0,0] adding one every time until it reached [9,9,9,9,9,9,9,9,9]. You can quickly notice that this can be shortened to [1,2,3,4,5,6,7,8,9] to [9,8,7,6,5,4,3,2,1].

One snag we encountered was the append statement in python. This adds something onto the end of a list but what we didn't know is that is was, in a way, smart. If you append say, n to a list and then change n's value the list's value will then be changed as well. We did not know this so when the script spit out answerlist=[[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1],[9,8,7,6,5,4,3,2,1]] we didn't understand. However what it was doing was appending all nine answers in their current state which was the end of the script state [9,8,7,6,5,4,3,2,1]. This was an easy fix and the hole thing after about a month came together.

This was the end result:
All Done!
 Your answerlist was:['[2, 7, 6, 9, 5, 1, 4, 3, 8]', '[2, 9, 4, 7, 5, 3, 6, 1, 8]', '[4, 3, 8, 9, 5, 1, 2, 7, 6]', '[4, 9, 2, 3, 5, 7, 8, 1, 6]', '[6, 1, 8, 7, 5, 3, 2, 9, 4]', '[6, 7, 2, 1, 5, 9, 8, 3, 4]', '[8, 1, 6, 3, 5, 7, 4, 9, 2]', '[8, 3, 4, 1, 5, 9, 6, 7, 2]']
 Your final x was:[9, 8, 7, 6, 5, 4, 3, 2, 1]
 and your try count was:375313600
Exit status: 0
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.


[Process completed]


1 comment:

  1. I am very proud of your persistent work at learning and solving this. Three hundred million tries is a lot! I think it's just the sort of problem computers can make great contributions in helping us solve.

    ReplyDelete