Showing posts with label data structure. Show all posts

What is difference between predicate logic, proportional logic and first order predicate logic?


  1. Predicate Logic: Predicate logic is the general form of all logics that uses predicates, like q(x). Here q is predicate. Predicate logic supports the ability to have variables, and quantifiers. For example, xy.p(x,y) means "For all x there exists a y such that the proposition p(x,y) is true".
  2. Propositional Logic: Propositional logic means without ability to do predication. For example, in P ^ Q, both p and q are propositions. 
  3. First order predicate logic:In first-order predicate logic, variables can appear only inside a predicate. That is, you can quantify over variables, but not predicates themselves. In second-order logic, you can also quantify over predicates, e.g. px.p(x)¬p(x) is true: for every predicate p, either p(x) or not p(x) is true, regardless of what x is.
Learn more »

Implement Tower of Hanoi Problem using C programmg with algorithm.


Tower of Hanoi problem:
Initial state:
  • There are three poles named as origin, intermediate and destination.
  • n number of different-sized disks having hole at the center is stacked around the
    origin pole in decreasing order.
  • The disks are numbered as 1, 2, 3, 4, ...................,n.
    Objective:
Transfer all disks from origin pole to destination pole using intermediate pole for temporary storage.
Conditions:
  • Move only one disk at a time.
  • Each disk must always be placed around one of the pole.
  • Never place larger disk on top of smaller disk.
    Algorithm: - To move a tower of n disks from source to dest (where n is positive integer):
    1. If n ===1:
    1.1. Move a single disk from
    source to dest.
    2. If n > 1:
    2.1. Let
    temp be the remaining pole other than source and dest.
    2.2. Move a tower of (n – 1) disks form source to temp. 2.3. Move a single disk from source to dest.
    2.4. Move a tower of (
    n – 1) disks form temp to dest.
    3. Terminate.
    Example: Recursive solution of tower of Hanoi:
    #include <stdio.h>
    #include <conio.h>
    void TOH(int, char, char, char); //Function prototype void main()
    {

    int n;
    printf(“Enter number of disks”); scanf(“%d”,&n); TOH(n,’O’,’D’,’I’);
    getch();

    }
    void TOH(int n, char A, char B, char C) {
    if(n>0) { 

    TOH(n-1, A, C, B);
    Printf(“Move disk %d from %c to%c\n”, n, A, B); TOH(n-1, C, B, A);


    } }
Learn more »

Why do we need data types?

Data types are format of literals or values that is stored in a variable. Data types are important in web applications or software or programs in many sense. Some of the important significance can be as follows:
  • If we know the data types, more analytical processing can be done. For example, we know the price of items are mostly in double format. It prevents us to think that, any string can be stored in it. We know that we can perform mathematical operations, statistical analysis with double value and come of with some reasoning.
  • Data types gives meaning to data. Integer data types tells that literals are in integer format, where as String data types indicates that it is composed of set of letters etc. 
  • Data types helps to distinguish different categories of values. It helps to distinguish between small numbers, numbers with decimal and values with letters etc.
Learn more »

Write a C method named isPrepareSArray that returns 1 if its array argument is a PrepareS array, otherwise return 0.

A PrepareS array has the following property.
a[0] = a[1] + a[2] = a[3]+a[4]+a[5] = a[6] + a[7] + a[8]+ a[9] = ....

Then length of PrepareS array must be n*(n+1)/2 for some n.
Write a C method named isPrepareSArray that returns 1 if its array argument is a PrepareS array, otherwise return 0.



//
//  main.c
//  pattern2
//
//  Created by Suresh KUMAR Mukhiya on 7/11/14.
//  Copyright (c) 2014 Suresh KUMAR Mukhiya. All rights reserved.
//

#include <stdio.h>

int isMadhavArray(int b[],int len)
{
    int m = 0, n = sqrt(8*len+1)/2,flag = 1;
    int sizeCheck = checkSize(len);
    if(sizeCheck == 1)
    {
        flag = 1;
    }
    else{
        flag = 0;
    }
    for(int i = 0; i<n; i ++)
    {
        int sum=0;
        for(int j = 0; j<i+1; j++)
        {
           
            sum = sum + b[m];
            m = m+ 1;

           
        }
       
        if(b[0] != sum)
        {
            flag = 0;
            break;
        }
    }
   
    return flag;
}

int main(int argc, const char * argv[])
{
   
        //int b[] = {2,1,1};
        //int b[] = {2,1,1,4,-1,-1};
       // int b[] = {6,2,4,2,2,2,1,5,0,0};
    //int b[] = {18,9,10,6,6,6};
    //int b[] = {3,1,2,3,0};
        //int b[] = {0,0,0,0,0,0,0,0,0,0,1,1,1,-2,-1};
        int b[] = {-6,-3,-3,8,-5,-4};
        int len = (sizeof(b)/sizeof(b[0]));
        int r = isMadhavArray(b, len);
        printf("isMadhavArray= %d\n",r);
   
    return 0;
}

int checkSize(int n)
{
    int trues = 1;
    int number = 8*n+1;
    int temp = sqrt(number);
    if(temp * temp !=number)
    {trues = 0;}
    return trues;
}

Some Tracings:
2,1,1 = is PrepareS array, returns 1
2,1,1,4,-1,-1 is PrepareS array, returns 1
3,1,2,3,0 is NOT PrepareS Array, returns 0 because it does not satisfy n*(n+1)/2 length.
Learn more »

What is an expression tree? How an expression is evaluated using an expression tree? Discuss its advantages over the other evaluation techniques.

Algebraic expressions such as 
a/b+(c-d)e  
have an inherent tree-like structure. For example, following figure is a representation of the expression in above equation. This kind of tree is called an expression tree
 
Fig: Example of Expression tree
 
The terminal nodes (leaves) of an expression tree are the variables or constants in the expression (a, b, c, d, and e). The non-terminal nodes of an expression tree are theoperators (+, -, x, / and )
 
The expression tree is evaluated using a post-order traversal of the expression tree as follows:
    1. If this node has no children, it should return the value of the node
    2. Evaluate the left hand child
    3. Evaluate the right hand child
    4. Then evaluate the operation indicated by the node and return this value

    Advantages of expression tree


    Understanding the order of operation. Operations that must be done sooner are further to the right in the tree.
    Counting the number of terms or factors in an expression. Each term or factor is a child node. For example the expression (a+b)/c+2*d contains two terms.

Learn more »

Differentiate between Compiler and Interpreter.


COMPILER
INTERPRETER
1.     A compiler translates the entire source program into object program in a single attempt, and then only the object program is executed.
2.     Compiler is faster than interpreter because the execution time is less. A compiler is 5 to 25 times faster than an interpreter.
3.     Compiler is a complex program i.e. it is larger than that of interpreter.
4.     As compared to an interpreter, developing a compiler is difficult task.
5.     Compiler make it little bit difficult and slower to detect and correct the syntax error.
6.     A compiler is a big and complex program therefore it occupies more space in memory.
7.     The compiled program (called object code) is permanently saved in the hard disk for future use. Therefore, the program need not be recompiled for execution next time.
1.     An interpreter translates one statement at a time, executes it and continues for another statement.
2.     Interpreter is slower than compiler because the execution time is more.
3.     Interpreter is less complex program than Compiler. An interpreter is a smaller program as compared to compiler.
4.     As compared to a compiler, developing an interpreter is easier.
5.     Interpreter makes it easier to detect syntax error in a program.
6.     An interpreter is smaller and less complex than compiler.It occupies less memory space.
7.     The interpreter program is temporarily saved, therefore need to reinterpreted next time.
Learn more »

Explain in detail about binary search algorithm.


Introduction
Binary search is an extremely efficient algorithm. This search technique searches the given item in minimum possible comparisons. To do the binary search, first we have to sort the array elements. The logic behind this technique is given below.
1.                                                                           First find the middle element of the array.
2.         Compare the middle element with an item.
3.         There are three cases.
a). If it is a desired element then search is successful,
b). If it is less than the desired item then search only in the first half of the array.
c). If it is greater than the desired item, search in the second half of the array.
4. Repeat the same steps until an element is found or search area is exhausted.

In this way, at each step we reduce the length of the list to be searched by half.

Requirements
  1. The list must be ordered
  2. Rapid random access is required, so we cannot use binary search for a linked list

Algorithm
Let 'a’ be the array of size 'Maxsize' and 'LB', 'UB' and 'mid' are variables to denote first, last and middle location of a segment. This algorithm finds the location 'Loc' of 'item' in array 'a’ or return fail(sets loc=NULL).

1.     [Initialize segment variables]
set beg = LB, end = UB and mid = int((beg + end)/2)
2.     Repeat steps 3 and 4 while beg<=end and a[mid]!=item
3.     if item<a[mid],then
set end=mid – 1
Else
set beg=mid + 1
[End if]
4.     set mid=int((beg + end)/2)

5      if a[mid]=item then
set loc=mid
print the value and its position
else
set loc=NULL
print search unsuccessful
[End if]
6.     Exit

Binary search efficiency

  1. In all cases, the no. of comparisons in proportional to n
  2. Hence, no. of comparisons in binary search is O (log n), where n is the no of items in the list
  3. Obviously binary search is faster then sequential search, but there is an extra overhead in maintaining the list ordered
  4. For small lists, better to use sequential search
  5. Binary search is best suited for lists that are constructed and sorted once, and then repeatedly searched

Binary Search Procedure

void binsrch( int a[], int beg, int end, int item)
{
int mid;
int count = 0;
mid = (beg + end)/2;
while(beg <= end && item != a[mid])
{
If(item < a[mid])
end = mid - 1;
else
beg = mid + 1;
mid = (beg + end)/2;
count ++;
}



if(item == a[mid])
{
printf(“\nSearch Successful!!!\n It took %d iterations to find this item”, cnt);
         printf(“\nThe position is %d”,mid);
}
else
printf(“\n Search Unsuccessful”);
getch();
}
Learn more »

What are the advantages and disadvantages of array?


Advantages of Array:

  1. An array implementation allows Print to be carried out in linear time and FindKth operation in constant time, which is good as can be expected
  2. Random access is possible
  3. Implementation of list using array is easier as compared to other implementations

Disadvantages of Array:

  1. Elements of arrays are always stored in contiguous memory
    1. Inserting or deleting an element in an array may require all of its elements to be shifted
  2. The size of array is always fixed
    1. You cannot add a new element beyond the end of the array
    2. Memory for the entire array is always reserved even though you use only part of the array
    3. You must guess the expected maximum size of the list in advance

Learn more »

Write a C program to find determinant of nxn matrix.

#include<conio.h>
#include<stdio.h>

int a[20][20],m;
int determinant(int f[20][20],int a);
int main()
{
  int i,j;
  printf("\n\nEnter order of matrix : ");
  scanf("%d",&m);
  printf("\nEnter the elements of matrix\n");
  for(i=1;i<=m;i++)
  {
  for(j=1;j<=m;j++)
  {
  printf("a[%d][%d] = ",i,j);
  scanf("%d",&a[i][j]);
  }
  }
  printf("\n\n---------- Matrix A is --------------\n");    
  for(i=1;i<=m;i++)
     {
          printf("\n");
          for(j=1;j<=m;j++)
          {     
               printf("\t%d \t",a[i][j]);
          }
     }
  printf("\n \n");
  printf("\n Determinant of Matrix A is %d .",determinant(a,m));
  getch();
}

int determinant(int f[20][20],int x)
{
  int pr,c[20],d=0,b[20][20],j,p,q,t;
  if(x==2)
  {
    d=0;
    d=(f[1][1]*f[2][2])-(f[1][2]*f[2][1]);
    return(d);
   }
  else
  {
    for(j=1;j<=x;j++)
    {        
      int r=1,s=1;
      for(p=1;p<=x;p++)
        {
          for(q=1;q<=x;q++)
            {
              if(p!=1&&q!=j)
              {
                b[r][s]=f[p][q];
                s++;
                if(s>x-1)
                 {
                   r++;
                   s=1;
                  }
               }
             }
         }
     for(t=1,pr=1;t<=(1+j);t++)
     pr=(-1)*pr;
     c[j]=pr*determinant(b,x-1);
     }
     for(j=1,d=0;j<=x;j++)
     {
       d=d+(f[1][j]*c[j]);
      }
     return(d);
   }
}
Learn more »

Write a sample C programming Codes to implement selection sort.


// C program to implement selection sort.
#include<stdio.h>
int main(){
  int s,i,j,temp,a[20];
  printf("Enter total elements: ");
  scanf("%d",&s);
  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);
  for(i=0;i<s;i++){
      for(j=i+1;j<s;j++){
           if(a[i]>a[j]){
               temp=a[i];
              a[i]=a[j];
              a[j]=temp;
           }
      }
  }
  printf("After sorting is: ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);
  return 0;
}

Sample Output:
Enter total elements: 8
Enter 5 elements: 4 5 0 21 7 1 2 9
The array after sorting is:  0 1 2 4 5 7 9 21
Learn more »