This assignment is worth 50 points.
One possible way to "solve" a magic square is a brute force search. To do this in C++ for all squares of size 4, I would:
l = {1,2,3,4} do { if (l is a magic square) PrintSquare(l); cout << " is a magic square " << endl while (next_permutation(l[0],l[3])
Since we don't have the next_permutation function in MIPS assembly, we must implement one. This can be done using Heap's permutation algorithm. I have modified Heap's algorithm below to check each permutation to see if it is a magic square. This, in some sense, becomes the main program.
void HeapPermute(int len, int l[]) if (len ==1) TestForMagicSquare() else for (int i = 0; i < len; i++) { HeapPermute(len-1) if (n%2 ==1) swap(l[0],l[len-1]) else swap(l[i],l[len-1]) }Notice that the mod function here is only checking to see if the value is odd or even, which can easily be accomplished with an andi. Calling HeapPermute with the size of an array and the array as arguments will produce ALL of the permutations of the array. By adding TestForMagicSquare to the function, it will accomplish the main algorithm above. Notice this will make n2! calls to TestForMagicSquare.
You are to write a program in MIPS assembly language which will find all possible permutations of a 3×3 magic square by checking all possible permutations of the numbers.
Magic happened. 2 9 4 7 5 3 6 1 8
Your routines should follow the calling convention.
You may assume that the square size is 3.
I found the following assembly program to be helpful
.text addi $t1,$zero, 20 addi $t2, $zero, 30 mult $t1, $t2 mflo $t3 addi $t1,$zero, 2 andi $t5, $t1, 1 addi $t2, $zero, 3 andi $t6, $t2, 1
Write it in C++, make sure you know what it is doing before you attempt the assembly code. This is not trivial.