Alternate Odd and Even Numbers with Two Goroutines
Problem statement
Write two workers that run at the same time and together produce the integers from 1 through n in increasing order. The odd worker produces only the odd numbers and the even worker produces only the even numbers, so the two workers take turns: 1 comes from the odd worker, 2 from the even worker, 3 from the odd worker, and so on.
In Go, run each worker in its own goroutine. In Java, Python, and C++, run each worker in its own thread. In JavaScript, run each worker in its own worker thread. Pass the turn from one worker to the other with synchronization, such as channels, a lock with a condition variable, or semaphores, and wait until both workers finish.
For this exercise, assume each worker adds its number to one shared output list instead of printing it, and the function returns that list after both workers finish.
The judge checks only the returned list. Building the list in one worker, or building two separate lists and merging them, returns the same list but skips the turn-taking that this question practices.
Function
alternateOddEven(n: int) → int[]Examples
Example 1
n = 5return = [1,2,3,4,5]The odd worker adds 1, 3, and 5. The even worker adds 2 and 4. They take turns, so the shared list is [1,2,3,4,5].
Example 2
n = 2return = [1,2]The odd worker adds 1 and hands the turn to the even worker, which adds 2. The list is [1,2].
Example 3
n = 1return = [1]Only the odd worker has a number to add. The even worker has no turn to take, and both workers still finish. The list is [1].
Constraints
1 <= n <= 1000