课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing

Solution: Rolling mean

(upbeat music) - [Instructor] Let's have a look at my implementation of the rolling mean method on lines 50 to 73. Channel and slice management are the key to solving this problem correctly. First, we declare a for loop which will allow our function to keep reading values until instructed to stop. On lines 52 to 57, we read the value and corresponding ok value from the input channel. If the ok value is false, indicating that the input channel has been closed, then we close the output channel and return terminating our infinite loop. Next up on lines 59 to 61, save the value received from the input channel, then increment the position and use the modular operator to ensure that we never exceed the capacity of the window. We increment the position after the element has been added, allowing us to use the index zero on the first element. On line 63 to 67, check the window filled field to see if we have enough values to calculate the mean. We'll have enough values as soon as the window has been filled for the first time. If the window has been previously filled, invoke the calculate mean method and send the value to the output channel. Finally, on line 69 to 71, deal with the window not filled case. This boolean value will be set to true the very first time that the position will be equal to the window size minus one. This signals that the next value received will fill the window and then we're able to calculate the first rolling mean. That's all the implementation we need. Let's have a look at the code in action. Looking closer at the test code, you can see that all the values are initialized as we expect, the rolling mean method is run in its own Go routine. Once the moving average struct is correctly configured further down, it uses another Go routine to loop through the numbers and writes them one by one to the input channel. Once all the values are written, it closes the input channel. Finally, it uses the read results function to read all the calculated rolling means. Let's execute this solution using the test my code button. The code returns the expected values and we have successfully completed the second challenge.

内容