A study plan turns topics and their hours into weeks. Doing the topics in order, a fixed number of hours each week, shows when each one will be done.
What to build
Schedule topics in order into weeks of a fixed number of study hours.
Requirements
- Line 1: hours available per week (a whole number, at least 1). Each remaining line is
topic hours. - Study topics in the given order, filling each week's hours before moving to the next week; a topic can continue into the next week.
- For each topic print
topic: weeks A-B, the first and last week it is studied in (weeks Aif it starts and ends in the same week). - At the end print
total: W weeks(the last week used).
Input
As described.
Output
One line per topic, then the total.
Constraints
Up to 50 topics. Hours are whole numbers from 1 to 1000.
Example
Input:
6
networking 10
linux 8
web-security 12
Output:
networking: weeks 1-2
linux: weeks 2-3
web-security: weeks 4-5
total: 5 weeks
Why it works
Keeping a running total of hours makes it easy to find any hour's week: week = floor((hour − 1) ÷ hours per week) + 1, applied to each topic's first and last hour.
Examples
Example 1 · Input
6 networking 10 linux 8 web-security 12
Expected output
networking: weeks 1-2 linux: weeks 2-3 web-security: weeks 4-5 total: 5 weeks
Example 2 · Input
10 one 10 two 10
Expected output
one: weeks 1 two: weeks 2 total: 2 weeks
Hints
Hint 1
Track the total hours studied before each topic starts.
Solution
Show one correct solution (try it yourself first)
const perWeek = Number(prompt());
let done = 0;
const week = (hour) => Math.floor((hour - 1) / perWeek) + 1;
let line = prompt();
while (line !== null) {
if (line.trim()) {
const [topic, hoursText] = line.trim().split(/\s+/);
const hours = Number(hoursText);
const first = week(done + 1);
const last = week(done + hours);
done += hours;
console.log(first === last ? `${topic}: weeks ${first}` : `${topic}: weeks ${first}-${last}`);
}
line = prompt();
}
console.log(`total: ${done ? week(done) : 0} weeks`);
▶ Open this solution in the compiler, then press Visualize to watch it run step by step