-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathjob_sequencing_greedyMethod.c
122 lines (112 loc) · 2.56 KB
/
job_sequencing_greedyMethod.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*Write a program to implement the job sequencing with deadline problem using greedy method. Consider the
following data for the problem. N=4
JOB: J1 J2 J3 J4
PROFIT: 100 10 15 27
DEADLINE: 2 1 2 1
*/
#include <stdio.h>
// Structure of each job
struct job
{
int id;
int profit;
int deadline;
};
/* Auxiliary Functions */
int scanJobs(struct job Jobs[], int n)
{
// Scan n number of jobs
int i, max_deadline = 0;
for (i = 0; i < n; i++)
{
printf("Enter the profit and deadline of job (J%d): ", i + 1);
scanf("%d %d", &Jobs[i].profit, &Jobs[i].deadline);
Jobs[i].id = i + 1;
if (Jobs[i].deadline > max_deadline)
{
max_deadline = Jobs[i].deadline;
}
}
return max_deadline;
}
void sort(struct job Jobs[], int n)
{
// Sort the job in descending order of profit
int i, j;
struct job key;
for (i = 1; i < n; i++)
{
key = Jobs[i];
j = i - 1;
while ((j >= 0) && (Jobs[j].profit < key.profit))
{
Jobs[j + 1] = Jobs[j];
j--;
}
Jobs[j + 1] = key;
}
}
int isEmpty(int arr[], int i)
{
// Returns True if i'th slot of an array is empty
return arr[i] == 0 ? 1 : 0;
}
void initSlots(int arr[], int m)
{
// Initialise job slots to 0
int i;
for (i = 0; i < m; i++)
{
arr[i] = 0;
}
}
int job_sequencing(struct job Jobs[], int m)
{
// Job sequencing function
int slots[m], profit = 0;
initSlots(slots, m);
int i, j, deadlineIdx;
for (i = 0; i < m; i++)
{
deadlineIdx = Jobs[i].deadline - 1;
if (isEmpty(slots, deadlineIdx))
{
slots[deadlineIdx] = Jobs[i].id;
profit += Jobs[i].profit;
}
else
{
for (j = deadlineIdx - 1; j >= 0; j--)
{
if (isEmpty(slots, j))
{
slots[j] = Jobs[i].id;
profit += Jobs[i].profit;
}
}
}
}
printf("\nJobs sequence: { ");
for (i = 0; i < m; i++)
{
printf("J%d ", slots[i]);
}
printf("}");
return profit;
}
int main()
{
int n, m, max_profit;
/*
n: number of jobs
m: number of job slots
*/
printf("Enter the number of jobs: ");
scanf("%d", &n);
struct job Jobs[n];
m = scanJobs(Jobs, n);
sort(Jobs, n);
max_profit = job_sequencing(Jobs, m);
printf("\nOptimal maximum profit: %d\n", max_profit);
return 0;
}