# Semaphore and Critical section

Before understanding semaphore we should first discuss the critical section.
critical section is a piece of code that can be executed by two or more process at a time. Because of the simultaneous access of code our data might get inconsistent. To avoid this inconsistency we use synchronization methods.

so semaphore is one of the synchronization technique. It is a locking mechanism which is use to provide a lock for the access of critical section. If a process wants to access the critical section it has to acquire the lock first and free the lock once it has completed their work. When one process is already having the lock and other process try to acquire the lock then that process has to wait for the time till the lock is freed by previous process.

suppose we have total n number of same object and for that we have n number of lock. if a process try to acquire a lock and lock is available then the value of lock will be decreased by one or if lock is not available then that process has to wait till the time any lock is available. we can understand this by following example.

total number of objects = 3

total number of locks available =3

# Counting Digits from given Range

Imagine you sell those metallic digits used to number houses, locker doors, hotel rooms, etc. You need to find how many of each digit to ship when your customer needs to number doors/houses:
1 to 100
51 to 300
1 to 2,000 with zeros to the left
The obvious solution is to do a loop from the first to the last number, convert the counter to a string with or without zeros to the left, extract each digit and use it as an index to increment an array of 10 integers.
I wonder if there is a better way to solve this, without having to loop through the entire integers range.
Thanx to mathematician’s Post that helped me to understand the complexity of problem, i just understood the equation and converted it to code. Enjoy !

# Minimum cost flow House coloring with three colors

There are a row of houses, each house can be painted with three colors red, blue and green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. You have to paint the houses with minimum cost. How would you do it?

Note: Painting house-1 with red costs different from painting house-2 with red. The costs are different for each house and each color.

Approach:
Dynamic Programming solution:
we can paint the i’th house with blue, red or green.

```Enter No. of Houses to paint : 6
1 4 5
1 3 9
6 7 2
9 6 4
3 5 2
6 7 4

Minimum Cost to paint all houses are 20
```
```#include <stdio.h>
#include <stdarg.h>
#define COLOR 3
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#define R 0
#define B 1
#define G 2
#define Color 3

int min( int num, ... )
{
va_list arguments;
int min=0;
int tmp=0;
/* Initializing arguments to store all values after num */
va_start ( arguments, num );
/* Sum all the inputs; we still rely on the function caller to tell us how
* many there are */
min = va_arg ( arguments, int );
//printf("\n1st|%d|\n",min);
for ( int x = 1; x < num; x++ )
{
tmp = va_arg(arguments,int);
min = MIN(min,tmp);
}
va_end ( arguments );
// Cleans up the list
//printf("\nMin is %d", min);
return min;
}
typedef struct {
int  color;
int cost;
//struct nodee *root;
}node;
int main()
{
node cost[3];
int house = 3;
printf("Enter No. of Houses to paint : ");
scanf("%d",&house);
int color[house][COLOR];
//	int ji=0;
for(int i=0; i<house;++i){
for(int j=0; j<COLOR;++j){
scanf("%d",&color[i][j]);
//				color[i][j]= ++ji;
}

}
//cost[0].cost=color[0][R];cost[1].cost=color[0][B];cost[2].cost=color[0][G];
for(int i= 0; i< Color ;i++){
cost[i].cost=color[0][i];
cost[i].color = i;
} // Initial Submission of values, and colour
//	printf("\nA.cost\t%d(%d)\tB.cost\t%d(%d)\tC.cost\t%d(%d)\n",cost[0].cost,cost[0].color,cost[1].cost,cost[1].color,cost[2].cost,cost[2].color);
//A.color = R; B.color = B; C.color = G;
int tmp_B=0,tmp_G=0,tmp_R=0;
//printf("\nR_cost\t%d\tB_cost\t%d\tG_cost\t%d\n",R_cost,B_cost,G_cost);
for(int i=1; i<house;++i)
{
for(int j= 0; j< Color ;j++){
if(cost[j].color == R){
if(color[i][B] < color[i][G]){
cost[j].cost = cost[j].cost + color[i][B];
cost[j].color = B;
//cost[j].root = malloc(sizeof(struct node));
//cost[j].root->next = 0;
//cost[j].root->x = color[i][B];
}else{
cost[j].cost = cost[j].cost + color[i][G];
cost[j].color = G;
}
}else if(cost[j].color == B){
if(color[i][R] < color[i][G]){
cost[j].cost = cost[j].cost + color[i][R];
cost[j].color = R;
}else{
cost[j].cost = cost[j].cost + color[i][G];
cost[j].color = G;
}
}else{
//Case for G
if(color[i][R] < color[i][B]){
cost[j].cost = cost[j].cost + color[i][R];
cost[j].color = R;
}else{
cost[j].cost = cost[j].cost + color[i][B];
cost[j].color = B;
}
}
//			printf("\nA.cost\t%d(%d)\tB.cost\t%d(%d)\tC.cost\t%d(%d)\n",cost[0].cost,cost[0].color,cost[1].cost,cost[1].color,cost[2].cost,cost[2].color);
}
/*
if(A.color == )
//R_cost = min(2,color[i][B],color[i][G])+R_cost;
if(color[i][B] < color[i][G]){

tmp_B = R_cost + color[i][B];
}else{
tmp_G = R_cost + color[i][G];
}

//B_cost = min(2,color[i][R],color[i][G])+B_cost;
if(color[i][R] < color[i][G]){

tmp_R = B_cost + color[i][R];
}else{
tmp_G = B_cost + color[i][G];
}
//G_cost = min(2,color[i][B],color[i][R])+G_cost;
if(color[i][R] < color[i][B]){

tmp_R = G_cost + color[i][R];
}else{
tmp_B = G_cost + color[i][B];
}
R_cost = tmp_R;
B_cost = tmp_B;
G_cost = tmp_G;
//printf("\n G %d:%d",color[i][B],color[i][R]);
*/
//			printf("\nA.cost\t%d(%d)\tB.cost\t%d(%d)\tC.cost\t%d(%d)\n",cost[0].cost,cost[0].color,cost[1].cost,cost[1].color,cost[2].cost,cost[2].color);
}
printf("\nMinimum Cost to paint all houses are %d\n",min(3,cost[0].cost,cost[1].cost,cost[2].cost));
}

```

# How Many Ip Address !!!

Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]{hint:recursion,backtrack}

Here is the Solution ……
it was taken me about 5 hours to solve see !!!

//cc Arun Kumar Gupta

import java.util.*;
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String input = sc.next();
int[] intArray = new int[input.length()];
int length = input.length();

for (int i = 0; i < input.length(); i++) {
intArray[i] = Character.digit(input.charAt(i), 10);
//System.out.println(intArray[i]);
}
int i = 0 , j = 1 , k = 2;
ip.Ipaddress(intArray , i , j , k , length-1);

}
void Ipaddress(int [] intArray , int i , int j , int k , int length)
{
try{
int where = 0 ,change = 0;
int p1 =createIP( intArray , -1 , i);
int p2 =createIP( intArray , i ,  j );
int p3 =createIP( intArray ,  j , k );
int p4 =createIP( intArray ,  k ,  length );
//System.out.println(“**********Garbage”+p1+”.”+p2+”.”+p3+”.”+p4);
//System.out.println(“i = “+i+”j = “+j+”k = “+k);
if((p1<=255)&&(p2<=255)&&(p3<=255)&&(p4<=255)&&(p4>0))
{
System.out.println(p1+”.”+p2+”.”+p3+”.”+p4);
}
if(p4 >255)
{
//if(k != j)
//++k;
where =4;
//System.out.println(“Problem at P4”);
}
else if(p3>255)
{
//if(j != i)
//++j;
//–k;
where = 3;
//System.out.println(“Problem at P3”);
}
else if(p2>255)
{
//++i;
where = 2;
//System.out.println(“Problem at P2”);
}
else if(p1>255)
{

//System.out.println(“Problem at P1”);
System.exit(0);
}

if((k == length) && (j+1 == k))
{
//System.out.println(“if((k == length) && (j+1 == k))”);
//System.out.println(i+”_”+j+”_”+k);
++i;
j = i+1;
k = j+1;
change = 1;
//System.out.println(i+”_”+j+”_”+k);

}
if((k == length) &&(change == 0) )
{
//System.out.println(“if((k == length) &&(change == 0) )”);
++j;
k = j+1;
change = 0;
}
else if(change == 0)
{
if( (k) < length )
++k;
}
/*if(where ==4)
{
++k;
}
if(where ==3)
{
++j;
–k;
}
if(where ==2)
{
++i;
–j;
}
/*if(k==length)
{
–k;
–j;
}*/
Ipaddress(intArray , i , j , k , length);
}
catch(ArrayIndexOutOfBoundsException e){
//System.out.println(“Exception thrown  :” + e);
}
}
static int createIP(int [] intArray , int start , int end)
{
//System.out.println(“I am at createIP()start = “+start+”\tend = “+end);
int val = 1 , fina = 0;
for(int e =end ; e>start ; –e)
{
fina = intArray[e]*val + fina;
val = val*10;
}
return fina;
}
}

# Prime Generator

Sorry for late post i was too busy ….
this is a new problem
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!

### Input

The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.

### Output

For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

### Example

`Input:21 103 5Output:235735`

`Solution :`

`CC Arun Kumar Gupta`

`import java.util.*;public class FastestPrime{ public static void main (String [] args) {  Scanner sc = new Scanner(System.in);  int test_cases = sc.nextInt();  if((test_cases <=10) && (test_cases > 0))  {  for(int i = 0 ; i   {    int m = sc.nextInt();    int n = sc.nextInt();    if((m<= 1000000000) &&(n<=1000000000)&&(n>0)&&(m>0))    {    if((n-m) <= 100000)    {     if((m % 2) == 0)     ++m;     for(int j = m ; j<= n ; ++j)     {      NextNum(j);      j = j+ 1;           }         }    }  System.out.println();    }  }   } static void  NextNum(int m) {  int div = 3;  int array [] = new int[1000];  int rem  = 1 ;  while((rem != 0) && (div <= (m/2)))   {    rem = m%div;    div = div+2;   }  if(rem != 0)  {  System.out.println(m);   }   }}`

# Sync Subtitles With The Video In VLC

I can’t stress the usefulness of subtitles enough, especially when you’re watching a movie in a foreign language. I was watching Heavenly Forest, a Japanese romantic drama, a few days back. The movie was wonderful, but I wouldn’t have understood anything had it not been for those English subtitles. I even tend to use English subtitles while watchingEnglish movies, because you guys talk so fast (Americans) or so weird (British) that it’s hard for me to grasp!
Handy as they are, subtitles can turn extremely irritating if they’re out of sync with the video. They distract you, and you end up understanding even less than what you’d have without the subs. Thankfully, if you’re using VLC player to watch the videos, you can make use of a nifty feature in the program to sync the subtitle with the video! Do note that it’ll only temporarily sync the subtitles with the video, and the sync will be gone the next time you watch the video.
Anyway, lets get started with how to implement it. I’m assuming that you’ve already loaded the video and subtitle files into VLC (you can just drag them both into its interface). Now, carefully take a look at the video and the subs, and see whether the subs are lagging behind or running ahead of the video. If you’re watching a foreign movie, it may seem like a very difficult job, but just try a little hard and you should be able to make this out. For example, if you see a girl screaming and running around wildly, and the subs show “Help me! Help me!” 3 seconds after that scene, this means that the titles are 3 seconds behind the movie.
Once you’ve figured out the lag / lead of the subtitle, it’s time to sync it with the video. In VLC, navigate to Tools > Track Synchronization, where you’ll find the Subtitles/Video section. Now comes the important part – syncing the subtitle. If the subtitle is lagging behind the video, you’ve to provide a negative value to ‘Advance of subtitles over video’. Say the subs display 3 seconds after the video, the value you got to enter is –3.000 s. Note that you can adjust the sync time to upto a thousandth of a second, although adjusting to the tenths does the job in all cases. Similarly if the subtitle is ahead of the video, enter the required positive number of seconds. Hit the Refresh button at the top right corner of the window, and you should see the change immediately.

# Alien Chef

A new programming Problem…..

/*

The aliens living in outer space are very advanced in technology, intelligence and everything, except one, and that is Cooking. Each year they spend millions of dollars in research, to crack famous recipes prepared by humans.

Recently they came to know about Khana-Academy, a non-profit organization streaming free cooking lesson videos on earth. There are N recipes, numbered 1 to N, and the video of the ith recipe is live in the time interval [Si, Ei]. An alien can visit earth but can not survive for more than just a small moment (earth is so advanced in pollution). An alien visits the earth at an integer time t and instantly downloads the complete video of all the lessons that are live at that moment of time t and leaves earth immediately. You are given the visiting times of a small group of K aliens. Find the number of different recipes aliens can learn by watching the downloaded videos. Not just one group of aliens, there are Q such groups, so you have to find the answer for each of these Q groups.
Input

The first line has an integer N. Each of the following N lines has two integers Si Ei. The next line has an integer Q, the number of groups. Each of the following Q lines has information of a group of aliens. The first integer is K, the number of aliens in that group, followed by K integers in the same line, the integer visiting times t of the aliens.

1 ≤ N ≤ 100000 (105)

1 ≤ Q ≤ 5000 (5 103)
1 ≤ K ≤ 20
1 ≤ Si, Ei, t ≤ 1000000000 (109)
Si < Ei

Output

For each of the Q groups, output the number of different recipes that group of aliens can learn by watching the downloaded videos.

Example

Input:

4
1 4
3 10
2 6
5 8
3
1 5
2 2 6
3 1 10 9

Output:

3
4
2

Explanation:

Given videos of 4 recipes in the following closed intervals.
1. [ 1 , 4 ]
2. [ 3 , 10 ]
3. [ 2 , 6 ]
4. [ 5 , 8 ]

In the first query, only one alien arrives at t = 5 and can download 3 recipes 2, 3, 4.

In the second query, two aliens arrive at t = 2 and 6. They can learn all the 4 recipes.

In the third query, three aliens arrive at t = 1, 10 and 9. They can learn only two recipes, 1 and 2.

*/

import java.util.*;
import java.lang.*;
/*public class Array
{
int num[]  = new int[20];

}

*/
public class AlienChefs
{
static int aaa[] = new int[100000];
static int end ;
//leng = 1;
static int start ;
public static void main(String [] args)
{

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if((0
{
int a[] = new int[2*n];
for(int i = 0 ; i<(2*n) ; ++i)
{
//System.out.println(“Inside”);

a[i] = sc.nextInt();
if( (0
{
if((i%2) == 1   )
{
//System.out.println(“Inside”);
if((a[i-1] > a[i]))
System.exit(0);
}

}
else
System.exit(0);
}
int groups = sc.nextInt();
//System.out.println(“********************”);
for(int i = 0 ; i< groups; ++i)
{
int count = 0 ;
int alen = 0 ;
int times = sc.nextInt();
for(int j =0 ;j
{

alen = sc.nextInt();
if((0
{
//System.out.println(alen);
count = count+ cc(a , alen);

}

}
start = end – start;
start = start +end + add ;
end = start;
aaa[start] = 1000;
System.out.println(count);

}
}

}
static int cc(int a [] , int val)
{
int count = 0 ;

for(int i = 0 ; i< a.length; i++)
{ //static int a;
int abc =0;

if((a[i] <= val)&& (val <= a[i+1] ))
{
//System.out.println(“***************************************”);
abc = check(aaa , i);
if( abc == 0)
{
++count;
}

}
++i;

}
//System.out.println(“Count Returned :”+count);

return count;
}
static int check(int qw [], int i)
{
//System.out.println(“Check Function is called “);
//System.out.println(start+”:”+end);
//System.out.println(“i = “+i);
for(int j = start ; j<=end ; j++)
{
if(qw[j] == i)
return 1;
}
qw[end] = i;