job sequencing (ada)
Thu Sep 19 2024 05:20:01 GMT+0000 (Coordinated Universal Time)
Saved by
@signup
import java.util.Arrays;
import java.util.Scanner;
class Job {
int id;
int deadline;
int profit;
Job(int id, int deadline, int profit) {
this.id = id;
this.deadline = deadline;
this.profit = profit;
}
}
public class JobScheduling {
public static void scheduleJobs(Job[] jobs) {
// Sort jobs based on profit in descending order
Arrays.sort(jobs, (a, b) -> b.profit - a.profit);
// Find the maximum deadline
int maxDeadline = 0;
for (Job job : jobs) {
if (job.deadline > maxDeadline) {
maxDeadline = job.deadline;
}
}
// Create a slot array based on maximum deadline
boolean[] slot = new boolean[maxDeadline];
int[] result = new int[maxDeadline];
for (Job job : jobs) {
// Find a free slot for this job
for (int j = Math.min(maxDeadline - 1, job.deadline - 1); j >= 0; j--) {
if (!slot[j]) {
slot[j] = true;
result[j] = job.id;
break;
}
}
}
// Output the scheduled jobs
System.out.println("Scheduled Jobs:");
for (int jobId : result) {
if (jobId != 0) {
System.out.print(jobId + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of jobs: ");
int n = sc.nextInt();
Job[] jobs = new Job[n];
System.out.println("Enter jobs (id, deadline, profit):");
for (int i = 0; i < n; i++) {
int id = sc.nextInt();
int deadline = sc.nextInt();
int profit = sc.nextInt();
jobs[i] = new Job(id, deadline, profit);
}
scheduleJobs(jobs);
sc.close();
}
}
content_copyCOPY
Comments