Question: Im trying to make a random integer generator from - 3 1 to 3 2 from mips but I encounter an error Runtime exception at

Im trying to make a random integer generator from -31 to 32 from mips but I encounter an error "Runtime exception at 0x00400020: Upper bound of range cannot be negative (syscall 42)" Here is my code in MIPS Assembly
.data
BingoArray: .word -31,-30,-29,-28,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,-17,-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32
ArraySize: .word 64 # Total elements in BingoArray
.text
.globl main
main:
# Load the array size
lw $a0, ArraySize
# Fisher-Yates Shuffle Algorithm
addi $a0, $a0,-1 # Adjust size for 0 indexing
move $t1, $a0 # $t1 will be used for 'i' in the loop, starting from n-1
shuffle_loop:
bltz $t1, print_random # If $t1<0, we've shuffled the array; go to print
# Generate random number, 0<= j <= i, using syscall 42
li $v0,42 # Syscall code for random int in range
li $a1,0 # Lower bound of the range
move $a2, $t1 # Upper bound is 'i'
syscall # Perform syscall, result is in $a0(random index j)
move $a1, $a0 # Move random index to $a1 for SWAP procedure
# Call SWAP with indices i ($t1) and j ($a1)
move $a2, $t1
jal SWAP
# Decrement i for next iteration
addi $t1, $t1,-1
j shuffle_loop
SWAP:
# Input: $a2= i, $a1= j
# Swap BingoArray[i] and BingoArray[j]
# Calculate addresses
sll $t2, $a2,2 # $t2= i *4
sll $t3, $a1,2 # $t3= j *4
add $t2, $t2, $gp # Address of BingoArray[i]
add $t3, $t3, $gp # Address of BingoArray[j]
# Swap values
lw $t4,0($t2) # Temporarily store BingoArray[i]
lw $t5,0($t3) # Temporarily store BingoArray[j]
sw $t5,0($t2) # BingoArray[i]= BingoArray[j]
sw $t4,0($t3) # BingoArray[j]= BingoArray[i]
jr $ra # Return to caller
print_random:
# Printing the first element of the shuffled array
lw $a0, BingoArray # Load the first element of the array
li $v0,1 # syscall for print integer
syscall
# End of program
li $v0,10 # exit syscall
syscall
The Swap procedure work like this
Store any variables you will use on your procedure on the stack
Inputs: i, j
Exchange BingoArray[i] and BingoArray[j]
Restore the used variables from the stack
And the psuedocode for shuffle work like this
To shuffle an array a of n elements (indices 0..n-1):
for i from n1 down to 1 do
j random integer such that 0<= j <= i
exchange a[j] and a[i]

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!