Reputation: 33
I am a attempting to create a function that arranges the of numbers in a square grid, where the numbers in each row, each column, and the numbers in the forward and backward main diagonals, all add up to the same number. And while I am relatively new to mips here is my latest attempt:
square: lw $t0,$zero #i = 0
lw $t2,1 # k = 1
div $t1,$a1,2 # j = n/2
mul $t3,$a1,$a1 # n*n
while: ble $t2,$t3,else1 # k <= n*n
bgt $t0,-1,else2 #
bgt $t1,-1,else2 #
ble $t1,$a1,else3 #
ble $t0,$a1,else4 #
bne $,$,else5#a[i,j] == 0
else1: #a[i,j] = k
addi $t0,$t0,-1 #
addi $t1,$t1,1 #
addi $t2,$t2,1 #
else2: lw $t0,1 #
addi $t1,$a1,-1 #
else3: lw $t1,$zero #
else4: addi $t0,$a1,-1 #
else5: addi $t0,$t0,2 #
addi $t1,$t1,-1 #
end: jr $ra
in addition this is the structure of the registers:
$a0 = base address of array (matrix), a
$a1 = n, size of matrix (number of rows and columns)
$t0 = i
$t1 = j
$t2 = k
$t3 = n*n
$t4 = arraya index - in steps
$t5 = array value
The trouble I am having is the creation of a[i,j] how is it done? here is a look at the algorithm:
i = 0, k = 1 and j = n/2
while (k <= n*n)
if (i > -1 and j > -1 and j < n and i < n and a[i,j] == 0)
a[i,j] = k
i = i - 1, j = j +1 and k = k + 1
else if (i < 0 and j == n) move out of upper right square
i = 1 and j = n - 1
else if (j == n) move out of right side of square
j = 0
else if (i < 0) move above top row
i = n - 1
else move to an already filled square
i = i + 2 and j = j - 1
end if - else
end while loop
Upvotes: 1
Views: 317
Reputation:
You can store a 2D array contiguously, with address computation: a[i, j]
stored at base address + i + j * n
.
For the sake of optimization, row/column traversals are made with +/-1
or +/-n
increments.
Alternatively, you can allocate different areas for the rows and provide a table of row starts.
Upvotes: 1