programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Ashish Schottky
Ranch Hand
Posts: 93
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
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
@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
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 ().