Program to Find Out the Number of Moves to Reach the Finish Line in Python

PythonServer Side ProgrammingProgramming

Suppose, we have a car and are driving it on a one−dimensional road. Currently we are at position = 0 and with speed = 1. We can perform any of these two operations.

  • Acceleration: position := position + speed and speed := speed * 2 Reverse Gear: speed := −1 when speed > 0 otherwise speed := 1.

We have to find the number of moves needed at least to reach the target.

So, if the input is like target = 10, then the output will be 7.

To solve this, we will follow these steps −

  • Define a function dfs() . This will take digit, cost, pos, neg, target

    • tot := cost + maximum of 2 *(pos − 1) and 2 * (neg − 1)

    • if tot >= ans, then

      • return

    • if target is same as 0, then

      • ans := minimum of ans and tot

      • return

    • step := (2^digit) − 1

    • if step * 2 < |target|, then

      • return

    • dfs(digit − 1, cost, pos, neg, target)

    • dfs(digit − 1, cost + digit, pos + 1, neg, target − step)

    • dfs(digit − 1, cost + digit * 2, pos + 2, neg, target − step * 2)

    • dfs(digit − 1, cost + digit, pos, neg + 1, target + step)

    • dfs(digit − 1, cost + digit * 2, pos, neg + 2, target + step * 2)

  • From the main function, do the following −

  • ans := infinity

  • hi := 1

  • while 2^hi < target, do

    • hi := hi + 1

  • dfs(hi, 0, 0, 0, target)

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, target):
      self.ans = int(1e9)
      hi = 1
      while (1 << hi) < target:
         hi += 1
      self.dfs(hi, 0, 0, 0, target)
      return self.ans
   def dfs(self, digit, cost, pos, neg, target):
      tot = cost + max(2 * (pos − 1), 2 * neg − 1)
      if tot >= self.ans:
         return
      if target == 0:
         self.ans = min(self.ans, tot)
         return
      step = (1 << digit) − 1
      if step * 2 < abs(target):
         return
      self.dfs(digit − 1, cost, pos, neg, target)
      self.dfs(digit − 1, cost + digit, pos + 1, neg, target − step)
      self.dfs(digit − 1, cost + digit * 2, pos + 2, neg, target − step * 2)
      self.dfs(digit − 1, cost + digit, pos, neg + 1, target + step)
      self.dfs(digit − 1, cost + digit * 2, pos, neg + 2, target + step * 2)
ob = Solution()
print(ob.solve(10))

Input

10

Output

7
raja
Published on 26-Dec-2020 11:24:53
Advertisements