Wednesday, June 29, 2016

C++ Exception Handling

Exception handling in C++ helps to prevent the unexpected problems which can happen while executing the program and if there is any error like invalid data, out of bound, overflow or any other
exceptional circumstances so that rest of the program and system in general does not get screwed up.

It mainly involves the idea:
1) Hit the exception at problem code.
2) Throw the exception
3) Catch/Receive the error info
4) handle the error or exception

Above steps gets wrapped under different block using keywords like try - to wrap the code where an exception needs to be detected & thrown.
catch - receives the exception  via exception object and handle the error.
finally -  {Not present in C++} block of code needs to be executed even if exception occurred on try block exit, used mostly to put clean up code , C++ can put those code in deconstructor.


sample code:


submitted solution from hackerrank

#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;

//Write your code here
class myException : public std::exception {
  virtual const char *what() const throw() {
    return "n and p should be non-negative";
  }
};

class Calculator {
   public:
    int power(int n, int p) {
        int result = 1;
        if(n <0 || p < 0)
            throw myException();
        for(int i=0; i<p;i++)
            result*=n;
        return result;
    }
};

int main()
{
    Calculator myCalculator=Calculator();
    int T,n,p;
    cin>>T;
    while(T-->0){
      if(scanf("%d %d",&n,&p)==2){
         try{
               int ans=myCalculator.power(n,p);
               cout<<ans<<endl;
         }
         catch(exception& e){
             cout<<e.what()<<endl;
         }
      }
    }   
}





Friday, May 27, 2016

C++ solved inheritance problem from hackerrank

C++ solved inheritance problem from hackerrank:

#include <iostream>
#include <vector>

using namespace std;


class Person{
    protected:
        string firstName;
        string lastName;
        int id;
    public:
        Person(string firstName, string lastName, int identification){
            this->firstName = firstName;
            this->lastName = lastName;
            this->id = identification;
        }
        void printPerson(){
            cout<< "Name: "<< lastName << ", "<< firstName <<"\nID: "<< id << "\n";
        }
   
};

class Student :  public Person{
    private:
        vector<int> testScores; 
    public:
          // Write your constructor
        Student(string firstName, string lastName, int identification, vector<int> scores): Person(firstName, lastName, identification), testScores(scores) {
        }
          // Write char calculate()
        char calculate() {
            int sum = 0;
            int count = 0;
            vector<int>::iterator it;
            for(it = testScores.begin(); it != testScores.end(); ++it) {
                sum+= *it;
                count++;
            }
            int avg = sum/count;
            if (90 <= avg && avg <=100)
                return 'O';
            else if(80<= avg && avg < 90)
                return 'E';
            else if(70<= avg && avg < 80)
                return 'A';
            else if(55<= avg && avg < 70)
                return 'P';
            else if(40 <= avg && avg < 55)
                return 'D';
             else
                return 'T';
        }
};

int main() {
    string firstName;
      string lastName;
    int id;
      int numScores;
    cin >> firstName >> lastName >> id >> numScores;
      vector<int> scores;
      for(int i = 0; i < numScores; i++){
          int tmpScore;
          cin >> tmpScore;
        scores.push_back(tmpScore);
    }
    Student* s = new Student(firstName, lastName, id, scores);
    s->printPerson();
    cout << "Grade: " << s->calculate() << "\n";
    return 0;
}

Sunday, May 8, 2016

progrom for converting time from 12 hr format to 24 hr format


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    char* time = (char *)malloc(10240 * sizeof(char));
    scanf("%s",time);
    int count = 0;
   
    int hh = (time[0] - '0') * 10 + (time[1] - '0');
    for(int i=0;i < 10240;i++) {
        if ((time[i] == 'P' || time[i] == 'p') && (time[i+1] == 'M' || time[i+1] =='m')) {
            if (hh > 11) break;
            if (hh == 24 )
                hh = 0;
            else
                hh+=12;
            break;
        }
        if ((time[i] == 'A'  || time[i+1] =='a') && (time[i+1] == 'M' || time[i+1] =='m')) {
            if (hh > 11) hh = 0;
            break;
        }
        if (time[i] == '\0') {
            break;
        }
        count++;
    }

    time[0] = hh/10 + '0';
    time[1] = hh%10 + '0';

    char* newTime = (char*) malloc(count* sizeof (char));
    strncpy(newTime, time, count);
        printf("%s", newTime);
    return 0;
}

Saturday, May 7, 2016

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void exchange(int *a, int* b) {
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
int partition (int* arr, int si, int ei) {
    int x = arr[ei];
    int i = si-1;
    int j;
    for (j = si; j < ei; j++) {
        if (arr[j] <= x) {
            i++;
            exchange(&arr[j], &arr[i]);
        }
    }
    exchange (&arr[i+1], &arr[ei]);
    return i+1;
}
void quickSort (int* arr, int si, int ei) {
    int pi;
    if (si < ei) {
        pi = partition(arr, si, ei);
        quickSort(arr, si, pi -1);
        quickSort(arr, pi+1, ei);
    }
}
int* twoSum(int* nums, int numsSize, int target) {
      int start = 0, end = numsSize-1, sum,a, b;
      int *temp = malloc(numsSize*sizeof(int));
      int k;
      for (k=0; k <= end; k++) {
          temp[k] = nums[k];
      }
     
      int* index = malloc(2*sizeof(int));
     
      quickSort(temp, start, end);
      int l;
      while (start < end) {
          sum = temp[start] + temp[end];
          if (sum == target) {
              a = temp[start];
              b = temp[end];
              break;
          } else if (sum > target)
            end--;
          else
            start++;
      }
      int z, y;
     
      for(z = 0; z < numsSize; z++) {
          if (nums[z] == a) {
             
              break;
          }
      }
      for (y = 0; y < numsSize; y++) {
          if(nums[y] == b && y!=z) {
             
              break;
          }
      }
      if (z < y) {
          index[0] = z;
          index[1] = y;
      }else {
          index[0] = y;
          index[1] = z;
      }

     
      return index;
}

Wednesday, January 13, 2016

Heap Introduction

Heap :

A Heap is a binary tree where all the leaves are either present at depth d or d-1 same as complete binary tree.
for every node n, the value in n is greater than or equal to the values in its children, thus also greater or equal
to all of the values in its subtrees.

Conditions for Heap: 
1) All leaves are either at depth d or d-1 for same d value
2) All of the leaves at depth d-1 are to the right of the leaves at d depth.
3) There is at most 1 node with just 1 child, that child is the left of its parent and it is the rightmost leaf at depth d.

examples  from http://pages.cs.wisc.edu/~vernon/cs367/notes/11.PRIORITY-Q.html





Saturday, October 31, 2015

Linked List rearrangement Example 1

/* re-arrange nodes in the LL inplace as below
head : 1->2->3->4->5
output: 1->5->2->4->3
 */

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
    int num;
    struct Node *next;
} Node;

Node *newNode(int num)
{
    Node *temp = (Node*) malloc(sizeof(Node));
    temp->num = num;
    temp->next = NULL;
    return temp;
}

void reverse (Node** head)
{
    Node *prev = NULL,  *cur = *head, *next;
    while(cur) {
    next = cur->next;
    cur->next = prev;
    prev = cur;
    cur = next;
    }
    *head = prev;
}

void reArrangeNodes( Node** head)
{
    Node *slow = *head;
    Node *fast = slow->next;
    // find the mid point
    while (fast && fast->next) {
    slow = slow->next;
    fast = fast->next->next;
    }
    Node *head1 = *head;
    Node *head2 = slow->next;
    slow->next = NULL;

    reverse(&head2);
    *head = newNode(0);
    Node* cur = *head;
    while(head1 || head2) {
    if (head1) {
        cur->next = head1;
        cur = cur->next;
        head1 = head1->next;
    }

    if (head2) {
        cur->next = head2;
        cur = cur->next;
        head2 = head2->next;
    }
    }
    *head = (*head)->next;
}
int main()
{
    Node *head = newNode(1);
    head->next = newNode(2);
    head->next->next = newNode(3);
    head->next->next->next = newNode(4);
    head->next->next->next->next = newNode(5);
    head->next->next->next->next->next = newNode(6);
    head->next->next->next->next->next = newNode(7);
    printf("Input: ");
    Node *temp = head;
    while(temp) {
    printf ("%d ", temp->num);
    temp = temp->next;
    }
    printf("\n");
    reArrangeNodes(&head);
    printf("output: ");
    while(head) {
    printf("%d ", head->num);
    head=head->next;
    }
    printf("\n");
    return 0;
}

compare two string represented as Linked List similar to strcmp

/* compare two string represented as LL similar to strcmp */

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
  char c;
  struct Node *next;
}Node;

Node* newNode(char c)
{
  Node *temp = (Node*) malloc (sizeof(Node));
  temp->c = c;
  temp->next = NULL;
  return temp;
};

int compare( Node *list1, Node *list2)
{
  while (list1 && list2 && (list1->c == list2->c))
      {
        list1 = list1->next;
        list2 = list2->next;
      }

   if (list1 && list2)
      return (list1->c >  list2->c) ? 1 : -1;

   if (list1 && !list2)
      return 1;
   if (!list1 && list2)
       return -1;
   return 0;
}

int main()
{
  Node *list1 = newNode('p');
  list1->next = newNode('e');
  list1->next->next = newNode('a');
  list1->next->next->next = newNode('c');

  Node *list2 = newNode('p');
  list2->next = newNode('e');
  list2->next->next = newNode('a');
  list2->next->next->next = newNode('c');
  list2->next->next->next->next = newNode('e');
  printf("compare result %d\n", compare(list1, list2));
  return 0;
}