Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หา Resulting Colour Combination ใน C++

มี String 3 สี (G, B, Y) ต้องหา Resulting Color จาก Rules:

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

ตัวอย่าง "GBYGB" = B, "BYB" = Y

วิธี: Compare Adjacent Characters ตาม Rules หา Color

ตัวอย่างโค้ด C++

#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);
}

ผลลัพธ์

Color Combination Result: B