david berdznishvili
david berdznishvili

Reputation: 1

Guess the number in MIPS

The goal is for computer to find the secret number, and user should tell the computer whether it is higher or lower? it works when it is always higher or always lower, but not when I have to enter both. Anyone know any sollution?

.data

prompt: .asciiz "Enter the Secret Number"
prompt2: .asciiz "\n Computer guess is: "

higherLowerorCorrect: .asciiz "\n Number is higher(h) lower(l) or correct/exit(2):" 

.text

li $v0, 4
la $a0, prompt
syscall

li $v0, 5
syscall

move $t2, $v0

li $t7, 101
li $t6, 0
li $t5, 0

loop:

move $a1, $t7
li $v0, 42
syscall


add $a0, $a0, $t6
move $t5, $a0

li $v0, 4
la $a0, prompt2
syscall

move $a0, $t5
li $v0,1
syscall

li $v0, 4
la $a0, higherLowerorCorrect #  
syscall

li $v0, 12 
syscall

beq $v0, 'l', setHigherBound ####

beq $v0, 'h', setLowerBound ####

beq $v0, 'x', exit ####


setHigherBound:
move $t7, $t5
j loop

setLowerBound:
add $t7,$t7,$t6
sub $t7, $t7, $t5
move $t6, $t5
j loop


exit:
output:

Upvotes: 0

Views: 394

Answers (1)

Michael
Michael

Reputation: 58467

The way you calculate the numbers that the computer is allowed to guess looks a bit broken to me.

Consider the following scenario:

  1. The secret number is 5. LB is 0 (inclusive), UB is 101 (exclusive).
    • The computer is allowed to guess the numbers [0, 100].
  2. The computer guesses 3, which is too low: UB = (101+0-3) == 98, LB = 3.
    • Oops! The computer is now allowed to guess the numbers [3, 100], even though you've already established anything <= 3 is too low.
  3. The computer guesses 10, which is too high: UB = 10.
    • Oops! The computer is now allowed to guess the numbers [3, 12], even though you've already established anything <= 3 is too low and anything >= 10 is too high.

I'd suggest that you change your setLowerBound code to:

setLowerBound:
addiu $t6, $t5, 1    # LB is inclusive, so set it to guess+1
j loop

And the random number generation to:

sub $a1, $t7, $t6
li $v0, 42
syscall
add $a0, $a0, $t6   # $a0 = rand(UB - LB) + LB

Upvotes: 1

Related Questions