第 28 关,三排序。指令介绍请看:https://www.annhe.net/article-3828.html。
优化目标
34行78步
代码
62行75步
参考 Github。基本思路是,不动数字在地毯上的位置,改变outbox顺序:
- 将前两个数放到 1,3号地毯
- 3 - 1,如小于零,认为输出是 right 方向,取第三个数,如果比3号还小,那就直接输出,然后输出 3,1
- 如果比3号大但是比1号小,输出 3,2,1
- 如果比1号大,输出 3,1,2
- 3 - 1,如大于零,认为输出是 left 方向,取第三个数,如果比1号小,就直接输出,然后输出 1,3
- 如果比1号大但是比3号小,输出 1,2,3
- 如果比3号大,输出 1,3,2
代码行数还有优化空间,比参考代码多了16行
JUMP start
r123:
COPYFROM 1
OUTBOX
COPYFROM 2
OUTBOX
COPYFROM 3
OUTBOX
JUMP start
r321:
COPYFROM 3
OUTBOX
COPYFROM 2
OUTBOX
COPYFROM 1
OUTBOX
start:
INBOX
COPYTO 1
INBOX
COPYTO 3
SUB 1
JUMPN right
INBOX
COPYTO 2
SUB 1
JUMPN left2
ADD 1
SUB 3
JUMPN r123
COPYFROM 1
OUTBOX
COPYFROM 3
OUTBOX
COPYFROM 2
OUTBOX
JUMP start
right:
INBOX
COPYTO 2
SUB 3
JUMPN right2
ADD 3
SUB 1
JUMPN r321
COPYFROM 3
OUTBOX
COPYFROM 1
OUTBOX
COPYFROM 2
OUTBOX
JUMP start
right2:
ADD 3
OUTBOX
COPYFROM 3
OUTBOX
COPYFROM 1
OUTBOX
JUMP start
left2:
ADD 1
OUTBOX
COPYFROM 1
OUTBOX
COPYFROM 3
OUTBOX
JUMP start
28行115步
参考 Github。
如何不引入第三个变量交换2个变量的值(a, b)
- a, b-a
- b-a+a, b-a
- b-a+a, b-a+a-b+a
或者
- a-b, b
- a-b, b+a-b
- b+a-b-a+b, b+a-b
start:
INBOX
COPYTO 0
INBOX
COPYTO 2
INBOX
main:
COPYTO 1
SUB 2
JUMPN c0
COPYTO 1
ADD 2
COPYTO 2
SUB 1
COPYTO 1
c0:
COPYFROM 1
SUB 0
JUMPN switch10
COPYFROM 0
OUTBOX
COPYFROM 1
OUTBOX
COPYFROM 2
OUTBOX
JUMP start
switch10:
COPYTO 1
ADD 0
COPYTO 0
SUB 1
JUMP main
第N次 38行103步
JUMP init
out:
COPYFROM 0
OUTBOX
COPYFROM 1
OUTBOX
COPYFROM 2
OUTBOX
init:
INBOX
COPYTO 0
COPYTO 1
COPYTO 2
INBOX
SUB 0
JUMPN start
ADD 0
COPYTO 1
COPYTO 2
third:
INBOX
COPYTO 9
SUB 0
JUMPN start2
ADD 0
SUB 1
JUMPN insert
ADD 1
COPYTO 2
JUMP out
start:
ADD 0
COPYTO 0
JUMP third
start2:
COPYFROM 0
COPYTO 1
COPYFROM 9
COPYTO 0
JUMP out
insert:
ADD 1
COPYTO 1
JUMP out
第一次pass 44行109步
JUMP init
out:
COPYFROM 0
OUTBOX
COPYFROM 1
OUTBOX
COPYFROM 2
OUTBOX
init:
INBOX
COPYTO 0
INBOX
COPYTO 1
INBOX
COPYTO 2
main:
SUB 0
JUMPN switch0
a:
COPYFROM 2
SUB 1
JUMPN switch1
b:
COPYFROM 1
SUB 0
JUMPN switch
JUMP out
switch0:
COPYFROM 2
COPYTO 3
COPYFROM 0
COPYTO 2
COPYFROM 3
COPYTO 0
COPYFROM 2
JUMP a
switch1:
COPYFROM 2
COPYTO 3
COPYFROM 1
COPYTO 2
COPYFROM 3
COPYTO 1
JUMP b
switch:
COPYFROM 1
COPYTO 3
COPYFROM 0
COPYTO 1
COPYFROM 3
COPYTO 0
JUMP out
发表回复