Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Wednesday, June 19, 2013

Interview Question (Programming in C++)

Give the output of the following program :

class Animal
{
  public :
  virtual void draw()
  {
    cout<<”Animal”;
  }
};
class Leopard : public Animal
{
  public :
  virtual void draw()
  {
    cout<<”Leopard”;
  }
};
main()
{
  Leopard l;
  Animal *a=&l;
  l.draw();
}

(A) Leopard (B) Animal (C) LeopardAnimal (D) AnimalLeopard

Answer :
(A) Leopard

Explanation :
The virtual keyword  indicates to the compiler that it should choose the appropriate definition of the function draw not by the type of reference, but by the type of object that the reference refers to.
For more details on the use of virtual keyword : Reference

Written by

Interview Question (Programming)

What does the following function check?

bool f(unsigned int v)
{
  return ((v!=0)&&!(v & v-1));
}

(A) v is an odd number (B) v is a multiple of 2 (C) v is a power of 2 (D) v has a 0 bit

Answer :
(C) v is a power of 2

Explanation :
1) If v is a power of 2,

  • v is never 0 (even 2^0 = 1) and (v != 0) will always be 1(True).
  • (v & v-1) will always be 0(False) and hence their negation will always be 1(True).
2) If v is not a power of 2, either
  • v = 0, or
  • (v & v-1) is something other than 0 and their negation is 0(False)


Written by

Wednesday, June 5, 2013

Cut the Gold Bar Twice and Pay for 7 Days - Puzzle#1

Puzzle : You have a 7 inch gold bar with you. You need to pay the servant 1 inch gold per day of work. (At the end of first day, servant should have 1 inch gold; at the end of second day, he should have 2 inch gold and so on). You may take back some of the given pieces if needed. How will you do this with minimum number of cuts of the gold bar?

Answer : 2 cuts (i.e 3 pieces => a 4 inch piece, a 2 inch piece and a 1 inch piece)

Explanation : TB = Take back



Written by

Wednesday, September 12, 2012

Minimum Distance Triplet in C


//Program : Given 3 arrays, find the triplet (containing one element from 
//each array) with the minimum distance. The distance of a triplet (a,b,c) 
//is defined as max(|a-b|, |b-c|, |c-a|)

#include<stdio.h>

int main()
{
  int n1, n2, n3, i, j, k, max, triplet_dist, trip_dist;
  int a1[10], a2[10], a3[10], triplet[3];

  // Input the 3 arrays
  printf("Enter the sizes of the 3 matrices\n");
  scanf("%d %d %d", &n1, &n2, &n3);
  printf("Enter the elements of the first array\n");
  for(i = 0; i < n1; i++)
    scanf("%d", &a1[i]);
  printf("Enter the elements of the second array\n");
  for(i = 0; i < n2; i++)
        scanf("%d", &a2[i]);
  printf("Enter the elements of the third array\n");
  for(i = 0; i < n3; i++)
        scanf("%d", &a3[i]);
  
  // Initialization of min distance
  triplet_dist = 9999;

  // Compute min distance of triplet
  for(i = 0; i < n1; i++)
    for(j = 0; j < n2; j++)
      for(k = 0; k < n3; k++)
      {
        // find out the distance of the triplet
        max = abs(a1[i] - a2[j]);
        if(abs(a2[j] - a3[k]) > max)
          max = abs(a2[j] - a3[k]);
        if(abs(a1[i] - a3[k]) > max)
          max = abs(a1[i] - a3[k]);
        
        // If the distance found is less than the already found min 
        // distance, update triplet array and triplet distance
        if(max < triplet_dist)
        {
          triplet_dist = max;
        }
      }

  // Print the min distance triplets
  printf("The minimum distance is %d\n", triplet_dist);
  printf("The min distance triplets are:\n");
  trip_dist = 9999;
  for(i = 0; i < n1; i++)
    for(j = 0; j < n2; j++)
      for(k = 0; k < n3; k++)
      {
        // findout the distance of the triplet
        max = abs(a1[i] - a2[j]);
         if(abs(a2[j] - a3[k]) > max)
           max = abs(a2[j] - a3[k]);
         if(abs(a1[i] - a3[k]) > max)
           max = abs(a1[i] - a3[k]);

         if(max == triplet_dist)
         {
           printf("(");
           printf("%d %d %d", a1[i], a2[j], a3[k]);
           printf(")");
           printf("\n");
         }
      }

  return 0;
}

Written by

Saturday, June 18, 2011

Interview Question - IF condition to print "Hello World" in C

What should be the so that the following code snippet prints ”Hello World”?


if( <condition> )
  printf ("Hello");
else
  printf("World");
Solution 1 - Using fork() system call

#include <stdio.h>

int main(void)
{
  if(fork())
    printf ("Hello ");
  else
    printf("World");

  return 0;
}
Solution 2 - Using return value of printf() function

#include <stdio.h>

int main(void)
{
  if(printf("Hello ") == 1)
    printf ("Hello");
  else
    printf("World");

  return 0;
}
Written by

Sunday, June 5, 2011

Count the Number of Bits Set in an Integer [Shift Operator]

Shift operators shift the bits in an integer variable by a specified number of positions. The << operator shifts bits to the left, and the >> operator shifts bits to the right. The syntax for these binary operators is x << n and x >> n Each operator shifts the bits in x by n positions in the specified direction. For a right shift, zeros are placed in the n high-order bits of the variable; for a left shift, zeros are placed in the n low-order bits of the variable.

Here are a few examples:

Binary 00001000 (decimal 8) right-shifted by 2 gives 00000010 (decimal 2).
Binary 00001000 (decimal 8) left-shifted by 3 gives 01000000 (decimal 64).

One of the application of shift operation is to count the number of bits set in an unsigned integer.
For example: f(0) = 0, f(1) = 1, f(2) = 1, f(3) = 2.

More information @ Wikipedia

Option 1: In a while loop, increment a counter if the last bit in the unsigned integer is 1 all the while right shifting the integer in each iteration of the while loop.

// C program to count the number of bits set in an integer

#include<stdio.h>

int main()
{
  unsigned int i, b[32] = {0};
  int j = 31, count = 0;
  printf("\nEnter the unsigned integer:");
  scanf("%d", &i);

  while(i != 0)
  {
    // Bitwise AND operation b/w i & 0x00000001 is 1
    // if the last bit of i is 1 and 0 if the last
    // last bit is 0
    b[j] = i & 0x00000001; 
    // Increment count whenever the bit is 1    
    if(b[j] == 1)
      count++;
    j--;
    // Right shifting i by 1 to get the next bit
    i = i >> 1;
  }

  printf("\nThe number of bits set in %d is %d", i, count);

  // The array b gives the binary representation of i
  printf("\nThe binary representation of %d is ", i);
  for(i = j + 1; j < 32; j++)
    printf("%d", b[j]); 

  return 0;
}


Brian Kernighan's method: Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to him that this method "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)".

long count_bits(long n) {     
  unsigned int c; // c accumulates the total bits set in v
  for (c = 0; n; c++) 
    n &= n - 1; // clear the least significant bit set
  return c;
}


Use built-in functions in compilers: GCC has the following built-in function to count the number of bits. The compiler can generate a single POPCNT instruction in the best case or generate a call to a function to count the number of bits in the worst case.

int __builtin_popcount (unsigned int x);


SWAR Algorithm: This uses a divide & conquer algorithm where the problem of summing the number of bits set in a 32 bit unsigned integer is divided into two problems of summing the number of bits set in a 16 bit integer. This strategy is applied recursively resulting in log2(32) = 5 steps. - From Hacker's Delight, p. 66, Figure 5-2

int pop(unsigned x)
{
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0F0F0F0F;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x0000003F;
}

These are some of the ways to tackle this problem.

References:



Written by