Thursday, 22 December 2022

CN

 

 // Hamming code
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int m_size, rbit = 0, msg[50], data[60], i, k, j, count = 0;
    cout << "\nEnter message size: ";
    cin >> m_size;

    // calculate value of r  2^r >= m_size +rbit +1
    while (1)
    {
        if ((m_size + rbit + 1) <= (int)pow(2, rbit))
            break;

        rbit++;
    }
    cout << "Enter message: ";
    for (i = m_size; i >= 1; i--)
    {
        cin >> msg[i];
    }
    k = 0; // for 2^k
    j = 1; // position of r bit
    for (i = 1; i <= (m_size + rbit); i++)
    {
        if (i == (int)pow(2, k))
        {
            data[i] = 8;
            k++;
        }
        else
        {
            data[i] = msg[j];
            j++;
        }
    }
    for (i = 1; i <= (m_size + rbit); i++)
    {
        if (data[i] == 8)
        {
            data[i] = 0;
            int count = 0;
            for (j = i; j <= (m_size + rbit); j++)
            {
                for (k = 0; k < i; k++)
                {
                    if (data[j] == 1)
                    {
                        count++;
                    }
                    j++;
                }
                j = j + i - 1;
            }

            if (count % 2 == 0)
                data[i] = 1;
            else
                data[i] = 0;
        }
    }
    cout << "\nSender side code: ";
    for (i = (m_size + rbit); i >= 1; i--)
        cout << data[i] << " ";
    cout << "\n\n-------------------------------------------------------\n"
         << endl;

    cout << "Enter receiver side code: ";
    for (i = (m_size + rbit); i >= 1; i--)
        cin >> data[i];

    int c = 0;

    int parities[m_size] = {0};
    for (i = 1; i <= (m_size + rbit); i++)
    {
        if (i == (int)pow(2, c))
        {
            count = 0;
            for (j = i; j <= (m_size + rbit); j++)
            {
                for (k = 0; k < i; k++)
                {
                    if (data[j] == 1)
                    {
                        count++;
                    }
                    j++;
                }
                j = j + i - 1;
            }
            if (data[i] == 1)
                count--;
            if (count % 2 == data[i])
                parities[c] = 1;
            else if (count % 2 != data[i])
                parities[c] = 0;
            c++;
        }
    }
    c = 0;
    for (int i = 0; i < rbit; i++)
    {
        c += parities[i] * ((int)pow(2, i));
    }
    if (c == 0)
    {
        cout << "NO ERROR FOUND !!!" << endl;
        exit(0);
    }
    cout << "\nError at position: " << c << endl;
    data[c] = data[c] == 0 ? 1 : 0;
    cout << "After error correction: ";
    for (i = (m_size + rbit); i >= 1; i--)
    {
        cout << data[i] << " ";
    }
    cout << endl;

    return 0;
}

 

//dijkstras

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 9


int minDistance(int dist[], bool sptSet[])
{
    int min = INT_MAX, min_index;

    for (int v = 0; v < V; v++)
        if (sptSet[v] == false && dist[v] <= min)
            min = dist[v], min_index = v;

    return min_index;
}


void printSolution(int dist[])
{
    printf("0 is the source node\n");
    printf("Enter the vertex (0-8) till which you have to find the minimum distance from the source: ");
    int v;
    scanf("%d", &v);
    for (int i = 0; i < V; i++)
    {
        if (v == i)
        {
            printf("Distance from source to entered vertex is: %d\n\n", dist[i]);
        }
    }
}

void dijkstra(int graph[V][V], int src)
{
    int dist[V];

    bool sptSet[V];

    for (int i = 0; i < V; i++)
        dist[i] = INT_MAX, sptSet[i] = false;

    dist[src] = 0;

    for (int count = 0; count < V - 1; count++)
    {
        int u = minDistance(dist, sptSet);

        sptSet[u] = true;

        for (int v = 0; v < V; v++)

            if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
                dist[v] = dist[u] + graph[u][v];
    }

    printSolution(dist);
}

int main()
{
    int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0},
                       {4, 0, 8, 0, 0, 0, 0, 11, 0},
                       {0, 8, 0, 7, 0, 4, 0, 0, 2},
                       {0, 0, 7, 0, 9, 14, 0, 0, 0},
                       {0, 0, 0, 9, 0, 10, 0, 0, 0},
                       {0, 0, 4, 14, 10, 0, 2, 0, 0},
                       {0, 0, 0, 0, 0, 2, 0, 1, 6},
                       {8, 11, 0, 0, 0, 0, 1, 0, 7},
                       {0, 0, 2, 0, 0, 0, 6, 7, 0}};

    dijkstra(graph, 0);

    return 0;
}

Friday, 1 July 2022

ADS

 P1: Coffee

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

struct node {
    int custid;
    char n[30];
    int amt;
    struct node* next;
} *head = 0, *temp, *ptr1 = 0, *ptr2 = 0, *new1, *max_id, *min_id;

int main() {
    int ch, id, cost, c = 0, max, min;
    char res, name[30];
    do {
        printf("1.Add\n2.Search by ID\n3.Print Bill\n4.Max and Min Sell\n\nChoose any 1: \t");
        scanf("%d", &ch);
        switch(ch) {
            case 1:
                do {
                    new1 =(struct node*)malloc(sizeof(struct node));
                    printf("\nEnter Customer ID, Name, Purchase Amount: \t");
                    scanf("%d %s %d", &id, &name, &cost);
                    new1->custid = id;
                    strcpy(new1->n, name);
                    new1->amt = cost;
                    new1->next = 0;

                    if(head == 0) {
                        head = new1;
                        c++;
                    } else {
                        temp = head;
                        while(temp->next != 0) {
                            temp = temp->next;
                        }
                        temp->next = new1;
                        c++;
                    }
                    printf("\nDo you want to add more: \t");
                    scanf(" %c", &res);
                } while(res == 'y');
            break;

            case 2:
                printf("\nEnter ID of customer to be searched : \t");
                scanf("%d", &id);
                temp = head;
                while(temp != 0) {
                    if(temp->custid == id) {
                        printf("\n**********************************************************\n");
                        printf("\nCustomer ID\tName\tTotal Purchase");
                        printf("\n%d\t%s\t%d", temp->custid, temp->n, temp->amt);
                        break;
                    } else {
                        temp = temp->next;
                    }
                }
            break;

            case 3:
                temp = head;
                max_id = head; min_id = head;
                int tot_sale = 0;
                printf("\n**********************************************************\n");
                printf("\nC_ID\t\tName\tTotal Purchase");
                while(temp != 0) {
                    printf("\n%d\t|\t%s\t|\t%d", temp->custid, temp->n, temp->amt);
                    tot_sale += temp->amt;
                    temp = temp->next;
                }
                printf("\n\nTotal Sale of the Day is :\t%d", tot_sale);
            break;

            case 4:
                temp = head->next;
                max = head->amt;
                min = head->amt;
                while(temp != 0) {
                    if(temp->amt > max) {
                        max_id = temp;
                        max = temp->amt;
                    }
                    if(temp->amt < min) {
                        min_id = temp;
                        min = temp->amt;
                    }
                    temp = temp->next;
                }
                printf("\nSell Type\tC_ID\t\tName\tTotal Purchase");
                printf("\nMax Sell:\t%d\t|\t%s\t|\t%d", max_id->custid, max_id->n, max_id->amt);
                printf("\nMin Sell:\t%d\t|\t%s\t|\t%d", min_id->custid, min_id->n, min_id->amt);
            break;
        }
        printf("\n\nDo you want to continue: \t");
        scanf(" %c", &res);
    } while(res == 'y');
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P2a: Stack

#include<bits/stdc++.h>
using namespace std;

struct node {
    struct node* prev;
    int val;
    struct node* next;
} *head = 0, *ptr1, *ptr2, *temp, *new1;

int main() {
    int ch, x, c = 0;
    char res;
    do {
        printf("\n1.Push\n2.Pop\n3.Display\nChoose any 1: \t");
        scanf("%d", &ch);
        switch(ch) {
            case 1:
                do {
                    printf("\nEnter value: \t");
                    scanf("%d", &x);
                    new1 = (struct node*)malloc(sizeof(struct node));
                    new1->prev = 0;
                    new1->val = x;
                    new1->next = 0;
                    if(head == 0) {
                        head = new1;
                        c++;
                    } else {
                        temp = head;
                        while(temp->next != 0) {
                            temp = temp->next;
                        }
                        temp->next = new1;
                        new1->prev = temp;
                        c++;
                    }
                    printf("\nDo you want to add more: \t");
                    scanf(" %c", &res);
                } while(res == 'y');
            break;

            case 2:
                temp = head;
                while(temp->next != 0) {
                    temp = temp->next;
                }
                ptr1 = temp;
                temp = temp->prev;
                temp->next = 0;
                free(ptr1);
            break;

            case 3:
                temp = head;
                while(temp->next != 0) {
                    temp = temp->next;
                }
                while(temp != head) {
                    printf("%d\n", temp->val);
                    temp = temp->prev;
                }
                printf("%d\n", head->val);
            break;
        }
        printf("\nDo you want to continue: \t");
        scanf(" %c", &res);
    }while(res == 'y');
}

P2b: Queue


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

// Structure to create a node with data and next pointer
struct node {
int data;
struct node *next;
};

struct node *front = NULL;
struct node *rear = NULL;

// Enqueue() operation on a queue
void enqueue(int value) {
struct node *ptr;
ptr = (struct node *)malloc(sizeof(struct node));
ptr->data = value;
ptr->next = NULL;
if ((front == NULL) && (rear == NULL)) {
front = rear = ptr;
} else {
rear->next = ptr;
rear = ptr;
}
printf("Node is Inserted\n\n");
}

// Dequeue() operation on a queue
int dequeue() {
if (front == NULL) {
printf("\nUnderflow\n");
return -1;
} else {
struct node *temp = front;
int temp_data = front->data;
front = front->next;
free(temp);
return temp_data;
}
}

// Display all elements of queue
void display() {
struct node *temp;
if ((front == NULL) && (rear == NULL)) {
printf("\nQueue is Empty\n");
} else {
printf("The queue is \n");
temp = front;
while (temp) {
printf("%d--->", temp->data);
temp = temp->next;
}
printf("NULL\n\n");
}
}

int main() {
int choice, value;
printf("\nImplementation of Queue using Linked List\n");
while (choice != 4) {
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value);
enqueue(value);
break;
case 2:
printf("Popped element is :%d\n", dequeue());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
return 0;
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P3: Skip List


#include <stdio.h>
#include <stdlib.h>
const int level = 3;
typedef struct Skip_List
{
    int data;
    struct Skip_List *next[3];
} * skl;
skl head = NULL;

skl getNode()
{
    int val;
    printf("Enter The value You want to Insert:-");
    scanf("%d", &val);
    struct Skip_List *newNode = (struct Skip_List *)malloc(sizeof(struct Skip_List));
    newNode->data = val;
    for (int i = 0; i < level; i++)
        newNode->next[i] = NULL;
    return newNode;
}

void DisplyExpress()
{
    struct Skip_List *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next[1];
    }
}
void DisplyExpress2()
{
    struct Skip_List *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next[2];
    }
}
void normalWay()
{
    struct Skip_List *newNode = getNode();
    if (head == NULL)
    {
        head = newNode;
        return;
    }
    struct Skip_List *temp = head;
    int cnt = 1;
    while (temp->next[0] != NULL)
    {
        temp = temp->next[0];
    }
    temp->next[0] = newNode;
}
void expressWay()
{
    skl temp, prev;
    for (int i = 1; i < level; i++)
    {
        int ct = 1;
        temp = head->next[i - 1];
        for (prev = head; temp != NULL; temp = temp->next[i - 1])
        {
            if (ct % level == 0)
            {
                prev->next[i] = temp;
                prev = temp;
            }
            ct++;
        }
    }
}
void Display()
{
    struct Skip_List *temp = head;
    while (temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next[0];
    }
}
void search(int key)
{
    skl prev = head;
    skl temp = head;
    int i = level - 1;
    int found = 0;
    int ct = 0;
    while (found == 0 && i >= 0)
    {

        if (key < head->data || temp == NULL)
        {
            printf("%d Element Not found", key);
            return;
        }
        else if (temp->data == key)
        {
            ct++;
            found = 1;
            printf(" %d Found in %d Iterations", key, ct);
        }
        else if (key > temp->data)
        {
            ct++;
            prev = temp;
            temp = temp->next[i];
            if (temp == NULL)
            {
                i--;
                temp = prev->next[i];
            }
        }
        else if (key < temp->data)
        {
            i--;
            temp = prev->next[i];
            ct++;
        }
        else
        {
            found=0;
        }
    }
    if(found==0)
        printf("Element Not Found!!!\n");
    
    printf("\n");
}
int main()
{
    char ch = 'y';
    do
    {
        normalWay();
        printf("\nWant To insert a Node(y/n):-");
        scanf(" %c", &ch);
    } while (ch == 'y');
    expressWay();
    printf("\n\nNormal Lane:\n");
    Display();
    printf("\n");
    printf("Express Lane 1:\n");
    DisplyExpress();
    printf("\n");
    printf("Express Lane 2:\n");
    DisplyExpress2();
    printf("\n\n");
    do
    {
        int key;
        printf("Enter Element You Want To search:");
        scanf("%d", &key);
        search(key);
        printf("\nWant To search another element ?(y/n):-");
        scanf(" %c", &ch);
    } while (ch == 'y');
    return 0;
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P4: Hashing


#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
struct node
{
  int data;
  struct node *next;
};
struct node *head[10]={NULL},*c;
void insert()
{
  int i,key;
  printf("\n\nEnter a value to be inserted :\n");
  scanf("%d",&key);
  i=key%10;
  struct node * newnode=(struct node *)malloc(sizeof(struct node));
  newnode->data=key;
  newnode->next = NULL;
  if(head[i] == NULL)
     head[i] = newnode;
  else
  {
  c=head[i];
  while(c->next != NULL)
  {
   c=c->next;
  }
  c->next=newnode;
}
}
void search()
{
  int key,index;
  printf("\nEnter the element to be searched:\t");
  scanf("%d",&key);
  index=key%10;
  if(head[index] == NULL)
  printf("\nSearch element not found\n");
  else
  {
  for(c=head[index];c!=NULL;c=c->next)

{
  if(c->data == key)
  {
  printf("\nSearch element found at index %d\n",index);
  break;
  }
}
  if(c==NULL)
  printf("\nSearch element not found\n");
 }
}
void display()
  {
  printf("\n");
  int i;
  for(i=0;i<10;i++)
  {
  if(head[i] == NULL)
  {
  printf("INDEX %d: \t0->", i);
  }
  else
  {
  printf("INDEX %d: \t", i);
  for(c=head[i];c!=NULL;c=c->next)
   printf("%d->",c->data);
  }
  printf("NULL\n\n");
 }


}
int main()
 {
 int ch,key,i;
 while(1)
 {
 printf("\n\n1.Add\n2:Display\n3:Search\n4:Exit");
 printf("\nEnter your choice :\t");
 scanf("%d",&ch);

 switch(ch)
 {
  case 1:
  insert();
  break;
  case 2:
  display();
  break;
  case 3:
  search();
  break;
  case 4:
  exit(0);
  }
 printf("\n*************************************************************");
 printf("\n*************************************************************");
 printf("\n");
 }
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P5: BST


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

struct node
{
    char emp_name[30];
    int emp_sal;
    struct node *right_child;
    struct node *left_child;
};

void Print(struct node *root, int k1, int k2)
{
   if ( NULL == root )
      return;
   if ( k1 < root->emp_sal )
    Print(root->left_child, k1, k2);
   if ( k1 <= root->emp_sal && k2 >= root->emp_sal )
    printf("\n%s\t|\t%d", root->emp_name, root->emp_sal);
   Print(root->right_child, k1, k2);
}

int FindTot(struct node* root) {
    int tot = 0, totLeft = 0, totRight = 0;
    if(root == NULL) {
        printf("Tree is empty\n");
        return 0;
    }
    else {
        if(root->left_child != NULL)
            totLeft = FindTot(root->left_child);

        if(root->right_child != NULL)
              totRight = FindTot(root->right_child);

        tot = root->emp_sal + totLeft + totRight;
        return tot;
   }
}

int FindMax(struct node* root)
{
    struct node* current = root;
    while (current->right_child != NULL)
        current = current->right_child;
    printf("\n%s\t|\t%d", current->emp_name, current->emp_sal);
    return 0;
}

int FindMin(struct node* root)
{
    struct node* current = root;
    while (current->left_child != NULL)
        current = current->left_child;
    printf("\n%s\t|\t%d", current->emp_name, current->emp_sal);
    return 0;
}
/*
struct node* search(struct node *root, int x)
{
    if(root==NULL)
        return 0;
    else if(root->data == x) return root;
    else if(x>root->data)
        return search(root->right_child, x);
    else
        return search(root->left_child,x);
}

struct node* find_minimum(struct node *root)
{
    if(root == NULL)
        return NULL;
    else if(root->left_child != NULL)
        return find_minimum(root->left_child);
    return root;
}
*/
struct node* new_node(char name[], int sal)
{
    struct node *p;
    p = malloc(sizeof(struct node));
    p->emp_sal = sal;
    strcpy(p->emp_name, name);
    p->left_child = NULL;
    p->right_child = NULL;

    return p;
}

struct node* insert(struct node *root, char name[], int sal)
{

    if(root==NULL)
        return new_node(name, sal);
    else if(sal > root->emp_sal)
        root->right_child = insert(root->right_child, name, sal);
    else
        root->left_child = insert(root->left_child, name, sal);
    return root;
}
/*
struct node* delete(struct node *root, int x)
{
    if(root==NULL)
        return NULL;
    if (x>root->data)
        root->right_child = delete(root->right_child, x);
    else if(x<root->data)
        root->left_child = delete(root->left_child, x);
    else
    {
        if(root->left_child==NULL && root->right_child==NULL)
        {
            free(root);
            return NULL;
        }

        else if(root->left_child==NULL || root->right_child==NULL)
        {
            struct node *temp;
            if(root->left_child==NULL)
                temp = root->right_child;
            else
                temp = root->left_child;
            free(root);
            return temp;
        }

        else
        {
            struct node *temp = find_minimum(root->right_child);
            root->data = temp->data;
            root->right_child = delete(root->right_child, temp->data);
        }
    }
    return root;
}
*/
void inorder(struct node *root)
{
    if(root!=NULL)
    {
        inorder(root->left_child);
        printf("\n%s\t|\t%d", root->emp_name, root->emp_sal);
        inorder(root->right_child);
    }
}
void preorder(struct node *root)
{
    if(root!=NULL)
    {
        printf("\n%s\t|\t%d", root->emp_name, root->emp_sal);
        preorder(root->left_child);
        preorder(root->right_child);
    }
}
void postorder(struct node *root)
{
    if(root!=NULL)
    {
        postorder(root->left_child);
        postorder(root->right_child);
        printf("\n%s\t|\t%d", root->emp_name, root->emp_sal);
    }
}
int main()
{
    int m = 0, n = 0;
    struct node *root;
    int ch, cnt = 0, sal;
    char res, name[30];
    do{
        printf("1.Add Employee\n2.Display Database\n3.Employee with Max and Min Salary\n4.Total Monthly Salary Expenditure of Company\n5.Display Salary in Range\n\nChoose any one: \t");
        scanf("%d", &ch);
        switch(ch) {
            case 1:
                do{
                    if(cnt == 0) {
                        printf("\nEnter Employee Name and Salary: \t");
                        scanf("%s %d", &name, &sal);
                        root = new_node(name, sal);
                        cnt++;
                    } else {
                        printf("\nEnter Employee Name and Salary: \t");
                        scanf("%s %d", &name, &sal);
                        insert(root, name, sal);
                    }
                    printf("\nDo you want to add more: \t");
                    scanf(" %c", &res);
                }while(res == 'y');
                printf("\n\n***********************************************************************");
                printf("\n***********************************************************************\n\n");
            break;
            case 2:
                printf("\nPreorder Display: \n");
                printf("\nName\t|\tSalary");
                preorder(root);
                printf("\n\nInorder Display: \n");
                printf("\nName\t|\tSalary");
                inorder(root);
                printf("\n\nPostorder Display: \n");
                printf("\nName\t|\tSalary");
                postorder(root);
                printf("\n\n***********************************************************************");
                printf("\n***********************************************************************\n\n");
            break;
            case 3:
                printf("\nMaximum Salary");
                printf("\nName\t|\tSalary\n");
                FindMax(root);
                printf("\n");
                printf("\nMinimum Salary");
                printf("\nName\t|\tSalary\n");
                FindMin(root);
                printf("\n");
                printf("\n\n***********************************************************************");
                printf("\n***********************************************************************\n\n");
            break;
            case 4:
                printf("\n-----------------------------------------------------------------------");
                printf("\nTotal Monthly Salary: ");
                int mon = FindTot(root);
                printf("%d", mon);
                printf("\n-----------------------------------------------------------------------");
                printf("\n\n***********************************************************************");
                printf("\n***********************************************************************\n\n");
            break;
            case 5:
                printf("\nSpecify Minimum and Maximum Salary: \t");
                scanf("%d %d", &m, &n);
                printf("\nName\t|\tSalary\n");
                Print(root, m, n);
                printf("\n\n***********************************************************************");
                printf("\n***********************************************************************\n\n");
            break;
        }
        printf("\nDo you want to continue: \t");
        scanf(" %c", &res);

    }while(res == 'y');
    return 0;
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P6a: Trie

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


#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define ALPHABET_SIZE (26)
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')
#define MAX 100

struct TrieNode
{
struct TrieNode *children[ALPHABET_SIZE];
bool isEndOfWord;
};

struct TrieNode *getNode(void)
{
struct TrieNode *pNode = NULL;

pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

if (pNode)
{
int i;

pNode->isEndOfWord = false;

for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
void insert(struct TrieNode *root, const char *key)
{
int level;
int length = strlen(key);
int index;

struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();

pCrawl = pCrawl->children[index];
}

pCrawl->isEndOfWord = true;
}
void display(struct TrieNode* root, char *str, int level)
{
struct TrieNode *pCrawl = root;
if (pCrawl->isEndOfWord == true)
{
str[level] = '\0';
printf("%s\t",str);
}

int i;
for (i = 0; i < ALPHABET_SIZE; i++)
{
if (pCrawl->children[i])
{
str[level] = i + 'a';
display(pCrawl->children[i], str, level + 1);
}
}
}
bool search(struct TrieNode *root, const char *key)
{
int level;
int length = strlen(key);
int index;
struct TrieNode *pCrawl = root;

for (level = 0; level < length; level++)
{
index = CHAR_TO_INDEX(key[level]);

if (!pCrawl->children[index])
return false;

pCrawl = pCrawl->children[index];
}

return (pCrawl->isEndOfWord);
}

int main()
{
    struct TrieNode *root = getNode();
    FILE *fptr = NULL;
    int i = 0;
    char word[MAX] = {0};
    char searchword[MAX];
    char res;
    

    fptr = fopen("input.txt", "r");
    while(fscanf(fptr, "%100s\n", word)!=EOF){
        insert(root, &word[i]);
    }
    fclose(fptr);


//Display
int level = 0;
    char str[20];
printf("Content of Trie:\n");
display(root, str, level);

char output[][32] = {"Not present in trie", "Present in trie"};

    do
    {
        printf("\nEnter Word to Search: ");
        scanf("%s",searchword);
        printf("%s --- %s\n", searchword, output[search(root, searchword)] );
        printf("\nDo you want to search more: ");
    scanf(" %c", &res);
    } while (res=='y');

return 0;
}

P6b: Trie

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define N 26
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

typedef struct TrieNode
{
struct TrieNode *children[N];
int flag;
}*Tr;

Tr getNode(void)
{
Tr newnode = NULL;

newnode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

if (newnode)
{
int i;

newnode->flag = 0;

for (i = 0; i < N; i++)
newnode->children[i] = NULL;
}

return newnode;
}

void insert(Tr root, const char *word)
{
int i;
int length = strlen(word);
int index;

struct TrieNode *temp = root;

for (i = 0; i < length; i++)
{
index = CHAR_TO_INDEX(word[i]);
if (!temp->children[index])
temp->children[index] = getNode();

temp = temp->children[index];
}

temp->flag = 1;
}

int search(Tr root, char *word)
{
int i;
int length = strlen(word);
int index;
struct TrieNode *temp =root;

for (i = 0; i< length; i++)
{
index = CHAR_TO_INDEX(word[i]);

if (!temp->children[index])
return 0;

temp = temp->children[index];
}

return (temp->flag);
}

int main()
{
char word[][15] = {"and","bat","ball","book","cot","cotton","internet","interview","joy","job","king","lion","man","mango","mango"};

char output[][32] = {"Not present in trie", "Present in trie"};

char word1[][15] = {0};


struct TrieNode *root = getNode();

// Construct trie
FILE* fp;

    printf("\nHow many words you have to search: \t");
    int n;
    scanf("%d", &n);
    char word2[30];

int i;

for (i = 0; i < ARRAY_SIZE(word); i++)
insert(root, word[i]);

// Search for different keys
printf("-----------------------------------\n");
printf("-----------------------------------\n");
// fp = fopen("Trie.txt", "r");
// int j=0;
// while (fscanf(fp, "%s/t", word1) == 1)
// {
for(int i=0;i < n; i++)
{
            printf("Enter the word: \t");
            scanf("%s", word2);
        printf("\nPresent\t\t\tNot Present\n");
    //printf("%d",(search(root, word1[i])));
    if((search(root, word2)) == 1) {
                printf("%d) %s\t\t\n", i, word2);
    } else printf("%d)\t\t\t%s\n", i, word2);
//printf("%s --- %s\n\n", word1[i],output[search(root, word1[i])] );
            printf("\n");
}
return 0;
}

P6c: Trie

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
#define N 26
#define CHAR_TO_INDEX(c) ((int)c - (int)'a')

typedef struct TrieNode
{
struct TrieNode *children[N];
int flag;
}*Tr;

Tr getNode(void)
{
Tr newnode = NULL;

newnode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

if (newnode)
{
int i;

newnode->flag = 0;

for (i = 0; i < N; i++)
newnode->children[i] = NULL;
}

return newnode;
}

void insert(Tr root, const char *word)
{
int i;
int length = strlen(word);
int index;

struct TrieNode *temp = root;

for (i = 0; i < length; i++)
{
index = CHAR_TO_INDEX(word[i]);
if (!temp->children[index])
temp->children[index] = getNode();

temp = temp->children[index];
}

temp->flag = 1;
}

int search(Tr root, char *word)
{
int i;
int length = strlen(word);
int index;
struct TrieNode *temp =root;

for (i = 0; i< length; i++)
{
index = CHAR_TO_INDEX(word[i]);

if (!temp->children[index])
return 0;

temp = temp->children[index];
}

return (temp->flag);
}

int main()
{
char word[][15] = {"and","bat","ball","book","cot","cotton","internet","interview","joy","job","king","lion","man","mango","mango"};

char output[][32] = {"Not present in trie", "Present in trie"};

char word1[][15] = {0};


struct TrieNode *root = getNode();

// Construct trie
FILE* fp;


int i;

for (i = 0; i < ARRAY_SIZE(word); i++)
insert(root, word[i]);

// Search for different keys
printf("Present\t\t|\tNot Present\n");
printf("-----------------------------------\n");
printf("-----------------------------------\n");
fp = fopen("Trie.txt", "r");
int j=0;
while (fscanf(fp, "%s/t", word1) == 1)
{
for(int i=0;i < ARRAY_SIZE(word1); i++)
{
    //printf("%d",(search(root, word1[i])));
    if((search(root, word1[i])) == 1) {
                printf("%d) %s\t\t|\n", j+1, word1[i]);
    } else printf("%d)\t\t|\t%s\n", j+1, word1[i]);
//printf("%s --- %s\n\n", word1[i],output[search(root, word1[i])] );
}
j++;

}


return 0;
}


---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P7: Network Failure

#include<stdio.h>
#include<stdlib.h>
int min(int a,int b)
{
    return(a<b?a:b);
}
struct node
{
 int val;
 struct node* next;
};
struct graph
{  
 int v;
 struct node** arr;
};
struct graph* createGraph(int v)
{
    int i;
    struct graph* temp =(struct graph*)malloc(sizeof(struct graph));
    temp->v=v;
    for(i=0;i<v;i++)
     temp->arr=(int*)malloc(sizeof(int*)*v);
    for(i=0;i<v;i++)
     temp->arr[i]=NULL;
    return temp;
}
void addEdge(struct graph* g,int u,int v)
{
    struct node* temp =(struct node*)malloc(sizeof(struct node));
    temp->val = v;
    temp->next = g->arr[u];
    g->arr[u] = temp;    
}
void apUtil(struct graph * g,int node,int* isVisited,int* des,int* parent,int* low,int* ap)
{
    struct node* temp=NULL;
    static int time=0;
    int children=0;
    temp = g->arr[node];
    isVisited[node]=1;
    time++;
    //printf("\nsetting time for %d",node);
    des[node]=low[node]=time;

    while(temp!=NULL)
    {      
       if(!isVisited[temp->val])
        {
          children++;
          parent[temp->val]=node;
          apUtil(g,temp->val,isVisited,des,parent,low,ap);

      low[node]= min(low[node],low[temp->val]);

          if(parent[node]==-1 && children>1)
             ap[node]=1;

      if(parent[node]!=-1 && des[node]<=low[temp->val])
            ap[node]=1;          
        }    
        else if(temp->val!=parent[node])
        {
            low[node]=min(low[node],des[temp->val]);
        }
       temp= temp->next;
      }
     //printf("%d",node);
}
void AP(struct graph* g)
{
    int i;
    int* des = (int*)malloc(sizeof(int)*g->v);
    int* isVisited = (int*)malloc(sizeof(int)*g->v);
    int* parent = (int*)malloc(sizeof(int)*g->v);
    int* low = (int*)malloc(sizeof(int)*g->v);
    int* ap = (int*)malloc(sizeof(int)*g->v);
    for(i=0;i<g->v;i++)
    {
        isVisited[i]=0;
        parent[i]=-1;
        ap[i]=0;
    }
    for(i=0;i<g->v;i++)
    {
        if(isVisited[i]==0)
        {
            apUtil(g,i,isVisited,des,parent,low,ap);
        }
    }
    printf("\n");
    int flag=0;
    printf("\nPoint of failure in a Network");
    for(i=0;i<g->v;i++)
    {
       
        if(ap[i]==1)
 {
   flag=1;
   printf("\nVertex : %d",i);
 }
    }
    if(flag==0)
 printf("\nNo point found.");
}
int main()
{
   
    int size=0,edges=0,i,u,v;
    struct graph* g = createGraph(5);
    addEdge(g, 1, 0);
    addEdge(g, 0, 2);
    addEdge(g, 2, 1);
    addEdge(g, 0, 3);
    addEdge(g, 3, 4);
   
    AP(g);
}

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

P8a: Graph

#include<bits/stdc++.h>
using namespace std;

class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // to add an edge to graph
bool isCyclic(); // returns true if there is a cycle in this graph
};

Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}

void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}

// This function is a variation of DFSUtil() in https://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack)
{
if(visited[v] == false)
{
// Mark the current node as visited and part of recursion stack
visited[v] = true;
recStack[v] = true;

// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i)
{
if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) )
return true;
else if (recStack[*i])
return true;
}

}
recStack[v] = false; // remove the vertex from recursion stack
return false;
}

// Returns true if the graph contains a cycle, else false.
// This function is a variation of DFS() in https://www.geeksforgeeks.org/archives/18212
bool Graph::isCyclic()
{
// Mark all the vertices as not visited and not part of recursion
// stack
bool *visited = new bool[V];
bool *recStack = new bool[V];
for(int i = 0; i < V; i++)
{
visited[i] = false;
recStack[i] = false;
}

// Call the recursive helper function to detect cycle in different
// DFS trees
for(int i = 0; i < V; i++)
if ( !visited[i] && isCyclicUtil(i, visited, recStack))
return true;

return false;
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);

FILE *fptr;
int vrt;
int wt;
fptr = fopen("nfile.txt", "r");

while(fscanf(fptr, "%d    %d", &vrt, &wt)!=EOF)
    {
        g.addEdge(vrt, wt);
    }
fclose(fptr);



if(g.isCyclic())
cout << "Graph contains cycle";
else
cout << "Graph doesn't contain cycle";
return 0;
}

P8b: Cycle

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

#define MAX 100
#define initial 1
#define visited 2
#define finished 3

void CreateGraph();
void DFS(int v);
void DFSTraversal();

int num;
int state[MAX];
int matrix[MAX][MAX];

void DFSTraversal()
{
        int v;
        for(v=0;v<num;v++)
        {
                state[v]=1;
        }
        //Our Root Vertex Is 0
        DFS(0);
        for(v=0;v<num;v++)
        {
                if(state[v]==1)
                {
                        DFS(v);
                }
        }
        printf("Graph Is Acyclic\n");
}

void DFS(int v)
{
        int i;
        state[v]=2;
        for(i=0;i<num;i++)
        {
                if(matrix[v][i]==1)
                {
                        if(state[i]==1)
                        {
                                DFS(i);
                        }
                        else if(state[i]==2)
                        {
                                printf("Back Edge From %d To %d Found!\n",v,i);
                                printf("Graph Is Cyclic\n");
                                exit(1);
                        }
                }
        }
        state[v]=3;
}

void CreateGraph()
{
        int maxedges;
        int origin;
        int destin;
        int i=0;
        printf("Enter The Number Of Vertices: ");
        scanf("%d",&num);
        maxedges=num*(num-1);
        for(i=1;i<=maxedges;i++)
        {
                printf("Enter %d Edge(-1 -1 To Quit): ",i);
                scanf("%d %d",&origin,&destin);
                if((origin==-1) && (destin==-1))
                {
                        break;
                }
                if(origin>=num || destin>=num || origin<0 || destin<0)
                {
                        printf("Invalid Edge!\n");
                        i--;
                }
                else
                {
                        matrix[origin][destin]=1;
                }
        }
}

int main()
{
        CreateGraph();
        DFSTraversal();
        return 0;
}

P8c: Cycle from matrix

#include<iostream>
#include<set>
#define NODE 3
using namespace std;

/*
    {0, 1, 0, 0, 0},
   {0, 0, 0, 0, 0},
   {1, 0, 0, 1, 0},
   {0, 0, 0, 0, 1},
   {0, 0, 1, 0, 0}
*/

int graph[NODE][NODE] = {
   {0,1,0},
   {0,0,1},
   {1,0,0}
};

bool dfs(int curr, set<int>&wSet, set<int>&gSet, set<int>&bSet) {
   //moving curr to white set to grey set.
   wSet.erase(wSet.find(curr));
   gSet.insert(curr);

   for(int v = 0; v < NODE; v++) {
      if(graph[curr][v] != 0) {    //for all neighbour vertices
         if(bSet.find(v) != bSet.end())
            continue;    //if the vertices are in the black set
         if(gSet.find(v) != gSet.end())
            return true;    //it is a cycle
         if(dfs(v, wSet, gSet, bSet))
            return true;    //cycle found
      }
   }

   //moving v to grey set to black set.
   gSet.erase(gSet.find(curr));
   bSet.insert(curr);
   return false;
}

bool hasCycle() {
   set<int> wSet, gSet, bSet;    //three set as white, grey and black
   for(int i = 0; i<NODE; i++)
      wSet.insert(i);    //initially add all node into the white set

   while(wSet.size() > 0) {
      for(int current = 0; current < NODE; current++) {
         if(wSet.find(current) != wSet.end())
            if(dfs(current, wSet, gSet, bSet))
               return true;
      }
   }
   return false;
}

int main() {
   bool res;
   res = hasCycle();
   if(res)
      cout << "The graph has cycle" << endl;
   else
      cout << "The graph has no cycle" << endl;
}


Thursday, 30 June 2022

MFDA

P1: DataFrame

Student_ID <- c()

for(i in 1001:1010) {

+ Student_ID <- append(Student_ID, i)

+ }

Student_ID


Name <- c("jim", "jacy", "ben", "lexi", "john", "suzan", "lee", "emma", "drax", "alice")

Name


Marks <- c(23,34,54,35,65,34,76,45,87,88)

Marks


 Gender <- c("male", "female", "male", "female", "male", "female", "male", "female", "male", "female")

Gender


stringAsFactors = FALSE


df <- data.frame(Student_ID, Name, Marks, Gender)

df


str(df)
summary(df)

extra <- c(1011, "jazz", 44, "male")
df[nrow(df) + 1,] <- extra
df

data.frame(df$Student_ID, df$Marks)


-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------

P2: Import Export

install.packages("writexl")
library("writexl")

Student_ID <- c()

for(i in 1001:1010) {

+ Student_ID <- append(Student_ID, i)

+ }

Name <- c("jim", "jacy", "ben", "lexi", "john", "suzan", "lee", "emma", "drax", "alice")

Marks <- c(23,34,54,35,65,34,76,45,87,88)

Gender <- c("male", "female", "male", "female", "male", "female", "male", "female", "male", "female")

stringAsFactors = FALSE

df <- data.frame(Student_ID, Name, Marks, Gender)


write.csv(df, file = "D:/University/Sem 4/MFDA/PR/pr2_try1.csv")

write.table(df, file = "D:/University/Sem 4/MFDA/PR/pr2_try2.txt")


df_read1 <- read.csv("D:/University/Sem 4/MFDA/PR/pr2_try1.csv")

df_read2 <- read.table(file = "D:/University/Sem 4/MFDA/PR/pr2_try2.txt")

-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------

P3: Central Tendencies

mean(mtcars$cyl)
mean(mtcars$mpg)
mean(mtcars$gear)
mean(mtcars$disp)

mode<-function(x){which.max(tabulate(x))}
mode(mtcars$cyl)

median(mtcars$cyl)

var(mtcars$cyl)

sd(mtcars$cyl)

boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data")

png(file = "C:/Users/HP/Documents/MFDATrash/line_chart1.jpg")
plot(mtcars$cyl, type = "o", xlab = "Index", ylab = "Cylinders", main = "Cylinders in mtcars DataSet")
dev.off()

png(file = "C:/Users/HP/Documents/MFDATrash/dotplot1.jpg")
dotchart(mtcars$cyl, labels = rownames(mtcars))
dev.off()

hist(mtcars$mpg, xlab = "Miles Per Gallon", ylab = "Number of Cars", main = "Cars Distribution")
hist(mtcars$cyl, xlab = "Cylinders", main = "Histogram for Cylinder in mtcars")

barplot(mtcars$cyl, xlab = "Cars", ylab = "Cylinders", main = "Barplot: Cars and Number of cyl")

barplot (table(mtcars$cyl), main = "Car Distribution", xlab = "Number of Cylinders", col = c("darkblue", "green", "red"), names.arg = c("4 Cylinder", "6 Cylinder", "8 Cylinder"))

pie(table (mtcars$cyl), labels = c("4 Cylinder", "6 Cylinder", "8 Cylinder"), main="Car Distribution")

plot(x = input$cyl, y = input$mpg, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Scatterplot: Cylinders vs MPG")

-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------

P4: Advanced Visual

sapply(mtcars, function(mtcars) max(mtcars, na.rm = TRUE) - min(mtcars, na.rm = TRUE))

order(mtcars$mpg)
sort(mtcars$mpg)
IQR(mtcars$mpg)

quantile(mtcars$wt, probs = c(0,0.25,0.5,0.75,1))

quantile(mtcars$wt, probs = c(.75, .8))

boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders", ylab = "Miles Per Gallon", main = "Mileage Data")

a) 8 cylinders are needed for lowest milage per gallon

b) Prediction with 6 number of cylinders gives maximum confidence


-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

P5: Prob Dis

x = 0:5
barplot(height = dbinom(x,5,0.4), names.arg = c(0,1,2,3,4,5), xlab = "Number of Late Arrivals", ylab = "Probability", main = "Problem 1")

x = 0:5
barplot(dbinom(x,5,0.1))
barplot(dbinom(x,5,0.3))
When prob is lower, i.e. 0.1: the data is right skewed. When prob increases, the data becomes left skewed. At 0.9, the data is left skewed.ype = "o") / barplot(dpois(x, 3))

x = 1:20
barplot(dbinom(x,20,0.4))

Keeping p = 0.4, and increasing n, the data follows normal distribution.
x <- c(0:4)
dpois(x, 5)

ppois(7, 5, lower.tail = TRUE)
ppois(7, 5, lower.tail = FALSE)
ppois(8,5)-ppois(4,5)

x <- c(1:50)
plot(x, dpois(x, 3), type = "o") / barplot(dpois(x, 3))

-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

P6: Case Study of Prob Dis

x <- seq(0, 50, by = 1)
y <- dnorm(x, mean = 25.0, sd = 10)
plot(x,y, main = "Normal Distribution", col = "blue")

pnorm(27.5, mean = 22, sd = 29) - pnorm(16.2, mean = 22, sd = 29)

cat("The probability is less than 17: ", pnorm(17, mean = 22, sd = 29))

pnorm(17, mean = 22, sd = 29)

pnorm(15, mean = 22, sd = 29) + (1 - pnorm(25, mean = 22, sd = 29))

pnorm(850000, mean = 1000000, sd = 200000)


-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

P7: Algebra Op and Dist Met

install.packages("pracma")

 

a <- c(1,2,3)

b <- c(5,6,7)

dot(a,b)

cross(a,b)

 

d = matrix(c(1,2,3), nrow=3, ncol=3, byrow=TRUE)

e = matrix(c(4,5,6), nrow=3, ncol=3, byrow=TRUE)

cross(d, e)

 

f = matrix(c(1,2,3), nrow=1, ncol=3, byrow=TRUE)

f

t(f)

 

install.packages("geometry")

install.packages("philentropy")

library(geometry)

library(philentropy)

 

x <- c(50,5,2)

y <- c(1,8,9)

p <- rbind(x,y)

distance(p, method = "euclidean")

distance(p, method = "manhattan")

distance(p, method = "jaccard")

print('Hamming Distance')

sum(x != y)

 

d = matrix(c(0.68567, 0.12975, -0.71626, 0.14807, 0.93855, 0.31176, 0.71269, -0.31982, 0.62433), nrow=3, ncol=3, byrow=TRUE)

det(d)

 

install.packages("matlib")

library(matlib)

 

e = matrix(c(13, -4, 2, -4, 11, -2, 2, -2, 8), nrow=3, ncol=3, byrow=TRUE)

ev <- eigen(e)

(values <- ev$values)

(vectors <- ev$vectors)

 

sum(e^2)

sum(values^2)

 

det(e)

prod(values)

 

R(e)

sum(values != 0)

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


P8: Sampling Dis Techniques

#define number of samples

n = 10000

 

#create empty vector of length n

sample_means = rep(NA, n)

 

#fill empty vector with means

for(i in 1:n){

  sample_means[i] = mean(rnorm(20, mean=5.3, sd=9))

}

 

#view first six sample means

head(sample_means) [o/p: [1] 4.304143 6.058354 7.803126 4.667816 4.379790 8.193655]

 

#create histogram to visualize the sampling distribution

hist(sample_means, main = "", xlab = "Sample Means", col = "steelblue")

 

#mean of sampling distribution

mean(sample_means)

 

#standard deviation of sampling distribution

sd(sample_means)

 

#calculate probability that sample mean is less than or equal to 6

sum(sample_means <= 6) / length(sample_means)


-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

P9: Estimated Value

install.packages(“MASS”)

library(MASS)

height.survey = survey$Height

mean(height.survey, na.rn = TRUE)

height.response = na.omit(survey$Height)

n = length(height.response)

s = sd(height.response)

SE = s/sqrt(n)

SE

E = qt(.975, df = n-1)*SE

xbar = mean(height.response)

xbar + c(-E, E)


-----------------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------------

P10: Hypothesis

 

xbar = 9900

mu0 = 10000

sigma = 120

n = 30

z = (xbar - mu0) / (sigma/sqrt(n))

z

alpha = 0.05

z.alpha = qnorm(1-alpha)

-z.alpha (reject)

 

xbar = 2.1

mu0 = 2

sigma = 0.25

n = 35

z = (xbar - mu0) / (sigma/sqrt(n))

z

alpha = .05

z.alpha = qnorm(1-alpha)

z.alpha (reject)