-
Notifications
You must be signed in to change notification settings - Fork 0
/
dp2.c
80 lines (70 loc) · 1.78 KB
/
dp2.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
#include<stdio.h>
#include<stdlib.h>
int mutex[20];
int main()
{
int n,i,ch,j;
printf("Enter the number of philosophers\n");
scanf("%d", &n);
for(i=0;i<n;i++)
mutex[i]=1;
printf("Initial State is: \n");
for(i=0;i<n;i++)
printf("Philosopher %d is thinking\n",i);
printf("enter the number of rounds\n");
scanf("%d",&ch);
for(j=0;j<ch;j++)
{
int random=rand()%n;
int r=rand()%2;
mutex[random]=r;
for(i=(random+1)%n;i!=random;i=(i+1)%n)
{
r=rand()%2;
if(r==0)
{ if(i==0)
{
if(mutex[n-1]==1)
mutex[i]=0;
else mutex[i]=1;
}
else if(mutex[(i-1)%n]==1)
mutex[i]=0;
else mutex[i]=1;
}
else mutex[i]=1;
}
r=rand()%2;
i=(random-1)%n;
if(i<0) i+=n;
if(r==0)
{
if(i==0)
{
if(mutex[n-1]==1 && mutex[(i+1)%n]==1)
mutex[i]=0;
else
mutex[i]=1;
}
else if(mutex[(i-1)%n]==1 && mutex[(i+1)%n]==1)
mutex[i]=0;
else mutex[i]=1;
}
else mutex[i]=1;
printf("Next Round is\n");
for(i=0;i<n;i++)
{
if(mutex[i]==1)
{
printf("Philosopher %d is thinking\n",i);
printf("%d ",0);
}
else
{
printf("Philosopher %d is eating\n",i);
printf("%d ",1);
}
}
printf("\n");
}
}