Jump to content

Talk:100 doors/8086 Assembly

From Rosetta Code

More optimized implementation

(using the syntax for "flat assembler") <lang asm> format binary org 0x0100

Initialization
Marking 100 doors as closed
   mov di,doors
   xor ax,ax ; two zero-value bytes
   mov cx,0x32
   rep stosw ; fill 50 words (50 * 2 bytes)
The result of "100 doors" task will be
"1 00 1 0000 1 000000 1 ..."
Every open door is offset by the next multiple of 2 closed doors
Following the steps
[next_position] = previous_position + counter
counter = counter + 2
where [0] is the first door position
and the counter is set to 3
[3] = 0 + (1 + 2)
[8] = 3 + (3 + 2)
[15] = 8 + (5 + 2)
etc.
   not al ; open door is marked by byte 0xFF
   mov di,doors
   
   ; the `stosb` instruction will always increase the destination register
   ; we can use this fact to initialize the counter with 2
   ; by setting it to 0 and increasing at the beginning of the loop
   xor cx,cx ; is 2 bytes long, where `mov cx,0x02` is 3 bytes long
 .door_loop:
   inc cx ; or `add cl,0x02`, although this approach uses less bytes
   inc cx
   stosb
   ; Notice that `ch` (upper 8 bits of `cx`) here needs to be set to 0
   ; because we are adding 16-bit registers
   add di,cx
   cmp di,(doors + 0x64) ; have we reached the 101th door?
     jb .door_loop ; if not, continue the loop
Here you can implement some code that outputs the result to the screen
Exiting the program (assuming it is run under MS-DOS)
   mov ax,0x4C00
   int 0x21
Pointer to the uninitialized memory allocated for the COM file
directly after our code

doors: </lang>

Compiled code is 33 bytes long, including 10 bytes of instructions for 100 bytes table initialization.

Flower35 (talk) 18:29, 23 April 2020 (UTC)

Cookies help us deliver our services. By using our services, you agree to our use of cookies.