Algorithm


Problem Name: 1115. Print FooBar Alternately

Suppose you are given the following code:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

The same instance of FooBar will be passed to two different threads:

  • thread A will call foo(), while
  • thread B will call bar().

Modify the given program to output "foobar" n times.

 

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
"foobar" is being output 1 time.

Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.

 

Constraints:

  • 1 <= n <= 1000

Code Examples

#1 Code Example with Python Programming

Code - Python Programming


import threading
class FooBar(object):
    def __init__(self, n):
        self.n = n
        self.f = threading.Semaphore()
        self.b = threading.Semaphore()
        self.b.acquire()

    def foo(self, printFoo):
        """
        :type printFoo: method
        :rtype: void
        """
        for i in range(self.n):
            self.f.acquire()
            # printFoo() outputs "foo". Do not change or remove this line.
            printFoo()
            self.b.release()


    def bar(self, printBar):
        """
        :type printBar: method
        :rtype: void
        """
        for i in range(self.n):
            self.b.acquire()
            # printBar() outputs "bar". Do not change or remove this line.
            printBar()
            self.f.release()
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
#1114 Leetcode Print in Order Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1116 Leetcode Print Zero Even Odd Solution in C, C++, Java, JavaScript, Python, C# Leetcode