TASK #1 › Average of Stream
Task
You are given a stream of numbers @N
.
Write a script to print the average of the stream at every point.
My solution
This is relatively straight forward, and the work is done with this bit of code map { ++$cnt; $sum += $_; $sum / $cnt } @N
. Basically, I add 1 to the counter and the value to the sum, and calculate the average (sum ÷ counter) at the point.
One thing that isn't explained is what happens when the average is not a whole number. Since there is no guidance on what to do, I will print out what Perl does. So one third shows as 0.333333333333333
Example
$ ./ch-1.pl 10 20 30 40 50 60 70 80 90
10 15 20 25 30 35 40 45 50
TASK #2 › Basketball Points
Task
You are given a score $S
.
You can win basketball points e.g. 1 point, 2 points and 3 points.
Write a script to find out the different ways you can score $S
.
My solution
When I saw this task, I immediately thought of the Climb Stairs task from Challenge 112. I used a similar methodology to solve this one.
The main work is done in the recursive function _score
(was called _climb
in the previous challenge). If there are three or fewer points remaining, I show the scoring shots to make the required points. If there is more than 1 point remaining, I call the _score
subroutine again for 1, 2 and 3 points if at least 1 more than that shot's point remain.
Examples
$ ./ch-2.pl 4
1 3
1 1 2
1 1 1 1
1 2 1
2 2
2 1 1
3 1
$ ./ch-2.pl 5
1 1 3
1 1 1 2
1 1 1 1 1
1 1 2 1
1 2 2
1 2 1 1
1 3 1
2 3
2 1 2
2 1 1 1
2 2 1
3 2
3 1 1
Top comments (0)