Last active
April 10, 2026 19:49
-
-
Save iharkatkavets/4005735c8e2881bf1955f51e5368cadb to your computer and use it in GitHub Desktop.
1115. Print FooBar Alternately (Swift version)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| // The problem repeats the LC problem '1115. Print FooBar Alternately' | |
| // https://leetcode.com/problems/print-in-order | |
| // Implement your solution inside the `FooBar` class. | |
| // Test with: swift main.swift | |
| final class FooBar: Sendable { | |
| let n: Int | |
| init(_ n: Int) { | |
| self.n = n | |
| } | |
| func foo(_ printFoo: @escaping @Sendable () async -> Void) async { | |
| for _ in 0..<n { | |
| await printFoo() // Don't change this line | |
| } | |
| } | |
| func bar(_ printBar: @escaping @Sendable () async -> Void) async { | |
| for _ in 0..<n { | |
| await printBar() // Don't change this line | |
| } | |
| } | |
| } | |
| // MARK: - | |
| // This section is required for the problem testing. | |
| // Do not modify. | |
| let expected = | |
| "foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar" | |
| for _ in 0..<10_000 { | |
| await runSolution() | |
| } | |
| func runSolution() async { | |
| actor Context { | |
| var str = "" | |
| func append(_ suffix: String) { | |
| str += suffix | |
| } | |
| } | |
| let result = await withTaskGroup(of: Void.self) { group in | |
| let fb = FooBar(100) | |
| let result = Context() | |
| group.addTask { | |
| await fb.bar { | |
| await result.append("bar") | |
| } | |
| } | |
| group.addTask { | |
| await fb.foo { | |
| await result.append("foo") | |
| } | |
| } | |
| await group.waitForAll() | |
| return await result.str | |
| } | |
| assert(result == expected, "Wrong string:\n\(result)\nExpected string:\n\(expected)") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment