The Programming Project

Wednesday, October 8, 2014

Binary Tree Traversal : C Code


Binary Tree Traversals inorder,preorder and postorder.  

#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void preorderTraversal(node *root);
void inorderTraversal(node *root);
void postorderTraversal(node *root);

int main() {
   node *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);   
      if( val == -1)
          break;
      insert(&root, val);
   }
   printf("\n Pre-order Traversal:");
   preorderTraversal(root);
   printf("\n");
   printf("\n Inorder Traversal:");
   inorderTraversal(root);
   printf("\n");
   printf("\n Postorder Traversal:");
   postorderTraversal(root);
   printf("\n");
   return 0;
}
void postorderTraversal(node *root) {
    if (root != NULL) {
            postorderTraversal(root->left);
            postorderTraversal(root->right);
              printf("%d ",root->key);
                }
    }
void inorderTraversal(node *root) {
    if (root != NULL) {
            inorderTraversal(root->left);
              printf("%d ",root->key);
                inorderTraversal(root->right);
               }
    }
void preorderTraversal(node *root) {
    if (root != NULL)
        printf("%d ",root->key);
    if (root->left != NULL)
        preorderTraversal(root->left);   
    if (root->right != NULL)
        preorderTraversal(root->right);       
    }
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Binary Search Tree (BST) : Finding Leaves : C Code

 Binary Search Tree (BST) : Finding Leaves : C Code

The following C code prints all the leaves nodes of a Binary Search Tree. A leaf-node is a node which has not left or right child. The code first scans the root node and looks whether it has a left and right child or not. If the condition is satisfied, it  is a leave node or else we recursively examine the left and right child.

#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void printLeaves(node *root);

int main() {
   node *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);   
      if( val == -1)
          break;
      insert(&root, val);
   }
  
   printLeaves(root);
   printf("\n");
   
   return 0;
}
void printLeaves(node *root) {
    if (root->right == NULL && root->left == NULL) {
        printf("\n Leaf Node: %d",root->key);
        return;
        }
    if(root->right != NULL)    
        printLeaves(root->right);
    if(root->left != NULL)   
    printLeaves(root->left);
    }
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Tuesday, October 7, 2014

Binary Tree C Code : Insertion : Find Max & MIn

In computer science, a binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a node-based binary tree data structure where each node has a comparable key (and an associated value) and satisfies the restriction that the key in any node is larger than the keys in all nodes in that node's left subtree and smaller than the keys in all nodes in that node's right sub-tree.

Insertion begins as a search would begin; if the key is not equal to that of the root, we search the left or right subtrees as before. Eventually, we will reach an external node and add the new key-value pair  as its right or left child, depending on the node's key. In other words, we examine the root and recursively insert the new node to the left subtree if its key is less than that of the root, or the right subtree if its key is greater than or equal to the root. Self referential structure has been used to link the nodes starting from the root node. In the code below, maximum and minimum value in the BST has been also calculated.


#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void findMax(node *root);
void findMin(node *root);
void searchKey(node *,int key);

int main() {
   node  *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);  
      if( val == -1)
          break;
      insert(&root, val);
   }
 
   findMin(root);
   printf("\n");
 
   findMax(root);
   printf("\n");
 
   printf("\n Enter the value to be searched:");
   scanf("%d",&search);
   searchKey(root,search);
   printf("\n");
  
   return 0;
}
void searchKey(node *root,int search) {
    if (root == NULL) {
        printf("\n Element Not Found:");
        return;
        }
    if (root->key == search) {
        printf("\n Key found:");
        return;
        }
    root->key < search ? searchKey(root->right,search) : searchKey(root->left,search);
    }
  
void findMax(node *root) {
    while(root->right != NULL)
        root = root->right;
    printf("\n Maximum value is:%d",root->key);
    }
  
void findMin(node *root) {
    while(root->left != NULL)
        root = root->left;
    printf("\n Minimum value is:%d",root->key);
    }  
  
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }

Monday, October 6, 2014

Addition of positive numbers using linked list: C code

Addition of large positive integers in C is quite difficult since there will be overflow error once the range of 'int' is crossed. But this problem can be overcome by the use of linked list. Happy addition! 



#include<stdio.h>
#include<stdlib.h>
struct numberList {
    int data;
    struct numberList *nextDigit;
    struct numberList *revDigit;
    };
    typedef struct numberList node;
void inputNumber(node*);
void display(node*,int);   
void addNumber(node*,node*);
int main() {
   
    node *firstNumber,*secondNumber,*sum;
    firstNumber = (node *)malloc(sizeof(node));
    secondNumber = (node *)malloc(sizeof(node));
    printf("\n Enter the first number(one digit at a time) type -1 to terminate the number:");
    printf("\n Enter the digit:");
    scanf("%d",&firstNumber->data);
    inputNumber(firstNumber);
   
    printf("\n Enter the second number(one digit at a time) type -1 to terminate the number:");
    printf("\n Enter the digit:");
    scanf("%d",&secondNumber->data);
    inputNumber(secondNumber);
   
    display(firstNumber,1);
    display(secondNumber,2);
   
    addNumber(firstNumber,secondNumber);   
    return 0;
    }   
void addNumber(node *p,node *q) {
    int len1=0,len2=0,min,i,once=0;
    while (p->nextDigit !=NULL) {
        len1++;
        p = p->nextDigit;
        }
    p = p->revDigit;   
    while (q->nextDigit !=NULL) {
        len2++;
        q = q->nextDigit;
        }
    q = q->revDigit;
    min = len1 <= len2 ? len1:len2;
    node *sum,*tmp,*sum1;   
    sum = (node *)malloc(sizeof(node));
    sum1 = sum;
    sum->revDigit = NULL;
    for ( i = 1; i <= min; i++) {
        sum->data = (p->data+q->data+once)%10;
        tmp = sum;
        once = (p->data+q->data+once)/10;
        p=p->revDigit;
        q=q->revDigit;
        sum->nextDigit = (node *)malloc(sizeof(node));
        sum = sum->nextDigit;
        sum->revDigit=tmp;
        }
    if ( len1 == len2 && once !=0) {
        sum->data = once;
        sum->revDigit=tmp;
        }   
    if (len1 > len2) {
        int t = len1-len2;
        sum = sum->revDigit;
        for ( i = 1; i<=t; i++) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->revDigit=tmp;
            sum->data = (p->data+once)%10;
            once = (p->data+once)/10;
            p = p->revDigit;
            } 
        if ( once !=0) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->data = once;
            sum->revDigit=tmp;
            }
               
        }   
    if (len1 < len2) {
        sum = sum->revDigit;
        int t = len2-len1;
        for ( i = 1; i<=t; i++) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->revDigit=tmp;
            sum->data = (q->data+once)%10;
            once = (q->data+once)/10;
            q = q->revDigit;
            }
        if ( once !=0) {
            tmp = sum;
            sum->nextDigit = (node *)malloc(sizeof(node));
            sum = sum->nextDigit;
            sum->data = once;
            sum->revDigit=tmp;
            }   
        }   
    sum->nextDigit = NULL;   
    printf("\n Sum of the numbers is:");
    while (sum1->nextDigit !=NULL) {
        //printf("\n%d",sum1->data);
        sum1 = sum1->nextDigit;
        }
    //sum1 = sum1->revDigit;   
    while (sum1 !=NULL) {
        printf("%d",sum1->data);
        sum1 = sum1->revDigit;
        }
    printf("\n");   
    }   
void display(node *p,int tx) {
    if (tx==1)
        printf("\nFirst Number\n");
    else
        printf("\nSecond Number\n");
    while (p->nextDigit !=NULL) {
        printf("%d",p->data);
        p = p->nextDigit;
        }
    p = p->revDigit;   
    /*while (p !=NULL) {
        //printf("%d",p->data);
        p = p->revDigit;
        }*/   
    }   
void inputNumber(node *p) {
    node *q;
    p->revDigit = NULL;
    while (1) {
        q = p;
        p->nextDigit = (node *)malloc(sizeof(node));
        p = p->nextDigit;
        printf("\n Enter the digit:");
        scanf("%d",&p->data);
        p->revDigit = q;
        if (p->data == -1)
            break;
        }
    p->nextDigit = NULL;
    }     

Tuesday, September 30, 2014

Largest product in a grid : Problem 11 Euler Project

In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?

Largest product in a grid : Problem 11 Source: Euler Project
I have saved the matrix in a file "11.txt"

C Code:

#include<stdio.h>
#include<malloc.h>
int main()
{
int **matrix,row,col,maxProduct=1;
int i,j;
int s1,s2,s3,s4,s5,s6,s7,s8;
FILE *fp;
matrix = (int **)malloc(20*sizeof(int*));
for(i=0;i<20;i++)
    matrix[i]=(int *)malloc(20*sizeof(int));
fp = fopen("11.txt","r");
while(!feof(fp)) {
    for(row=0;row<20;row++) {
        for(col=0;col<20;col++) {
        fscanf(fp,"%d",&matrix[row][col]);
            }
        }
    }
for(i=0;i<20;i++) {
    s1=s2=s3=s4=s5=s6=s7=s8=1;
    for(j=0;j<20;j++) {
        // left-sum
        if(j-3 < 0)
            s1 = 1;
        else
            s1 = matrix[i][j]*matrix[i][j-1]*matrix[i][j-2]*matrix[i][j-3];
        if (maxProduct < s1)   
            maxProduct =s1;
        // right-sum   
        if(j+3 >= 20)
            s2 = 1;
        else
            s2 = matrix[i][j]*matrix[i][j+1]*matrix[i][j+2]*matrix[i][j+3];   
        if (maxProduct < s2)   
            maxProduct =s2;   
        // up-sum
        if(i-3 <0)
            s3 = 1;
        else
            s3 = matrix[i][j]*matrix[i-1][j]*matrix[i-2][j]*matrix[i-3][j];   
        if (maxProduct < s3)   
            maxProduct =s3;           
        // down-sum
        if(i+3 >= 20)
            s4 = 1;
        else
            s4 = matrix[i][j]*matrix[i+1][j]*matrix[i+2][j]*matrix[i+3][j];   
        if (maxProduct < s4)   
            maxProduct =s4;   
        // diag-up-left
        if(j-3 < 0 || i - 3 < 0)
            s5 = 1;
        else
            s5 = matrix[i][j]*matrix[i-1][j-1]*matrix[i-2][j-2]*matrix[i-3][j-3];   
        if (maxProduct < s5)   
            maxProduct =s5;   
        // diag-up-right
        if(i-3 < 0 || j + 3 >= 20)
            s6 = 1;
        else
            s6 = matrix[i][j]*matrix[i-1][j+1]*matrix[i-2][j+2]*matrix[i-3][j+3];
        if (maxProduct < s6)   
            maxProduct =s6;   
        // diag-down-left       
        if(i+3 >= 20 || j-3 < 0)
            s7 = 1;
        else
            s7 = matrix[i][j]*matrix[i+1][j-1]*matrix[i+2][j-2]*matrix[i+3][j-3];
        if (maxProduct < s7)   
            maxProduct =s7;   
        // diag-down-right       
        if(i+3 >= 20 || j+3 >=20)
            s8 = 1;
        else
            s8 = matrix[i][j]*matrix[i+1][j+1]*matrix[i+2][j+2]*matrix[i+3][j+3];   
        if (maxProduct < s8)   
            maxProduct =s8;           
        }
       
    }   
printf("\nLargest Product is %d",maxProduct);   
fclose(fp);           
return 0;   
}

Sunday, September 7, 2014

Combinatoric selections : Problem 53 Euler Project

Combinatoric selections :Problem 53

There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr =
n!
r!(n−r)!
,where rn, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of  nCr, for 1 ≤ n ≤ 100, are greater than one-million?

Problem Source : Euler Project

Python Code:

 def combinatoricSelection():
    def binomial(n,k):
        if k < 2:
            if k == 1:
                return n
            else:
                return 1
        else:
            return (n*binomial(n-1,k-1))/k
   
    n = 23
    counter = 0
    for i in range(78):
        i = i + n
        for j in range (i):   
            if binomial(i,j) > 1000000:
                counter = counter + 1
    print counter               
combinatoricSelection()


Self powers : Problem 48 Euler Project

Self powers : Problem 48 Euler Project

The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.

Python Code

def selfPower():
     sumT = 0
     for i in range(1000):
             i = i+1
             sumT = sumT + (i**i)%10000000000
     print "last ten digits of the sum:",sumT%10000000000
selfPower()