Say I have 2 carts on an infinite railroad, each cart is initially under a lamp. There are only 2 lamps, and they are at a fixed location, hence they don't change their location. The distance between them is D, but its not known. Each cart has a processing unit, both will execute a copy of the same program once the whole system is "initiated".

The task: to write a code in pseudo-code, which will make the 2 carts collide.

Restrictions: The following commands can be used:

  1. move left/right *insert_number_here* steps //each movement takes 1 clock cycle, meaning that "move left C steps takes C clock cycles
  2. if underlamp *put_instruction_here* //if the cart is under a lamp
  3. goto *number_of_line_here*
  4. stop

Variables, loops and not (!) are usable.

the given solution is:

for i=1 to infinity:

  1. go left i steps.

  2. if underlamp stop.

  3. go right i steps.

Now, I need a hint to help me make a simple improvement to the algorithm that is given in the trivial solution, so when the distance between the lamps is D, the total number of steps of both carts will be a first order polynomial function of D.

My lecturer gave the following solution, and told me to improve the given code using a different idea. This is his solution:

  1. go right.
  2. go right.
  3. go left.
  4. if underlamp goto 6.
  5. goto 1.
  6. go right.
  7. goto 6.

My improvement of the given code, but I'm not sure that in this one, the total number of steps is a first order polynomial function of D.

for i=1 to infinity:

  1. go right i steps.

  2. if underlamp goto 4.

  3. go left.

4.for j=1 to infinity:

  1. go right j steps.

没有正确的解决方案

许可以下: CC-BY-SA归因
不隶属于 cs.stackexchange
scroll top