• Post Reply Bookmark Topic Watch Topic
  • New Topic

About Magic Squares  RSS feed

 
Ashish Schottky
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to work out things with magic squares.
I found a pseudo-code for the same on internet, but then I am unable to program the logic of the code for the spiral patterns and simultaneous checking at rows and columns and where to check for which column, I have coded the following


Kindly help.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pencil, paper and eraser. That's what you need. The eraser is probably the most important piece of that hardware.

Write down on the paper exactly how you intend to do it. If you are given an algorithm, that will make it so much easier. Once you have got it down to really tiny steps, then you can write code. In fact you are wasting your time writing code until you have got the algorithm really simplified.
 
Ashish Schottky
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Cambell: Thanks, your advice and some of my logic did work. However I want to verify if I can make my code work faster than what it does.
The goal is to findout all the combination of 4x4 magic squares. This is my self assigned work, I am working on a 2-d board game AI program, and so I thought it might be helpful to go back and brush up recursion skills a bit.

Currently my program takes 11 minutes to compute all the possibilities of the 4x4 magic squares.


Its faster than what I did before.
Can it be still optimized?
If yes then kindly provide the hint and if possible the pseudocode.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know a lot about optimising that. You are using the brute-force method, and finding another algorithm will make much more difference than optimisations.

One change I would suggest is that you replace the % 4 operation by & 3. There are subtle differences between % 4 and & 3; & 3 never returns a negative result, and it requires (). It will probably only make a slight difference to your performance. I'll let you work out how it works, and why you can't do a similar trick with % 13.

i % 4 == 0 is slower than (i & 3) == 0, but the % operator doesn't require the ().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!