Skip to content

Commit 444f6d3

Browse files
authored
Merge pull request #606 from madihamallick/master
Added Job Sequencing Problem in C
2 parents 4f9d4fb + 9a219c7 commit 444f6d3

File tree

1 file changed

+122
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)