C++ Program to find out the health of a character

C++Server Side ProgrammingProgramming

Suppose, we are playing a 2d scrolling game. The character of the game is currently located in position pos with health h. When the character proceeds in the game, he gains pos amount of health, and the pos value decreases in each step. Whenever the character encounters an obstacle at position oh or ph, the character's health decreases by od or pd respectively. The character stops moving only when he is in pos 0. We have to find out the health h of the character in position pos = 0.

Problem Category

Various problems in programming can be solved through different techniques. To solve a problem, we have to devise an algorithm first, and to do that we have to study the particular problem in detail. A recursive approach can be used if there is a recurring appearance of the same problem over and over again; alternatively, we can use iterative structures also. Control statements such as if-else and switch cases can be used to control the flow of logic in the program. Efficient usage of variables and data structures provides an easier solution and a lightweight, low-memory-requiring program. We have to look at the existing programming techniques, such as Divide-and-conquer, Greedy Programming, Dynamic Programming, and find out if they can be used. This problem can be solved by some basic logic or a brute-force approach. Follow the following contents to understand the approach better.

So, if the input of our problem is like pos = 6, h = 5, oh = 3, od = 3, ph = 3, pd = 4, then the output will be 15.

Steps

To solve this, we will follow these steps −

while h is not equal to -1, do:
   pos := pos + h
   if h is same as ph, then:
      pos := pos - oh
   if h is same as pd, then:
      pos := pos - od
   if pos < 0, then:
      pos := 0
   (decrease h by 1)
print(pos)

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
void solve(int pos, int h, int oh, int od, int ph, int pd) {
   while(h != -1){
      pos = pos + h;
         if(h == ph)
            pos -= oh;
         if(h == pd)
            pos -= od;
         if(pos < 0)
            pos = 0;
         h--;
   }
   cout<< pos;
}
int main() {
   int pos = 6, h = 5, oh = 3, od = 3, ph = 3, pd = 4;
   solve(pos, h, oh, od, ph, pd);
   return 0;
}

Input

6, 5, 3, 3, 3, 4

Output

15
raja
Updated on 07-Apr-2022 10:18:20

Advertisements