Store tasks (name, priority 1 = highest, deadline day) in a PriorityQueue ordered by priority then deadline then name, and print the order in which they should be done.
Solution
Main.java
import java.util.Comparator;
import java.util.PriorityQueue;
record Task(String name, int priority, int deadline) { }
public class Main {
public static void main(String[] args) {
PriorityQueue<Task> pq = new PriorityQueue<>(Comparator.comparingInt(Task::priority).thenComparingInt(Task::deadline).thenComparing(Task::name));
pq.add(new Task("Write report", 2, 5));
pq.add(new Task("Fix prod bug", 1, 1));
pq.add(new Task("Code review", 2, 3));
pq.add(new Task("Team lunch", 3, 2));
pq.add(new Task("Deploy patch", 1, 1));
pq.add(new Task("Update docs", 3, 9));
int step = 1;
while (!pq.isEmpty()) {
Task t = pq.poll();
System.out.printf("%d. %-13s P%d day %d%n", step++, t.name(), t.priority(), t.deadline());
}
}
}
Output Verified by compiling and running
1. Deploy patch P1 day 1
2. Fix prod bug P1 day 1
3. Code review P2 day 3
4. Write report P2 day 5
5. Team lunch P3 day 2
6. Update docs P3 day 9
A chained Comparator defines the priority; ties on priority and deadline fall back to the name.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!