0

Map and Fold

I am trying to implement a fold and map in an array to output the standard deviation. I had it working when I used only for loops and not the recursion. When I enter the following in the playground the output is incorrect: Input: 8 2 4 4 4 5 5 7 9 Output should read: Avg: 5.00 SD: 2.00 SSD: 2.14 https://code.sololearn.com/cCctvUp8qtMf

13th Mar 2022, 5:44 PM
William Owens
William Owens - avatar
3 Antworten
+ 3
Your map function should modify the list, should it not? Not only does it not modify the list, it shifts the list pointer, so that at the end it would return a pointer past the last element of the original list. You do not use the return value, so you would not notice at the moment. But the map function needs rework, the foldl looks good.
13th Mar 2022, 6:33 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
This could work: static float *map(float (*fun)(float, float), float *list, size_t size, float avg){ if ( size != 0 ) { *list = fun(*list, avg); map(fun, list + 1, size - 1, avg); } return list; }
13th Mar 2022, 6:44 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Ani Jona Thank you that was perfect, I also had to change a bit in line 40.
13th Mar 2022, 7:29 PM
William Owens
William Owens - avatar