ASM Code:
#include <mips.h>
.data
next_set: .asciiz "\n\n\n"
hist: .word 4, 5, 6, 7, 0, 0, 0, 0
.text
.globl main
main:
subiu $sp, $sp, 40 #allocate 40 bytes on the stack
sw $ra, 36($sp) #save the return address.
li $4, 8 #push n
li $5, 0 #push col
la $6, hist #push hist
jal solve #call solve
addiu $sp, $sp, 40 #deallocate 40 bytes on the stack
sw $ra, 36($sp) #pop restore return address.
li $v0, 10 #mov eax, 0
syscall #ret
solve:
bne $5, $4, atk #if col == n
li $v0, 4 #get ready to print string.
la $a0, next_set #push string onto stack
syscall #printf("\n\n\n")
#for (int i = 0; i < n; ++i)
li $t1, 0 #i = 0.
lf1:
beq $t1, $4, lf1e #i == 10? end the loop.
#for (int j = 0; j < 2; ++j)
li $t2, 0 #j = 0.
lf2:
beq $t2, 2, lf2e
#for (int k = 0; k < n; ++k)
li $t4, 0 #k = 0
lf3:
beq $t4, $4, lf3
#char c = k == hist[i] ? 'Q' : ((i + k) & 1) ? ' ' : 178
bne $t4, $6, eff #if j == hist[i]
lb $t9, 'Q' #c = 'Q'
j eaf
#else if (i + k & 1)
eff:
move $t6, $t1 #put i into temp register for arithmetic.
add $t6, $t6, $t4 #i + k
and $t6, $t6, 1 #i + k & 1
beqz $t6, eee #if (i + k & 1) == 0 go to the else statement
lb $t9, 32 #c = ' '
j eaf
#else
eee:
lb $t9, 178 #c = ascii 178.
eaf:
move $13, $t9 #save c. probably better to use sb instruction.
#for (int l = 0; l < 4; ++l)
li $t6, 4
li $t9, 0 #l = 0
lf4:
beq $t9, $t6, lf4e
li $v0, 4
move $a0, $13
syscall #putchar(c)
li $a0, 0
addi $t9, $t9, 1 #++l
j lf4
lf4e:
add $t4, $t4, 1 #++k
j lf3
lf3e:
addi $t2, $t2, 1 #++j
j lf2
lf2e:
addi $t1, $t1, 1 #++i
j lf1
lf1e:
atk:
li $t0, 0 #i = 0
li $t1, 0 #j = 0
lfatk1:
beq $t0, $4, lfatk1e #if i == n
lfatk2:
beq $t1, $5, lfatk2e #if j == col
move $7, $t0
move $8, $t1
jal attack
beqz $v0, lfatk2e #if !attack(i, j)
addi $t1, $t1, 1 #++j
blt $t1, $5, lfatk2 #continue
mul $t2, $5, 4 #calculate array offset.
add $t2, $t2, $6 #offset the hist address.
sw $t3, 0($t2) #hist[col] = i
addi $5, $5, 1
jal solve
lfatk2e:
addi $t0, $t0, 1
j lfatk1
lfatk1e:
atke:
jr $ra #ret
#define attack.. as a separate function:
attack:
move $t1, $6 #hist
mul $t2, $7, 4 #calculate true offset
add $t1, $t1, $t2 #load hist[j] into $t1
lw $t2, 0($t1) #t2 = hist[j]
sub $t3, $t2, $8 #t3 = hist[j] - i
#t3 = abs(t3)
sra $t4, $t3, 31
xor $t3, $t3, $t4
sub $t3, $t3, $t4
sub $t4, $5, $7 #t4 = col - j
bne $t2, $8, acmp2 #hist[j] == i
bne $t2, $t4, acmp1 #[hist[j] == col - j
lw $v0, 1 #return true.
jr $ra
acmp2:
beqz $t3, acmp1 #abs(hist[j] - i) != 0
bne $t3, $t4, acmp1 #abs(hist[j] - i) == col - j
lw $v0, 1 #return true
jr $ra
acmp1:
li $v0, 0 #return false
jr $ra