You have an array containing only '0's, '1's and '2's. Club same items together in single scan.

let's try to understand problem:



algorithm:
i)  initialize i and j to 0 and  k to n-1 Where n is  number of balls
ii) while j <= k  do
            if pointer  j point to red ball than
                     swap a[i] and a[j];
and  perform i++; j++

           if pointer  j point to white ball than
just perform j++

           if pointer  j point to blue ball than
swap a[j] and a[k];
         and  perform  k--;

This problem is also known as Dutch National Flag Problem. Check out how Dutch flag looks like:

code:
#include <stdio.h>

//here red->0, white->1, blue->2
int arr[] = { 0,1,0,2,2,0,1,1,0 };
int arr_size = sizeof(arr)/sizeof(arr[0]);

void swap(int *a, int *b);
void dutchflag( );

int main()
{
int c;
dutchflag();
printf("\ndutch flag Order: ");
for (c = 0; c < arr_size; c++)
printf("%d ", arr[c]);

return 0;
}
/* test function to to Sort the balls in dutch flag order*/
void dutchflag( )
{
int i = 0,j=0 , k = arr_size - 1;

while(j <= k)
{
switch(arr[j])
{
case 0:
swap(&arr[i++], &arr[j++]);
break;
case 1:
j++;
break;
case 2:
swap(&arr[j], &arr[k--]);
break;
}
}
}

/* Function to swap *a and *b */
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}


output:-
dutch flag Order: 0 0 0 0 1 1 1 2 2

Time Complexity:  O(n)
Three ants are sitting at the three corners of an equilateral triangle. Each ant starts randomly picks a direction and starts to move along the edge of the triangle. What is the probability that none of the ants collide? Now find the same for n vertex polygon with n ants.

solution :

Every Ant can move in 2 possible directions , Backward  ( B )  and Forward ( F ).
for 3 ants we have 2^(3) combination of moves,so the whole sample space consists of 8 choices.

F F B
F F F
F B B
F B F
B F B
B F F
B B B
B B F

here out 8 only 2 , namely BBB and FFF are no collision choices. 
so probability of not colliding is 2 /8 = 1/4=0.25

think in this way:

how can you avoid collision ?

The ants can only avoid a collision if they all decide to move in the same direction (either clockwise or anti-clockwise). If the ants do not pick the same direction, there will definitely be a collision.

1) all move in clockwise direction



2) move in anti-clockwise direction






Therefore  we have only 2 ways to avoid collision irrespective of shape and no of ant. 


how to find probability for n vertex polygon with n ants ?


As we know Every Ant can move in 2 possible directions , backward and forward .Therefore we have 2^(n) combination of moves.but only two will avoid collision (when all move in either clockwise or ant-clockwise direction )
hence probability of not colliding is 2/ 2^(n)
and probability of colliding is 1-2/ 2^(n)
example:pentagon 
pentagon has five vertices so n is 5
probability of not colliding = 2/ 2^(n)=2/2^(5)=2/32=1/16
probability of colliding = 1-2/ 2^(n)=1-2/2^(5)=1-2/32=1-1/16=15/16

Here another way to watch same problem...

As we know Each ant has the option to either move clockwise or anti-clockwise. There is a one in two chance that an ant decides to pick a particular direction. Using simple probability calculations, we can determine the probability of no collision.

P(No collision) = P(All ants go in a clockwise direction) + P( All ants go in an anti-clockwise direction)
P(No collision)= 0.5 * 0.5 * 0.5 + 0.5 * 0.5 * 0.5 = 0.25

let's generalize this for  n vertex polygon with n ants

P(No collision) = P(All ants go in a clockwise direction) + P( All ants go in an anti-clockwise direction)
P(No collision)=(0.5)^n + (0.5)^n
P(No collision)=2*(0.5)^n
P(No collision)=1-2*(0.5)^n

example:pentagon 
pentagon has five vertices so n is 5
probability of not colliding = 2*(0.5)^5=0.0625
probability of colliding = 1-2*(0.5)^5=0.9375

i know both are same and after simplifying them final formula is 1/2^(n-1) &1-1/2^(n-1) for No collision & collision resp.

A duck, pursued by a fox, escapes to the center of a perfectly circular pond. The fox cannot swim, and the duck cannot take flight from the water (it’s a deficient duck). The fox is four times faster than the duck. Assuming the fox and duck pursue optimum strategies, is it possible for the duck to reach the edge of the pond and fly away without being eaten? If so, how?

This is not a simple mathematical puzzle to solve like normal common problems. Fox in this puzzle is too fast and clever for any normal and simple strategy.
From the speed of the fox it is obvious that duck cannot simply swim to the opposite side of the fox to escape.

idea:
step 1:
As we know fox is four times faster than the duck.Let the duck rotate around the pond in a circle of radius R/4. Now fox and duck will take exact same time to make a full circle.
                             

step 2:
Now reduce the radius the duck is circling by a very small amount (Delta). Now the Fox will lag behind, he cannot stay at a position as well.


step 3:
Now in due time duck will get to a position we wanted, 3/4*R distance away from shore where fox is on the exact opposite side of the pond. From there duck can swim safely to shore and fly away.



For example: if the solution is 'RGGB' and the user guesses 'YRGB' they have 2 hits and one pseudo hit. Write a program to, given a solution and a guess, calculate the number of hits and pseudo hits.

Solution 1:
Algorithm:
1.Take an temp array of length ascii chars(256), although we need array of length of 4 here
taking above array will give advantage so that we set/reset the 1 or 0 at particular character
position according to their ascii value.
2.scan solution & guess string & set value to 1 in temp array for each matching character of
solution & guess string also increment the hits counter.else increment temp array location of
corresponding character location.
3.in 2nd pass over temp array check for each location if that location value is not equal to 1 &
also temp[location]>0 if yes then increment pseudo-counter & decrement corresponding character
count in temp array.
code:
#include <stdio.h> 
int main()
{
char solution[]={'A','B','C','D'};
char guess[] ={'A','E','D','D'};
int arr[256],i,hits=0,pseudoHits=0;

for ( i = 0; i < 4; i++) // initialize all char in solution to set
arr[solution[i]]=1;
//arr[i]=00..111100... till 256
for ( i = 0; i < 4; i++)
{
if (guess[i]== solution[i]) // if match then increment hit
hits++;
else
arr[guess[i]]++; //no match increment guess array index by 1
}
//now array will look like arr[i]=00..111210... till 256 
//because in this example E and D does not mach hence we increment them
//but D was present in sol hence it value was 1 and after increment it become 2 
//and E was initially 0 and after increment it become 1
//note:all index having value 2 means they are already present in solution 
//but guess does not match
//hence to find pseudoHits we have to search for index value equal to 2
for ( i = 0; i < 4; i++)
{
if (arr[solution[i]]> 1)
{
pseudoHits++;
arr[solution[i]]--;
}
}
printf("number of hits is %d\n",hits);
printf("number of pseudo hits is %d",pseudoHits);
return 0;
}


output:-
number of hits is 2
number of pseudo hits is 1
but can we do better than this ?

yes
instead of using char array of length 256 we can take help of bits to make set/reset the 1 or 0 to keep track of particular character.

Solution 2:
code:
#include <stdio.h> 
int main()
{
char solution[]={'A','B','C','D'};
char guess[] ={'A','E','D','D'};
int solution_mask = 0,i,hits=0,pseudoHits=0;
for ( i = 0; i < 4; ++i)
solution_mask =solution_mask | 1 << (solution[i] - 64);

for ( i = 0; i < 4; ++i)
{
if (guess[i]== solution[i])
{
hits++;
}
else if ((solution_mask & (1 << (guess[i] - 64))) >= 1)
{
pseudoHits++;
}
}
printf("number of hits is %d\n",hits);
printf("number of pseudo hits is %d",pseudoHits);
return 0;
}


output:-
number of hits is 2
number of pseudo hits is 1

time complexity:-  O(n)
space complexity:-  O(1)

Step By Step Execution:
initialize solution_mask to 0
Step 1:-
for ( i = 0; i < 4; ++i)
solution_mask =solution_mask | 1 << (solution[i] - 64);

for i=0
let's break the things first,
1<<(solution[i] - 64)
1<<(A-64)
1<<1
0000 0001
after 1<<1
0000 0010
now
solution_mask = solution_mask | 1 << (solution[i] - 64)
00000000 | 00000010 =00000010
decimal of 00000010 is 2.
Therefore new value of solution_mask is 2.

for i=1
1<<(solution[i] - 64)
1<<(B-64)
1<<2
0000 0001
after 1<<2
0000 0100
Value of solution_mask is 2 and binary of 2 is 00000010
solution_mask = solution_mask | 1 << (solution[i] - 64)
00000010 | 00000100 =00000110
decimal of 00000110 is 6.
Therefore new value of solution_mask is 2.

for i=2
1<<(solution[i] - 64)
1<<(C-64)
1<<3
0000 0001
after 1<<3
0000 1000
Value of solution_mask is 6 and binary of 6 is 00000110
solution_mask = solution_mask | 1 << (solution[i] - 64)
00001000 | 00000110 =00001110
decimal of 00001110 is 14.
Therefore new value of solution_mask is 14.

for i=3
1<<(solution[i] - 64)
1<<(D-64)
1<<4
0000 0001
after 1<<3
0001 0000
Value of solution_mask is 6 and binary of 6 is 00000110
solution_mask = solution_mask | 1 << (solution[i] - 64)
00010000 | =00001110 =00011110
decimal of 00011110 is 30.
Therefore new value of solution_mask is 30.

Step 2:-
 for ( i = 0; i < 4; ++i) 
{
if (guess[i]== solution[i])
{
hits++;
}
else if ((solution_mask & (1 << (guess[i] - 64))) >= 1)
{
pseudoHits++;
}
}
for i=0
guess[i]== solution[i]
'A'=='A'is equal
therefore increment hit by 1

for i=1
guess[i] != solution[i]
hence control move to else part
now,let's break the things again
1<<(guess[i] - 64)
1<<(E-64)
1<<5
0000 0001
after 1<<5
0010 0000
now
solution_mask & (1 << (guess[i] - 64))
00011110 & 00100000  =00000000
decimal of 00000000 is 0.
((solution_mask & (1 << (guess[i] - 64))) >= 1)
0>=1 condition become false hence control goes to for loop

for i=2
guess[i] != solution[i]
hence control move to else part
now,let's break the things again
1<<(guess[i] - 64)
1<<(D-64)
1<<4
0000 0001
after 1<<5
0001 0000
now
solution_mask & (1 << (guess[i] - 64))
00011110 & 00010000  =00010000
decimal of 00000000 is 16.
((solution_mask & (1 << (guess[i] - 64))) >= 1)
16>=1 condition is true
hence pseudoHits will increment by 1

for i=3
guess[i]== solution[i]
'D'=='D'is equal
therefore increment hit by 1

Hence number of hits is 2 and pseudo hits is 1

done!!


A->R : Load R with A

B->R : Load R with B

A-R->A : Subtract R from A and store the result in A

Using these instructions how can you do the follwoing?

B->A : Load A with B


solution:-

A->R       // R ==  A
A-R->A   // A ==  0
B->R       // R ==  B
A-R->A   // A == -B
A->R       // R == -B
A-R->A   // A ==  0
A-R->A   // A ==  B

let's try to understand problem:



code to generate hash function:
#include <stdio.h> 
#include <math.h>
char arr[100];
int i,j=4,total=0;
double x;
/* this function will generate hashcode */
void hashcode()
{
for(i=0;i<5;i++)
{
if(arr[i]==' ') // to caovert space to 0
x=0;

if(arr[i]>='0'&& arr[i]<='9') // to convert ascii of 0-9 to 1-10
x=(arr[i]-47);

if(arr[i]>='A'&& arr[i]<='Z') // to convert ascii of A-Z to 11-36
x=(arr[i]-54);

x=x*pow(37, j);
total=total+(int)x;
j--;
}
}
int main()
{
printf("enter the usename of length 5\n");
for(i=0;i<5;i++)
scanf("%c",&arr[i]);
hashcode();
printf("\n%d",total);
return 0;
}


output:-
enter the usename of length 5
Z10 A

67572482
----------------------------------------------
Z10 A=36*37^(4)+2*37^(3)+1*37^(2)+0*37^(1)+11*37^(0)
refer table givien below





Given a sorted array, where exists duplicated integers, find the first occurrence of the target integer?

code:
#include <stdio.h> 
int arr[100],mid,l,r,len,position,i,target;
int binarySearchFirstOccur();
int main()
{
printf("Enter number of elements\n");
scanf("%d",&len);
printf("Enter %d integers\n", len);
for ( i = 0 ; i < len ; i++ )
scanf("%d",&arr[i]);

printf("Enter value to find\n");
scanf("%d",&target);
position=binarySearchFirstOccur();
if( position!= -1)
printf(" Given integer is present at %d index in array",position);
else
printf(" Given integer is not present in array");
return 0;
}

int binarySearchFirstOccur()
{
int l=0,r=len-1;
int mid=(l+r)/2;

while(l+1!=r) //l+1==r => arr[l]<target and arr[r]>=target and l<r
{
if(arr[mid]<target) //target is in the right
l=mid;
else
r=mid;
mid=(l+r)/2;
}

if(r<len||arr[r]==target)
return r; //r is the first occurrence index
else
return -1; //didnt find the integer
}

output:-
Enter number of elements
10
Enter 10 integers
1 2 3 4 5 6 7 8 8 9
Enter value to find
8
Given integer is present at 7 index in array

let me demonstrate this for you:
first initialize l,r and mid
l=0
r=9
mid=0+9/2=4

value:  1  2   3   4   5   6   7   8   8   9
index:  0  1   2   3   4   5   6   7   8   9
             l                  m                      r
arr[mid]<target
arr[4]<8
5<8
yes,therefore change value of l,
l=mid
l=4
r=9
mid=(4+9)/2=6

value: 1  2   3   4   5   6   7   8   8   9
index: 0  1   2   3   4   5   6   7   8   9
                                      m            r
arr[mid]<target
arr[6]<8
7<8
yes,therefore change value of l,
l=mid
l=6
r=9
mid=(6+9)/2=7


value: 1  2   3   4   5   6   7   8   8   9
index: 0  1   2   3   4   5   6   7   8   9
                                          m        r
arr[mid]<target

arr[7]<8
8<8
no,therefore change value of r,
r=mid
r=7
l=6
mid=(6+7)/2=6

now we are done with first occurrence
note in while loop condition is

while(l+1!=r)
not
 while(l<r)

because it will go to infinite loop because as you can see we are storing index in r. Therefore
l<r will always true.