Find profession in a special family in C++

C++Server Side ProgrammingProgramming

Consider there is a special family of doctors and engineers. There are some rules, these are like below −

  • Everybody has two children
  • First child of an engineer is an engineer, second child is doctor
  • First child of a doctor is a doctor, second child is an engineer
  • All generations of doctors and engineers starts with engineer

So if we want to get result for level 4 and pos 2, then result will be Doctor

The idea is simple. Profession of a person depends on following two.

  • Profession of the parent.
  • Position of node: When the position of a node is odd, then its profession is same as its parent. otherwise profession is different from its parent.

We recursively find the profession of parent, then use point 2 above to find the profession of current node.

Example

 Live Demo

#include<iostream>
using namespace std;
char getProfession(int level, int pos) {
   if (level == 1)
   return 'E';
   if (getProfession(level-1, (pos+1)/2) == 'D')
   return (pos%2)? 'D' : 'E';
   return (pos%2)? 'E' : 'D';
}
int main(void) {
   int level = 4, pos = 2;
   cout << "The profession is: ";
   if(getProfession(level, pos) == 'E'){
      cout << "Engineer";
   } else {
      cout << "Doctor" ;
   }
}

Output

The profession is: Doctor
raja
Published on 17-Dec-2019 11:12:15
Advertisements