Feature news

Showing posts with label Tech. Show all posts

Write a function called my2DAlloc which allocates a two dimensional array. Minimize the number of calls to malloc and make sure that the memory is accessible by the notation arr[i][j].

let's allocate two-dimensional array of dynamic space:
i)  Define 'rowptr', a pointer to pointer to int, as the name of the 2D array.
ii) To pointer 'rowptr', let us allocate an array of 'm' elements of type 'pointer to int', Here, 'm' is the number of rows we wish the 2D array to have.
iii) To each element rowptr[i] allocated above, let us allocate an array of 'n' elements of type 'int'.  Here, 'n' is the number of columns in each row of the array.
lets take an example of rowptr[4][4].
code:
int **  My2DAlloc ( int  rows ,  int  cols ) 
{ 
    int  ** rowptr  =  ( int ** ) malloc ( rows * sizeof ( int * )); 
    for ( int  i = 0 ;  i < rows ;  ++ i ) 
        rowptr[ i ]  =  ( int * ) malloc ( cols * sizeof ( int )); 
    return  arr ; 
}
Above method use malloc function (rows + 1) times.Too much use of malloc function will affect the efficiency of the program.How to avoid this ?

Allocate all space once and then move pointer to appropriate position.

lets calculate total no of space we required
Total space = no of rows + no of rows*no of rows  /*( as we can see in above diagram)*/
    
    int header = rows * sizeof(int*);   //no of rows
    int data = rows * cols * sizeof(int);  //no of rows*no of rows
    int** rowptr = (int**)malloc(header + data); // total space
now we have to skip no of rows and then store data
let take previous example of rawptr[4][4]
Total space = no of rows + no of rows*no of rows
Total space = 4 + 4*4=20
now we have to allocate first 4 space for row array
so we have to skip till no of rows. To do this we are using variable buf.
int* buf = (int*)(rowptr + rows);
now we have to allocate address for  row array.
    int header = rows * sizeof(int*);
    int data = rows * cols * sizeof(int);
    int** rowptr = (int**)malloc(header + data);
    int* buf = (int*)(rowptr + rows);
    int k;
    for (k = 0; k < rows; ++k) 
        rowptr[k] = buf + k*cols;
lets assume size of int is 4 and we have 4 rows and columns
header=4*4=16
data=4*4*4=64
total space allocated for rowptr is 64+16=80 and assume address of rowptr is 100
but  we have to skip space till no of rows, for that we are using variable buf.
buf=100+16=116

pass 0:
rowptr[k] = buf + k*cols=116+0*4=116                       //Here we Assume Size of int is 4.
pass 1:                                                                      //Therefore every address is increment by 4.
rowptr[k] = buf + k*cols=116+1*4=132
 pass 2:
 rowptr[k] = buf + k*cols=116+2*4=148
pass 3:
rowptr[k] = buf + k*cols=116+3*4=164
done!!
we did it in one malloc function call.
final code:
#include <stdio.h>

int ** rowptr,* buf,header,data,rows,cols,k,i, j;

void ** malloc2d(int rows, int cols)
{
     header = rows * sizeof(int*);
     data = rows * cols * sizeof(int);
     rowptr = (int**)malloc(header + data);
     buf = (int*)(rowptr + rows);
    for (k = 0; k < rows; ++k) 
        rowptr[k] = buf + k*cols;
}

void free2d(int** rowptr)
{
    free(rowptr);
}
int main( )
{
    malloc2d(3,4);
    for( i = 0; i < 3; i++)
        for(j = 0; j < 4; j++)
  {
            rowptr[i][j] =1;
            printf("%d",rowptr[i][j]);
        } 
    free2d(rowptr);
    return 0;
}

output:-
111111111111

Have questions about this code? Comments? Did you find a bug? Let us know!

Learn more »

Difference between Array and Linked List


ArrayLinked list
DefineArray is a collection of elements having same data type with common name.Linked list is an ordered collection of elements which are connected by links/pointers.
AccessIn array, elements can be accessed using index/subscript value, i.e. elements can be randomly accessed like arr[0], arr[3], etc. So array provides fast and random access.In linked list, elements can’t be accessed randomly but can be accessed only sequentially and accessing element takes 0(n) time.
Memory StructureIn array, elements are stored in consecutive manner in memory.In linked list, elements can be stored at any available place as address of node is stored in previous node.
Insertion & DeletionInsertion & deletion takes more time in array as elements are stored in consecutive memory locations.Insertion & deletion are fast & easy in linked list as only value of pointer is needed to change.
Memory AllocationIn array, memory is allocated at compile time i.e. Static Memory Allocation.In linked list, memory is allocated at run time i.e.Dynamic Memory Allocation.
TypesArray can be single dimensional, two dimension or multidimensional.Linked list can be singly, doubly or circular linked list.
DependencyIn array, each element is independent, no connection with previous element or with its location.In Linked list, location or address of elements is stored in the link part of previous element/node.
Extra SpaceIn array, no pointers are used like linked list so no need of extra space in memory for pointer.In linked list, adjacency between the elements are maintained using pointers or links, so pointers are used and for that extra memory space is needed.
Figure
Learn more »

Add two numbers without using arithmetic operators

How to add two number ?

now try this

but today i am going to introduce new trick  to add two numbers that you are never want to use in real life.
but it still worth and interviewers just love to see this method.



Add two numbers without using arithmetic operators

but before doing this let me introduce background for this method.
so lets start..
a = 999
b = 909
let me tell you rule how to add it.
rule 1: Add them but do not add carry and store in variable sum
rule 2: Now add again but this time list out the carry’s and append 0 at end and store in list carry
rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.

let's do it
a = 999
b = 909
pass 1:
rule 1: Add them but do not add carry and store in sum
as you can see we are adding value of a and b ad discarding all carry.

rule 2: Now add again but this time list out the carry’s and append 0 at end

as you can see we are adding value of a and b and storing only carry.
ex: 9+9 is 8 with carry 1 so we discard 8 and just take carry 1.

rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.
carry is 1010 which is not equal to 0.
now a= 898
        b=1010
and move to pass 2.

pass 2:
rule 1: Add them but do not add carry and store in sum

rule 2: Now add again but this time list out the carry’s and append 0 at end

rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.
carry is 0100 which is not equal to 0.
now a= 1808
        b=0100
and move to pass 3.

pass 3:
rule 1: Add them but do not add carry and store in sum

rule 2: Now add again but this time list out the carry’s and append 0 at end

rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.
here carry is 0.hence we stop.
and sum is 1908

check answer with regular method 

   a = 999
+ b = 909
---------------
        1908
---------------
we are correct.

let's write code:
But howto do this without using arithmetic operations ?
here we can use property of xor and And operator.
when we xor two no we get addition of two no without carry
and when we And two no we list out the carry’s.

xor = Add them but do not add carry.
And = list out the carry’s

As in rule 2 we have to append 0 at end.
To do this we can use left shift operator(<< ).
Iterative code:
#include <stdio.h>

int sum,listcarry;
int Add(int a, int b)
{ 
    while (1)
    {
        // rule 1: Add a and b but do not add carry and store in variable sum

        sum = a ^ b;

        //rule 2: Now add again but this time list out the carry’s 
       //and append 0 at end and store in list carry
 
        listcarry = a & b;  
        listcarry =listcarry << 1;//left shift operator(<<)to append 0 at end

        //rule 3: stop if list carry become 0 else move sum to a 
        //and list carry to b  and repeat all this.

        if(listcarry==0)
         break;       
        else
         {
          a=sum;
          b=listcarry; 
         }
    }
    return sum;  // return sum;
}
 
int main()
{
    printf("%d",Add(909, 999) );
    return 0;
}

output:-
1908

Recursive code:

#include <stdio.h>

int sum,listcarry=-1;
int Add(int a, int b)
{ 
  if(listcarry==0)
      return sum ;       
  else
  {
    //rule 1: Add a and b but do not add carry and store in variable sum
    sum = a ^ b;
         
    //rule 2: Now add again but this time list out the carry’s 
    //and append 0 at end and store in list carry
         
    listcarry = a & b;  
    listcarry=listcarry << 1;//left shift operator(<<)to append 0 at end
    a=sum;
    b=listcarry;
    return Add(a, b) ;  
  }
}
 
int main()
{
    printf("%d",Add(909, 999) );
    return 0;
}
output:-
1908




click for code explanation let a=2

let a=2
     b=3
in terms of binary
a=2=0010
b=3=0011

pass 1:
rule 1: Add them but do not add carry and store in sum
rule 2: Now add again but this time list out the carry’s and append 0 at end

rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.
carry is 0100 which is not equal to 0.
now a= 0001
        b=0100
and move to pass 2.
pass 2:
rule 1: Add them but do not add carry and store in sum
rule 2: Now add again but this time list out the carry’s and append 0 at end
rule 3: stop if list carry become 0 else move sum to a and list carry to b and repeat all this.
here carry is 0.hence we stop.
and sum is 101 which is binary of 5.



Why append 0 at end ? ( because carry is always added with next more significant digit.hence append 0 at end.
e.g.

as you can see during carry addition

i) If there is carry then it will go to next more significant digit
ii) If there is no carry than we put 0

Hence in both case rightmost digit is always 0.therefore we append 0 at end )
Learn more »

Given an array of red, green and blue balls arrange them in groups of all red together, greens together and blue together. Do in a single scan of the array.

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)
Learn more »

3 Ants and Triangle Puzzle

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.

Learn more »

The Fox and The Duck

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.



Learn more »

Game of master mind: you have four balls, and four different colors, as a solution. The user tries to guess the solution. If they guess the right color for the right spot, it counts as a 'hit'. If it's the right color, but the wrong spot, it counts as a pseudo-hit.

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!!

Learn more »

A computer has three registers, A, B and R. It has only three instructions:


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
Learn more »

Design a hash table to store phone #s. Your job is to write a hash function that has a parameter username, and generate a key. Username is unique, length 5 and can be A-Z, 0-9, space. Write a hash function that generate keys without collisions and use minimum memory.


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





Learn more »

Find the first occurrence of an integer in an array of sorted integers in O(logn).

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
                               l        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
                                        l   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.

Learn more »

Explain ((n & (n-1)) == 0)


variant of question:-
 find whether a no is power of two ?

It's figuring out if n is either 0 or an exact power of two.

how ?

It works because of binary Bits Magic.
but before explaining first i want to define them  
n ->  unsigned long 
(n-1) -> it is simple Subtraction 
& -> The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
Bitwise AND Truth Table :


now, why it work ?

because all number n which is power of 2 follow some pattern

look at this:

2  = 10
4  = 100
8  = 1000
16= 10000
32= 100000
64= 1000000

and all number (n-1) also follow some pattern

1=   01
3  = 011
7  = 0111
15= 01111
32= 011111
64= 0111111


all number n which is power of 2 has msb( leftmost bit ) 1 followed by all 0's              and all (n-1) number  has msb( leftmost bit ) 0 followed by all 1's

when we perform logical & operation between n and (n-1) answer will always 0.

example:

For n=2

  n           2 =  1 0
n-1     &  1 =  0 1
           ------------------
                      0 0
           ------------------

For n=4

  n           4 =  1 0 0
n-1     &  3 =  0 1 1
           ------------------
                      0 0 0
           ------------------

For n=8

  n           8 =  1 0 0 0
n-1     &  7 =  0 1 1 1
           ------------------
                      0 0 0 0
           ------------------

And so on...

But what about 0 ?

let n=0
n-1= (0-1)= (-1)
binary representation of 0=0000
and (-1) represent in 2's complement form 
Therefore binary representation of (-1)=1111

For n=0
  n               0 =  0 0 0 0
n-1      &  (-1) =  1 1 1 1
          -----------------------
                          0 0 0 0
          -----------------------

What if i only want to find whether number is power of two or not ?

(n != 0) && ((n & (n - 1)) == 0);

code:
#include <stdio.h> 
int main()
{
int n,x;
printf("enter value of n:");
scanf("%d",&n);
x= n & (n-1);
if( x==0)
printf("n is either 0 or an exact power of two.");
else
printf("n is neither 0 nor an exact power of two.");
return 0;
}

output:-
enter value of n:16
n is either 0 or an exact power of two.

To find whether number is power of two or not?

code:
#include <stdio.h> 
int main()
{
int n,x;
printf("enter value of n:");
scanf("%d",&n);
x= n & (n-1);
if( x==0)
printf("number is power of 2");
else
printf("number is not power of 2");
return 0;
}

output:-
enter value of n:16
number is power of 2




Learn more »

Whats the difference between statically and dynamically typed languages? what is Strong Typing and Weak Typing?



Static vs. dynamic typing



Here are some claimed benefits.
Static typing
1. Reduced CPU usage since types don’t need to be checked at run-time
2. Reduced memory usage since types don’t need to be stored at run-time
3. Other type-directed optimizations
4. Discovery of errors as early as possible, for all my code
5. statically typed language, every variable name is bound both
       a) to a type (at compile time, by means of a data declaration)
       b)  to an object.

Dynamic typing
1. Easier to run and test since there are practically no compile-time or link-time errors
2. Programs are not limited by the expressiveness of the type system of the language
— e.g. heterogeneous data structures w/o explicit tagging.
3. Allows for implicit open recursion, late binding, dynamic scope, and duck typing
4. Programs are simpler since I don’t have to worry about types. Things are often coerced implicitly       making my programs more concise, and I don’t have to use really abstract things like type                   variables and higher-order types. In other words, they have been abstracted away by being pushed       down to a place I don’t have to think about.
5. In a dynamically typed language, every variable name is (unless it is null) bound only to an object.

Learn more »

write a program to find whether the m/c is big endian or little endian

Big endian and little endian are two formats to store multibyte data types into computer's memory. These two formats are also called network byte order and host byte order respectively.

let's try to understand problem:



code:
#include <stdio.h> 
int main ()
{
unsigned int x = 0x76543210;
char *c = (char*) &x;
printf ("value of *c is: 0x%x\n", *c);
if (*c == 0x10)
printf ("your Machine architecture is little endian. \n");
else
printf ("your Machine architecture is Big Endian. \n");
return 0;
}

output:-
value of *c is: 0x10
your Machine architecture is little endian.
Learn more »

Given n stairs, how many number of ways can you climb if u use either 1 or 2 at a time?

variant of question:-
A person can take m steps at a time to reach a particular floor( say in a building). How many different ways can a person reach the nth floor?

let's try to understand problem:




but we have to make some modification in Fibonacci sequence to get correct answer.
why?
In Fibonacci first element is 0 & second is 1
i.e for step no 0  we have 0 ways & for step no 1 we have 1 way
for step no 2=no of ways(0)+ no of ways(1)=0+1=1
but  answer is 2 which is no of ways(2)+ no of ways(1)=1+1=2
look at table

Here our first element is 1 not 0
therefore to find no of ways for step no n ,we have to find  no of ways for step no n+1

code:
#include <stdio.h> 
int Fibonacci(int);
main()
{
int n;
printf("total no of steps:");
scanf("%d",&n);
printf("no of ways to climb is %d\n", Fibonacci(n+1));
return 0;
}

int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
output:-
total no of steps:4
no of ways to climb is 5

but what if person can take m steps at a time ?
if person take up-to 2 steps at time(i.e either 1-step or 2-step) then to get no of steps we add
(n-1) +(last result)=(new result)

if person take up-to 3 steps at time(i.e either 3-step or 2-step or 1-step) then to get no of steps we add
(n-2)+(n-1) +(last result)=(new result)
similarly, 
if person take up-to m steps at time then to get no of steps we add
(n-(m-1))+(n-(m-1)-1) ..............+(last result)=(new result)

Generalize code:
#include <stdio.h> 
int n, m;
int Fibonacci(int n);
int main ()
{
printf("total no of steps:");
scanf("%d",&n);
printf("max no of steps can climb:");
scanf("%d",&m);
printf("no of ways to climb is %d\n", Fibonacci(n+1));
return 0;
}
int Fibonacci(int n)
{ int total=0,i;
if ( n == 0 )
return 0;
if ( n == 1 )
return 1;
for ( i = 1; i<=m && i<=n; i++) //for m steps
total += Fibonacci(n-i);
return total;
}

output:-
total no of steps:4
max no of steps can climb:3
no of ways to climb is 7


Learn more »

Shuffle card algorithm

One common programming question is how to randomly shuffle an array of numbers in-place.

variant of question:-
How would you write code to shuffle a deck of cards?
                                                   OR
write a program to generate a random permutation of array elements.


let's try to understand problem:



algorithm:

1. Start iterating the array from the last element.
2. If you are at ith element from the end, generate a random number say j,in range[0,i].
3. Swap A[i] and A[j].
4. Decrease j by 1
5. Continue till you reach the element at index 1 i.e A[1].

Generalize code:

#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
int a[] = {1, 2, 3, 4, 5, 6, 7, 8},temp,i, n = 8;
// A function to generate a random permutation of a[]
void randomize ( )
{

// srand()--> gives the random function a new seed, a starting point
//(usually random numbers are calculated by taking the previous number
//(or the seed) and then do many operations on that number to generate the next).

//time(0)--> gives the time in seconds since the Unix epoch,
//which is a pretty good "unpredictable" seed
//(you're guaranteed your seed will be the same only once,
//unless you start your program multiple times within the same second).
srand ( time(NULL) );

//We don't need to run for the first element that's why n-1 pass

for ( i = n-1; i > 0; i--) //for Shuffle card algorithm i=51
{
// Pick a random index from 0 to i
int j = rand() % (i+1);

// Swap a[i] with the element at random index
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

int main()
{
// shuffle the array
randomize ();
// print results.
for ( i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}


output:-

8 1 5 4 6 2 3 7

time complexity:-  O(n)
time complexity to traverse array is o(n) and assume rand() generates random number in O(1) time.

code for  shuffle deck of cards: 
we have to make change in input and array size of above generalize algorithm.input array consist of 52 cards

int a[] ={ 1,2,3,4,5,6,7,8,9,10,11,12,13,
14,15,16,17,18,18,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
};
change value of n
int n=52  // array size 
final code for  shuffle deck of cards:  :
#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
// Clubs->1 to 13
//Diamonds->14 to 26
//Hearts->27 to 39
//Spades->40 to 52
int a[] ={ 1,2,3,4,5,6,7,8,9,10,11,12,13,
14,15,16,17,18,18,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
};
int temp,i, n = 52;
// A function to generate a random permutation of a[]
void randomize ( )
{

// srand()--> gives the random function a new seed, a starting point
//(usually random numbers are calculated by taking the previous number
//(or the seed) and then do many operations on that number to generate the next).

//time(0)--> gives the time in seconds since the Unix epoch,
//which is a pretty good "unpredictable" seed
//(you're guaranteed your seed will be the same only once,
//unless you start your program multiple times within the same second).
srand ( time(NULL) );

//We don't need to run for the first element that's why n-1 pass

for ( i = n-1; i > 0; i--) //for Shuffle card algorithm i=51
{
// Pick a random index from 0 to i
int j = rand() % (i+1);

// Swap a[i] with the element at random index
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

int main()
{
// shuffle the array
randomize ();
// print results.
for ( i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
output:-
29 8 47 10 49 28 24 43 14 13 48 32 2 12 
36 31 30 18 50 1 25 41 40 45 39 38 6 35
23 17 9 46 20 11 51 52 4 34 42 15 22 7
37 33 18 3 5 16 27 26 21 44



Learn more »