Leetcode

LeetCode 1115. Print FooBar Alternately [C++/ promise]

치킨먹고싶어요 2022. 6. 3. 16:32

https://leetcode.com/problems/print-foobar-alternately/

 

Print FooBar Alternately - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

코드 :

class FooBar {
private:
    int n;
    std::promise<bool> a, b; // 꼭 출력해줄 것이라 약속한다
public:
    FooBar(int n) {
        this->= n;
        b.set_value(true); // foo를 먼저 출력해야하므로 b를 먼저 출력을 허가해 준다
    }
 
    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            b.get_future().get(); // b를 받는다
            printFoo();
            a = promise<bool>();
            a.set_value(true); // a를 출력해 줄 것이라 약속한다
        }
    }
 
    void bar(function<void()> printBar) {
        for (int i = 0; i < n; i++) {
            a.get_future().get(); // a를 받는다
            printBar();
            b = promise<bool>();
            b.set_value(true); // b를 출력해 줄 것이라 약속한다
        }
    }
};
cs