2014-04-11 61 views
1

我試圖創建一個函數,它將數字排列在一個正方形網格中,其中每行,每列以及前向和後向主對角線中的數字全部合計爲相同的數字。雖然我是比較新的MIPS這裏是我的最新嘗試:Mips函數數組

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 

除了這是寄存器的結構:數組

$ A0 =基址(矩陣),一個

$ A1 = n時,矩陣

$ T0(行和列的數目)的尺寸= I

$ T1 = j的

$ T2 = K

$ T3 = N * N

$ T4 = arraya指數 - 在步驟

$ T5 =數組值

我遇到的麻煩是創建a [i,j]它是如何完成的?這裏是看看算法:

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 

回答

1

可以連續存儲一個二維數組,以地址計算:a[i, j]儲存在base address + i + j * n

爲了優化,使用+/-1+/-n增量進行行/列遍歷。

或者,您可以爲行分配不同的區域並提供行開始的表格。