# Copy Memory Only Using Store And Subtraction

A peer of mine approached me with this challenge and I wasn't able to come up with an elegant solution. After discussing my approach, we began to wonder what the people at Code Golf would come up with.

# Given

• A processor that implements only two instructions:

1. STO <register>, <address> (store from this register to this address)
2. SUB <register>, <address> (subtract the value at this address from this register)
• It also only contains 2, 32-bit registers: A and B
• As well as 2, 32-bit RAM address: 0x00 and 0x01
• The values of A and B are unknown

# Challenge

Write a program to copy RAM address 0x00 into 0x01 optimised to use the fewest number of instructions possible.

• Welcome to PCG! Note that this isn't a very good challenge. It's simple enough to likely only have one good solution. Try using the Sandbox for Proposed Challenges first next time to get feedback about proposed challenges. Thanks. Jun 12, 2015 at 21:15
• @mbomb007 Thank you, I'm new and figured there was a better way to do this. I'm sorry for the poor question and I greatly appreciate the help. Thank you! Jun 12, 2015 at 21:18

Assuming registers are signed and/or wrapping

8 instructions:

STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x00
SUB A 0x00
SUB A 0x00
STO A 0x00
STO A 0x01


A 7-instruction version provided by lrn:

STO A 0x01
SUB A 0x01
SUB A 0x00
STO A 0x01
SUB A 0x01
SUB A 0x01
STO A 0x01

• That and the next instruction serve to zero register A. Then we do a what amounts to [00]=-[00], then some more stuff to restore [00] to its original value while simultaneously setting A to that value, then we write that value to [01]. The requirement was that [01] and [00] both end up having the value that [00] initially had. Jun 12, 2015 at 20:50
• Oops, I read the challenge as being to swap the memory locations. Jun 12, 2015 at 21:00
• @feersum: I don't think you could do that with this command set without adding a third address. Jun 12, 2015 at 21:02
• @Brett Can you post yours, please? I'm interested. Jun 12, 2015 at 21:17
• Why store A to 0x00 in the second to last step? If you use 0x01 as temporary in step 4 and forward, you don't need to store back into 0x00. That is: STO A 0x01; SUB A 0x01; SUB A 0x00; STO A 0x01; SUB A 0x01; SUB A 0x01; STO A 0x01 should copy 0x00 to 0x01 and keep 0x00 unchanged in one instruction less.
– lrn
Jun 12, 2015 at 22:58