Find the resulting Colour Combination in C++


We have a string with three colors (G, B, Y). We have to find the resulting color based on these relations −

  • B * G = Y
  • Y * B = G
  • G * Y = B

Suppose the string is “GBYGB” is B. If the string is “BYB”, then it will be Y.

The approach is simple; we will take the string. Compare each alphabet with adjacent characters, using the given condition, find the color.

Example

Live Demo

#include <iostream>
using namespace std;
char combination(string s) {
   char color = s[0];
   for (int i = 1; i < s.length(); i++) {
      if (color != s[i]) {
         if ((color == 'B' || color == 'G') && (s[i] == 'G' || s[i] == 'B'))
            color = 'Y';
            else if ((color == 'B' || color == 'Y') && (s[i] == 'Y' || s[i] == 'B'))
               color = 'G';
         else
            color = 'B';
      }
   }
   return color;
}
int main() {
   string color_str = "GBYBGY";
   cout << "Color Combination Result: " << combination(color_str);
}

Output

Color Combination Result: B

Updated on: 21-Oct-2019

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements