This is a question I saw in an interview :
A,B are non-negative numbers and you need to return C=|A-B| where you have only the following instructions:
Just decrement both in a loop until one of them gets to be zero. The other is obviously the result.
inc a
inc b ; make sure input is not zero
loop:
dec a
jnz skip
dec b
mov eax, b ; return b as answer
ret
skip:
dec b
jnz loop
mov eax, a ; return a as answer
ret
The original question as I saw it was:
Using jnz, inc, dec, and halt implement abs(a - b)
My answer:
There is no need to use the mov eax command. just store the result in the result register using the available commands. The solution decrements both A and B until one of them zero, then it sets the value of the other to RES register and halts the program execution. (when the program is halted the result will be in RES register).
My code would look like this:
// define/map names to the registers
#define A R0
#define B R1
#define RES R2
// This solution uses the assumption that A and B are not holding init value of negative numbers values.
// clear result if not already cleared.
DEC RES; // in case it was already cleared, this step will prevent counting through all possible values.
CLEAR_RESULT:
INC RES;
JNZ CLEAR_RES;
INC A; // to handle a case of A is initially zero
INC B; // to handle a case of B is initially zero
DEC_A:
DEC A;
JNZ DEC_B;
//Now A is zero, and the result is B-1;
SET_B_TO_RES:
INC RES;
DEC B;
JNZ SET_B_TO_RES;
DEC RES; // compensate the incr that was initially done to handle value of 0 (should only be done here...)
HALT;
DEC_B:
DEC B;
JNZ DEC_A;
//Now B is zero, and the result is A;
SET_A_TO_RES:
INC RES;
DEC A;
JNZ SET_A_TO_RES;
HALT;
// test values:
// =============
// A B
// 0 2 // A is zero
// 2 0 // B is zero
// 1 4 // A is smaller than B
// 5 2 // B is smaller than A
// 2 2 // A is equal to B
A solution with just the instructions allowed may be this (though not elegant). Where the pseudo registers a and b holds the operands and the pseudo register c the result (which is initially zero as stated).
_dec_a:
dec a
inc a
jnz _dec_b
;a is zero here
_a_zero_dec_b:
dec b
inc b
jnz _a_zero_b_non_zero
;a and b are zero here
;;C is the result
inc c
jnz _result
_a_zero_b_non_zero:
dec b
inc c
jnz _a_zero_dec_b
;CANNOT FALL HERE
_dec_b:
dec b
inc b
jnz _subtract
;b is zero here
_b_zero_dec_a:
dec a
inc a
jnz _b_zero_a_non_zero
;a and b are zero here
;; C is the result
inc c
jnz _result
_b_zero_a_non_zero:
dec a
inc c
jnz _b_zero_dec_a
;CANNOT FALL HERE
_subtract:
dec a
dec b
jnz _dec_a
;Result
_result:
dec c