Showing posts with label programming in c++. Show all posts
Showing posts with label programming in c++. Show all posts

Wednesday, June 19, 2013

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, October 10, 2012

Birthday Paradox Simulation in C

/* Given a group of n people how to calculate the probability that m people among them have the same birthday without using a formula*/


#include<stdio.h>
#include<stdlib.h>

int main()
{
  int i, n, m, rand_birthday, j, a;
  int *array = NULL, c, k, t;
  float count = 0.0, trial = 1.0, prob, percent;
  
  printf("\nEnter the number of people in a room:");
  scanf("%d", &n);
  printf("\nEnter the number of people whose birthday ");
  printf("needs to be on the same day:");
  scanf("%d", &m);
  printf("\nEnter the no. of trials:");
  scanf("%d", &t);

  // Dynamically allocate memory for n elements
  array = (int *)calloc(n, sizeof(int));

  while(trial <= t)
  {
    for(i = 0; i < n; i++)
    {
      rand_birthday = gen_rand();
      array[i] = rand_birthday;
    }
    printf("\nRandom birthdays are : \n");
    for(i = 0; i < n; i++)
      printf(" %d ", array[i]);
    printf("\n");
  
    // Sorting the birthdays
    for(i = 0; i < n; i++)
    {
      for(j= i + 1; j < n; j++)
      {
        if(array[i] > array[j])
        {
          a = array[i];
          array[i] = array[j];
          array[j] = a;
        }
      }
    }

    printf("\nRandom birthdays(sorted) are : \n");
    for(i = 0; i < n; i++) 
      printf(" %d ", array[i]);
    printf("\n");

    // Check for the same birthdays
    i = 0; j = 1; 
    while(j < n)
    {
      c = 1;
      if(array[i] != array[j])
      {
        i++;
        j++;
      }
      else
      {
        for(k = j; ((k < n) && (array[i] == array[k])); k++)
          c++;
        i = k;
        j = k + 1;
        if(c >= m)
        {
          count++;
          break;
        }
      }
    }
    trial++;
  }

  // Calculate the probability
  printf("\ncount = %f, \ntrials = %f\n", count, trial);
  prob = (count/trial);
  printf("Probability of getting %d same birthdays", m);
  printf(" among %d people is %f", n, prob);
  percent = prob * 100;
  printf(" = %f percentage\n", percent);

  return 0;
}

int gen_rand(void)
/* returns random number in range of 0 to 364 */
{
   int n;
   n=rand() % 365;
   return(n);
}




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

Sunday, September 25, 2011

Function to count the number of terminal(leaf) nodes in a binary tree.

The function "terminal_count()" counts the number of leaf nodes of a binary tree.

int terminal_count(struct node *t)
{
  static int count = 0;
  if((t -> Llink == NULL) && (t -> Rlink == NULL))
    return 1;
  else
    count = count + terminal_count(t -> Llink) + terminal_count(t -> Rlink);
  return count;
}

Written by

Height of a Binary Tree

Function to find the height of a binary tree


int height(struct node *t)
{
  if(t == NULL)
    return 0;
  int left = height(t -> Llink);
  int right = height(t -> Rlink);
  if(left > right)
    return left + 1;
  else 
    return right + 1; 
  }
}

Written by

Saturday, September 24, 2011

Reverse a Circular Doubly Linked List - Recursive Solution

Function to reverse a Circular Doubly Linked List

A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes.

The structure of a node in a Doubly linked list is as given below.

struct node
{
  struct node *Llink;
  int data;
  struct node *Rlink;
}


If we create the Doubly linked list in a circular fashion, it forms a Circular doubly linked list.

The function "reverse" reverses a circular doubly linked list with the head node given.

void swap(struct node *p,struct node *q)
{
  struct node *r;
  r = p;
  p = q;
  q = r;
}

void reverse(struct node *head)
{
  struct node *t = head -> Rlink;
  while(t != head)
  {
    swap(t -> Llink, t ->Rlink);
    t = t -> Llink;
  }
  swap(head -> Llink, head -> Rlink)
}

Written by

Reverse a Linked List - Recursive Solution

Function to reverse a linked list - recursive solution


void reverse(struct node *pred, struct node *curr)
{
  if(curr)
  {
    reverse(curr, curr -> link);
    curr -> link = pred;
  }
  else
    first = pred;
}

void main()
{
  reverse(NULL, first);
}

Written by

Reverse a Linked List - Iterative Solution

Function to reverse a linked list - iterative solution


void reverse(struct node *first)
{
  // p is used to traverse the linked list
  struct node *p = first;
  // q points to the start of the reversed list
  struct node *q = NULL;
  // r is a temporary variable used in this process
  struct node *r;

  while(p)
  {
    r = q;
    q = p;
    p = p -> link;
    q -> link = r;
  }
  first = q;
}

Written by

Count the Number of Nodes in a Linked List - Recursive Solution

Function to count the number of nodes in a linked list - recursive solution


int count(struct node *p)
// p is a pointer to the first node of the list.
{
  if(p)
    return 1 + count(p->link);
  else
    return 0;
}


Written by

Function to count the number of nodes in a linked list - iterative solution


int count(struct node *first)
// first is a pointer to the first node
{
  struct node *p = first;
  int count = 0;
  while(p)
  {
    ++count;
    p = p->link;
  }
  // Final value of count gives the number of nodes
  // in the linked list.
  return count;
}

Written by

Saturday, August 6, 2011

Heap Sort in C - Iterative Algorithm

"Heapsort is a comparison-based sorting algorithm to create a sorted array (or list), and is part of the selection sort family. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but is not a stable sort." - Wikipedia

#include<stdio.h>
#define maxheapsize 50
#define LEFT(i) 2*i
#define RIGHT(i) 2*i+1

MAX_HEAPIFY(int *a, int i, int size)
{
  // Largest of a[i], a[LEFT(i)] and a[RIGHT(i)]
  // is determined and the index is stored in "largest".
  int l, r, largest, temp;
  l = LEFT(i);
  r = RIGHT(i);
  if ((l <= size)&&(a[l] > a[i]))
    largest = l; 
  else largest = i;
  if((r <= size)&&(a[r] > a[largest]))
    largest = r;
  
  // If largest != i, swap a[i] and a[largest]
  // and heapify the subtree rooted at largest
  if(largest != i)
  {
    temp = a[i];
    a[i] = a[largest];
    a[largest] = temp;

    MAX_HEAPIFY(a, largest, size);
  }
}

BUILD_MAX_HEAP(int *a, int size)
{
  int i;

  // 2nd half of the array are leaf nodes, so each is a
  // 1-element heap to begin with.
  for(i = size/2; i > 0; i--)
    MAX_HEAPIFY(a, i, size);
}

HEAPSORT(int *a, int size)
{
  int sortedarray[maxheapsize], actualsize, root;
  int i, s = 0, j, temp;
  actualsize = size;
  
  // Build the heap tree
  BUILD_MAX_HEAP(a, size); 
  
  for(i = size; i > 0; i--)
  { 
    // Save the root to another array
    sortedarray[++s] = a[1];
    root = a[1];

    // exchange a[1](root) and a[i]
    temp = a[1];
    a[1] = a[i];
    a[i] = temp;
    
    size--;
    
    // MAX_HEAPIFY lets the value of a[i] "float down" in
    // the max-heap so that the subtree rooted at index i
    // obeys the max-heap property
    MAX_HEAPIFY(a, 1, size);

    printf("\nHeap tree after removing the largest element %d\n", root);
    for(j = 1; j<=size; j++)
      printf("%d ", a[j]);
    if(size == 0)
      printf("NULL\n");
  }

  // Print the sorted array
  printf("\nSorted array\n");
  for(i = actualsize; i > 0; i--)
    printf("%d ", sortedarray[i]);
}

int main()
{ 
  int a[maxheapsize], n, i;
  printf("\nEnter the size of the array (< 50):");
  scanf("%d", &n);
  printf("\nEnter the elements of the array\n");
  for(i = 1; i <= n; i++)
    scanf("%d", &a[i]);

  HEAPSORT(a, n);

  return 0;
}
Written by

Sunday, July 3, 2011

GATE 2010 C Programming Question

GATE 2013 Comprehensive Information Pagehttp://www.codeblocks.info/2012/08/gate-2013.html

What is the value printed by the following C program?

#include <stdio.h>

int f(int *a, int n)
{
  if(n <= 0) return 0;
  else if(*a % 2 == 0) return *a + f(a + 1, n - 1);
  else return *a - f(a + 1, n - 1);
}

int main()
{
  int a[] = {12, 7, 13, 4, 11, 6};
  printf("%d", f(a, 6));
  return 0;
}



(A) -9
(B) 5
(C) 15
(D) 19

Answer
------
(C) 15

Explanation
-----------
f(12,....6, 6) = 12 + f(7,....6, 5)
f(7,....6, 5) = 7 - f(13,....6, 4)
f(13,....6, 4) = 13 - f(4,....6, 3)
f(4,....6, 3) = 4 + f(11,....6, 2)
f(11,....6, 2) = 11 - f(6, 1)
f(6, 1) = 6 + f(NULL, 0)
f(NULL, 0) = 0

Hence, 12 + (7 - (13 - (4 + (11 - (6 + (0)))))) = 15
Written by

Thursday, June 23, 2011

GATE 2011 C Progamming Question

GATE 2013 Comprehensive Information Pagehttp://www.codeblocks.info/2012/08/gate-2013.html

Consider the following recursive function that takes two arguments

unsigned int foo(unsigned int n, unsigned int r)  {
  if(n > 0) return ((n % r) + foo(n / r, r));
  else return 0;
}


What is the return value of the function "foo" when it is called as foo(345, 10)?

(A) 345
(B) 12
(C) 5
(D) 3

Answer: (B) 12
5 + 4 + 3 + 0 = 12

What is the return value of the function "foo" when it is called as foo(513, 2)?

(A) 9
(B) 8
(C) 5
(D) 2

Answer: (D) 2
1 + 1 = 2
Written by

Saturday, June 18, 2011

GATE 2011 C Programming Question

GATE 2013 Comprehensive Information Pagehttp://www.codeblocks.info/2012/08/gate-2013.html

What does the following fragment of C program print?

  char c[] = "GATE2011";
  char *p = c;
  printf("%s", p + p[3] - p[1]);

(A) GATE2011
(B) E2011
(C) 2011
(D) 011

Answer: (C) 2011

Explanation:
p[3] = A (Ascii = 65)
p[1] = E (Ascii = 69)
p[3] - p[1] = 4
p + p[3] - p[1] = p + 4


printf starts printing from the p + 4 till the end giving 2011

Written by

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

Saturday, May 28, 2011

Basic Stack Operations in C

Basic stack operations in C

"A stack is a basic computer science data structure and can be defined in an abstract, implementation-free manner, or it can be generally defined as a linear list of items in which all additions and deletion are restricted to one end that is Top." - Wikipedia
Written by

Wednesday, May 18, 2011

Friday, May 13, 2011

Check if a String is Palindrome in C

"A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers." - Wikipedia

This is a C program to check if a given string is a palindrome or not.
Written by