![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find profession in a special family in C++
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
#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
Advertisements