Skip to content

Instantly share code, notes, and snippets.

@mlhaufe
Created October 28, 2012 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlhaufe/3969503 to your computer and use it in GitHub Desktop.
Save mlhaufe/3969503 to your computer and use it in GitHub Desktop.
Case insensitive Palindrome Checker
######################################
# Case insensitive Palindrome Checker
######################################
# Register Usage
# $t0 = index
# $t1 = character
# $t2 = ASCII 97 'a'
# $t3 = ASCII 122 'z'
# $t4 = string length
# $t5 = ASCII difference
# $t6 = ASCII 10 '\n'
# $t7 = maxlen
# $s1 = char comparator 1
# $s2 = char comparator 2
#####################################
.data
promptString: .asciiz "\nEnter a string <= 20 characters in length (Empty string to exit): "
promptExit: .asciiz "GoodBye"
promptErr: .asciiz "String is too long.\n"
promptTrue: .asciiz "True"
promptFalse: .asciiz "False"
maxlen: .word 21
buffer: .space 21
str: .space 21
len: .word 0
.text
main:
li $t0, 0
li $t2, 97
li $t3, 122
li $t4, 0
li $t5, 32
li $t6, 10
lw $t7, maxlen
jal promptInput
jal checkEmpty
jal toUpperCase
jal checkLen
jal isPalindrome
jal reset
j main
promptInput:
li $v0, 4
la $a0, promptString
syscall
la $a0, buffer
lw $a1, maxlen
li $v0, 8
syscall
jr $ra
checkEmpty:
lb $t1, buffer($t0)
beq $t1, $t6, exit
checkLen:
bgt $t4, $t7, errLen #input is too long
jr $ra
errLen:
li $v0, 4
la $a0, promptErr
syscall
j reset
isPalindrome:
li $t0, 0 # index = 0
addi $t4, $t4, -3 #decrement to the last character
j palinLoop
palinLoop:
lb $s1, str($t0)
lb $s2, str($t4)
beq $s1, $s2, pMatch #if characters match
j printFalse
pMatch:
ble $t4, $t0, printTrue #if indexes match
addi $t0, $t0, 1 #increment start index
addi $t4, $t4, -1 #decrement end index
j palinLoop
printTrue:
li $v0, 4
la $a0, promptTrue
syscall
jr $ra
printFalse:
li $v0, 4
la $a0, promptFalse
syscall
jr $ra
toUpperCase:
lb $t1, buffer($t0) # $t1 = get char
blt $t1, $t2, saveChar # $t1 < 'a' ? saveChar
bgt $t1, $t3, saveChar # $t1 > 'z' ? saveChar
j saveUpper
saveChar:
addi $t4, $t4, 1 # increment string length
sb $t1, str($t0) # store char into str
addi $t0, $t0, 1 # increment index
bne $t1, $0, toUpperCase # loop while not null
jr $ra # return from toUpperCase
saveUpper:
addi $t4, $t4, 1 # increment string length
sub $t1, $t1, $t5 # $t1 = lowercase $t1
sb $t1, str($t0) # store char into str
addi $t0, $t0, 1 # increment index
bne $t1, $0, toUpperCase # loop while not null
jr $ra # return from toUpperCase
reset:
li $t0, 0
li $t1, 0
li $s1, 0
li $s2, 0
j rLoop
rLoop:
sb $t1, str($t0) #erase str position
sb $t1, buffer($t0) #erase buffer position
addi $t0, $t0, 1 # increment index
beq $t0, $t7, rLoopEnd
j rLoop
rLoopEnd:
jr $ra
exit:
li $v0, 4
la $a0, promptExit
syscall
li $v0, 10
syscall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment