Problems › TypeScript › finance
Average monthly figures for a year
Twelve monthly totals summarise a year. Report the average monthly figure, dropping the fractional minor unit.
- The list always carries twelve whole entries for a real year.
- Average is the total divided by 12, rounded down.
- A list with fewer than twelve entries is not a full year: return 0.
yearlyAverage(monthlyTotals: list<int>) → int
Where you start
function yearlyAverage(monthlyTotals: number[]): number {
}
Worked examples
| Call | Result |
|---|---|
yearlyAverage([1,1,1,1,1,1,1,1,1,1,1,1]) | 1 |
yearlyAverage([1,2,3,4,5,6,7,8,9,10,11,12]) | 6 |
yearlyAverage([0,0,0,0,0,0,0,0,0,0,0,0]) | 0 |
yearlyAverage([100,100,100,100,100,100,100,100,100,100,100,100]) | 100 |
Hint
Guard the length, sum the entries, divide by twelve.
Reference solution in TypeScript
function yearlyAverage(monthlyTotals: number[]): number {
if (monthlyTotals.length < 12) return 0;
let sum = 0;
for (const v of monthlyTotals) sum += v;
return Math.floor(sum / 12);
}