john_l 0 Newbie Poster

I'm writing a program using the LC-3 Simulator with limited instructions. I'm trying to solve the problem "n choose r" recursively. I'm having difficulty pin pointing where my programs going wrong. Any help would be greatly appreciated.

.orig x3000

	;Clear registers
	and r0, r0, #0
	and r1, r1, #0
	and r2, r2, #0
	and r3, r3, #0
	and r4, r4, #0
	and r6, r6, #0
	and r7, r7, #0

        ;parameters
        add r0, r0, #4
        add r1, r1, #2

	ld r6, stackBase	;beginning of stack

	;Push param1 and param2 on stack
	add r6, r6, #-2

	str r0, r6, #1
	str r1, r6, #0

	jsr NchooseR		;NchooseR( r0, r1 )

	lea r0, eopMssg
	puts

	halt

	stackBase	.fill	xFD00

	eopMssg
		.stringz "\n\nEnd of processing..."

NchooseR			;NchooseR( r0, r1 )

	add r6, r6, #-2

	str r2, r6, #0            ;save r2
	str r7, r6, #1            ;save r7

	;load param1 and param2
	ldr r0, r6, #3		;r0 <- param1
	ldr r1, r6, #2		;r1 <- param2

	not r3, r1
	add r3, r3, #1		;-param2

	add r3, r0, r3		;param1-param2

	brnz NchooseRSpecialCase

	add r1, r1, #0		;check if param2 is zero
	
	brz NchooseRSpecialCase
	
	add r0, r0, #-1		
	br NchooseRGeneral

     NchooseRSpecialCase	;r = 0

	add r0, r0, #0		;n < 0
	brn NchooseRReturn

	and r0, r0, #0		;zero out register
	add r0, r0, #1		;return 1
	br NchooseRReturn

     NchooseRGeneral

	add r6, r6, #-2
	str r0, r6, #1		;push param1 - 1
	str r1, r6, #0		;push param2

	jsr NchooseR		;r0 <- NchooseR( param1 - 1, r1 )
	add r6, r6, #2		;pop param1 - 1 and param2

	add r2, r0, #0		;r2 <- NchooseR( param1-1, param2 )

	ldr r0, r6, #2		;r0 <- param1-1
	ldr r1, r6, #1		;r1 <- param2

	add r0, r0, #0		;r0 <- param1	;
	add r1, r1, #-1		;r1 <- param2 - 1

	;push variables on stack
	add r6, r6, #-2
	str r0, r6, #1		;push param1
	str r1, r6, #0		;push param2-1

	jsr NchooseR		;NchooseR( param1-1, param2-1 )
	add r6, r6, #2

	add r0, r0, r2		;r0<- NchooseR(n-1, r) + NchooseR(n-1, r-1)
 
     NchooseRReturn

	ldr r2, r6, #0          ;restore r2
	ldr r7, r6, #1		;restore r7
	add r6, r6, #2		;pop locals and parameters

	ret
   
        .end
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.