Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Monday, June 8, 2015

Integer In Words Conversion

The problem is given a number (upto a certain range) we need to convert the number in words.

Example:

  1. 999 -> Nine Hundred Ninety-Nine
  2. 4 -> Four
  3. 0 -> Zero
  4. -230 -> Minus Two Hundred Thirty.
  5. 40 -> Forty

C Implementation

#include <stdio.h>

void print(int arr[], int n)
{
    int m, i;
    char *unit[] = {"","One","Two","Three","Four","Five","Six",
                    "Seven","Eight","Nine"};
    char *ten[] = {"","Ten","Twenty","Thirty","Forty",
                    "Fifty","Sixty","Seventy","Eighty","Ninety"};
    char *hundred[] = {"Ten","Eleven","Twelve","Thirteen","Fourteen",
                    "Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
    
    for(i = 0; i < 5; i++) {
        if(i != 3) {
            if(arr[i]) {
                if((arr[i]%10) != 0) {
                    if(arr[i] < 10)
                        printf("%s ",unit[arr[i]]);
                    else if(arr[i] <= 19)
                        printf("%s ",hundred[arr[i]%10]);
                    else
                        printf("%s-%s ",ten[arr[i]/10],unit[arr[i]%10]);
                }
                else
                    printf("%s ",ten[arr[i]/10]);
                switch(i) {
                case 0: printf("Coror ");break;
                case 1: printf("Lakh ");break;
                case 2: printf("Thousand ");
                }
            }
        }
        else if(arr[3]) {
            printf("%s ",unit[(arr[i])]);
            printf("Hundred ");
        }
    }
    printf("\b.");
}

void divide(long int temp)
{
    int arr[10], i;
    long int div = 10000000;
    for(i = 0; i < 5; i++) {
        arr[i] = temp/div;
        temp = temp%div;
        if(i == 2) div /= 10;
        else div /= 100;
    }
    print(arr, 10);
}

int main(void)
{
    int i,j;
    long int num,temp;

    printf("Enter A Number(9-dig): ");
    scanf("%lld",&num);
    
    temp = (num < 0)? (-1 * num) : num;

    printf("In Words: ");
    if(num < 0) {
        printf("Minus ");
        divide(temp);
    }
    else if(num == 0) {
        printf("Zero.");
    }
    else {
        divide(temp);
    }
    return 0;
}



Enter A Number(9-dig): 3
In Words: Three.

Enter A Number(9-dig): 120
In Words: One Hundred Twenty.

Enter A Number(9-dig): 0
In Words: Zero.

Enter A Number(9-dig): -120
In Words: Minus One Hundred Twenty.

Enter A Number(9-dig): 99999
In Words: Ninety-Nine Thousand Nine Hundred Ninety-Nine.

Enter A Number(9-dig): 999999
In Words: Nine Lakh Ninety-Nine Thousand Nine Hundred Ninety-Nine.

Enter A Number(9-dig): 9999999
In Words: Ninety-Nine Lakh Ninety-Nine Thousand Nine Hundred Ninety-Nine.

Enter A Number(9-dig): 002
In Words: Two.

Binary Insertion Sort

We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search.

C Implementation

// Binary Insertion Sort
#include <stdio.h>
 
// A binary search based function to find the position
// where item should be inserted in a[low..high]
int binarySearch(int a[], int item, int low, int high)
{
    if (high <= low)
        return (item > a[low])?  (low + 1): low;
 
    int mid = (low + high)/2;
 
    if(item == a[mid])
        return mid+1;
 
    if(item > a[mid])
        return binarySearch(a, item, mid+1, high);
    return binarySearch(a, item, low, mid-1);
}
 
// Function to sort an array a[] of size 'n'
void insertionSort(int a[], int n)
{
    int i, loc, j, k, selected;
 
    for (i = 1; i < n; ++i)
    {
        j = i - 1;
        selected = a[i];
 
        // find location where selected should be inserted..
        loc = binarySearch(a, selected, 0, j);
 
        // Move all elements after location to create space..
        while (j >= loc)
        {
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = selected;
    }
}
 
int main()
{
    int a[] = {37, 23, 0, 17, 12, 72, 31,
              46, 100, 88, 54};
    int n = sizeof(a)/sizeof(a[0]), i;
 
    insertionSort(a, n);
 
    printf("Sorted array: \n");
    for (i = 0; i < n; i++)
        printf("%d ",a[i]);
 
    return 0;
}

Output

Sorted array:
0 12 17 23 31 37 46 54 72 88 100

Thursday, April 23, 2015

Bresenham's Line Drawing Python Implementation

Bresenham's line drawing algorithm for drawing a line in a computer screen by using integer arithmetic operations only. It is more efficient that the older DDA Line drawing algorithm that uses floating-point arithmetic and rounding operations although it can be optimised to perform only integer operations still pixle selection using Besenham's gives better result than DDA.

Python3 implementation of the algorithm is given below using graphics module by John M.Zelle


from graphics import *
import time

def BresenhamLine(x1,y1,x2,y2):
    """ Bresenham Line Drawing Algorithm For All Kind Of Slopes Of Line """
   
    dx = abs(x2 - x1)
    dy = abs(y2 - y1)
    slope = dy/float(dx)
    
    x, y = x1, y1   

    # creating the window
    win = GraphWin('Brasenham Line', 600, 480)
    
    # checking the slope if slope > 1 
    # then interchange the role of x and y
    if slope > 1:
        dx, dy = dy, dx
        x, y = y, x
        x1, y1 = y1, x1
        x2, y2 = y2, x2

    # initialization of the inital disision parameter
    p = 2 * dy - dx
    
    PutPixle(win, x, y)

    for k in range(2, dx):
        if p > 0:
            y = y + 1 if y < y2 else y - 1
            p = p + 2*(dy - dx)
        else:
            p = p + 2*dy

        x = x + 1 if x < x2 else x - 1
        
        # delay for 0.01 secs
        time.sleep(0.01)
        PutPixle(win, x, y)

def PutPixle(win, x, y):
    """ Plot A Pixle In The Windows At Point (x, y) """
    pt = Point(x,y)
    pt.draw(win)

def main():
    x1 = int(input("Enter Start X: "))
    y1 = int(input("Enter Start Y: "))
    x2 = int(input("Enter End X: "))
    y2 = int(input("Enter End Y: "))

    BresenhamLine(x1, y1, x2, y2)
        
if __name__ == "__main__":
    main()


Output For (50,60) to (300,400)

Tuesday, March 24, 2015

C Program To Delete All Single Line and Multiline Comment From A C File

The problem is to delete all comment lines from a C or C++ or any other programming languages that uses comment like single line comment ( // )  and multi-line comment (/**/).

The program given below will delete all the comment line in a file. If the code is not working properly please comment below in the comment section. If someone have some better approach also comment below.

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

void refine(const char line[]) 
{
    char *sl = "//", *ml = "/*", *ptSingleLine, *ptMultiLine;
    ptSingleLine = strstr(line, sl);
    if ( ptSingleLine ) {
        *ptSingleLine = '\0';
    }   
    ptMultiLine = strstr(line, ml);
    if ( ptMultiLine ) {
        *ptMultiLine = '\0';
    }
}


int findComment(const char *line) 
{
    char *singleLine = "//", *multiLine = "/*" ;
    
    if ( strstr(line, singleLine) || strstr(line, multiLine)) {
        return 1;
    }
    else {
        return 0;
    }
}

int main()
{
    int found;
    FILE *fin, *fout;
    char ch, line[200], fname[100], temp[50];
    
    printf("Enter The Name Of The File: ");
    fflush(stdin);
    gets(temp);
    
    getcwd(fname, 99);
    
    strcat(fname, "/");
    strcat(fname, temp);

    fin = fopen(fname, "r");
    fout = fopen("new.c", "w");
    
    if ( fin == NULL ) {
        printf("\nFile %s Not Found.", fname);
    }
    else {  
        while ( fgets(line,  100, fin) != NULL )
        {
            found = findComment(line);
            if( found == 1 ) {
                refine(line);
                fprintf(fout, "%s", line);
            }
            else {
                fprintf(fout, "%s", line);
            }
        }
        printf("\nDone Copying To 'new.c' W/O Comment Lines.");
        fclose(fin);
        fclose(fout);
    }
    return 0;
}

Friday, March 13, 2015

Operator Overloading In C++

C++ allows us to specify more than one definition for a function or an operator this property is known as function overloading and operator overloading.

Operator overloading lets us define the meaning of an operator when applied to operand(s) of a class type. Well use of operator overloading can make our
programs easier to write and easier to read.

By operator overloading we can't define a new operator i.e.. we can't use ** and define it to find power. 

Here is a program in which some arithmetic operators are overloaded for Complex Number class.

#include <iostream>
using namespace std;

class Complex
{
    float real, imag;
    
    public:
        Complex(float r = 0, float i = 0) : real(r), imag(i) {}
        
        friend ostream& operator<<(ostream&, const Complex&);
        friend istream& operator>>(istream&, Complex&);

        friend Complex operator+(const Complex&, const Complex&);
        Complex operator+(const Complex&);
        
        friend Complex operator-(const Complex&, const Complex&);
        Complex operator-(const Complex&);

        friend Complex operator*(const Complex&, const Complex&);
        Complex operator*(const Complex&);

        friend Complex operator/(const Complex&, const Complex&);
        Complex operator/(const Complex&);

        class DivideByZero {};
};

Complex operator*(const Complex& lhs, const Complex& rhs)
{   
    Complex result;
    cout << "Friend * Function Is Called." << endl;
    result.real = (lhs.real * rhs.real) - (lhs.imag * rhs.imag);
    result.imag = (lhs.real * rhs.imag) + (lhs.imag * rhs.real);

    return result;
}

Complex Complex::operator*(const Complex& rhs)
{
   Complex result;
   cout << "Member * Function Is Called." << endl;
   result.real = (real * rhs.real) - (imag * rhs.imag);
   result.imag = (real * rhs.imag) + (imag * rhs.real);

   return result;
}

Complex operator/(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend / Function Is Called." << endl;
    float tmp = (lhs.imag * lhs.imag) + (rhs.real * rhs.real);
    
    if (tmp == 0.0) {
        throw Complex::DivideByZero();
    }

    result.real = ((lhs.real * rhs.real) + (lhs.imag * rhs.imag)) / tmp;
    result.imag = ((lhs.imag * rhs.real) - (lhs.real * rhs.imag)) / tmp;    
 
    return result;
}

Complex Complex::operator/(const Complex& rhs)
{
    Complex result;
    cout << "Member / Function Is Called." << endl;
    float tmp = (imag * imag) + (rhs.real * rhs.real);
    
    if (tmp == 0.0) {
        throw Complex::DivideByZero();
    }

    result.real = ((real * rhs.real) + (imag * rhs.imag)) / tmp;
    result.imag = ((imag * rhs.real) - (real * rhs.imag)) / tmp;    
 
    return result;
}

Complex operator+(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend + Function Is Called." << endl;
    result.real = lhs.real + rhs.real;
    result.imag = lhs.imag + rhs.imag;

    return result;
}

Complex Complex::operator+(const Complex& rhs)
{
    Complex result;
    cout << "Member + Function Is Called." << endl;   
    result.real = real + rhs.real;
    result.imag = imag + rhs.imag;
    
    return result;
}

Complex operator-(const Complex& lhs, const Complex& rhs)
{
    Complex result;
    cout << "Friend - Function Is Called." << endl;
    result.real = lhs.real - rhs.real;
    result.imag = lhs.imag - rhs.imag;

    return result;
}

Complex Complex::operator-(const Complex& rhs)
{
    Complex result;
    cout << "Member - Function Is Called." << endl;   
    result.real = real - rhs.real;
    result.imag = imag - rhs.imag;
    
    return result;
}

ostream& operator<<(ostream& out, const Complex& rhs)
{
    out << "(" <>(istream& in, Complex& rhs)
{
    in >> rhs.real >> rhs.imag;
    return in;
}

int main()
{
    float r, i;

    cout << "---Arithmetic Operations---" << endl;

    cout << "Enter The First Complex Number: " << endl;
    cout << "Enter Real Part: " << endl; 
    cin >> r;
    cout << "Enter Imaginary Part: " << endl;
    cin >> i;
    Complex c1(r, i);

    cout << "Enter The Second Complex Number: " << endl;
    cout << "Enter Real Part: " << endl;
    cin >> r;
    cout << "Enter Imaginary Part: " << endl;
    cin >> i;
    Complex c2(r, i);

    cout << "The Result Is Of c1 + c2: " << c1 + c2 << endl;
    cout << "The Result Is Of c1 - c2: " << c1 - c2 << endl;
    cout << "The Result Is Of c1 * c2: " << c1 * c2 << endl;
    
    try {
        cout << "The Result Is Of c1 + c2:" << c1 / c2 << endl;
    }
    catch (Complex::DivideByZero) {
        cout << "Exception: Can't Divide By Zero." << endl;
        return -1;
    }
    
    cout << "---Automatic Type Conversion Testing---" << endl;
    
    Complex c3(2,5);
    cout << "Addition Of c3 + 2: " << c3 + 2 << endl;
    cout << "Multiplication Of c3 * 0: " << c3 * 0.0 << endl;

    return 0;
}


---Arithmetic Operations---
Enter The First Complex Number:
Enter Real Part:
2
Enter Imaginary Part:
3
Enter The Second Complex Number:
Enter Real Part:
4
Enter Imaginary Part:
5
Member + Function Is Called.
The Result Is Of c1 + c2: (6) + (8i)
Member - Function Is Called.
The Result Is Of c1 - c2: (-2) + (-2i)
Member * Function Is Called.
The Result Is Of c1 * c2: (-7) + (22i)
Member / Function Is Called.
The Result Is Of c1 + c2:(0.92) + (0.08i)
---Automatic Type Conversion Testing---
Member + Function Is Called.
Addition Of c3 + 2: (4) + (5i)
Member * Function Is Called.
Multiplication Of c3 * 0: (0) + (0i)

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

Tuesday, March 3, 2015

C++ Linked List Implementation Using Template

Templates in C++ is a tool for generic programming. In general we want to make program that is independent of input type (integer, real, strings etc.).

Here we want to create a List class that in generic in nature and works or all sort of input type like strings , integers, float, double, chars etc.

#include <iostream>
#include <string>
using namespace std;

template <class T> class List;

template <class T>
class Node
{
    friend class List<T>;
    T val;
    Node<T> *link; 
    public:
        Node() {}
        Node(T v) : val(v), link(NULL) {}
        Node(T v, Node<T> *p) : val(v), link(p) {}
};

template <class T>
class List
{
    int size;
    Node<T> *head;
    public:
        List() : size(0) {
            head = new Node<T>();
        }
        void append(T);
        void prepend(T);
        void insertAt(T, int);
        void show() const;
        inline int len() { return size; }
};

template <class T>
void List<T>::append(T item)
{
    Node<T> *pivot = new Node<T>(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node<T> *temp = head;
        while (temp->link != NULL) {
            temp = temp->link; 
        }
        temp->link = pivot;
    }
    size++;
}

template <class T>
void List<T>::insertAt(T item, int pos)
{
    Node<T> *pivot = new Node<T>(item);

    if (pos <= size+1 && pos > 0) {
        int i = 0;
        Node<T> *temp = head, *prev;
        while (i != pos) {
            ++i;
            prev = temp;
            temp = temp->link;
        }
        pivot->link = temp;
        prev->link = pivot;
        size++;
    }
    else {
        cerr << "Invalid Position '" << pos << "' Sprecified." << endl;
    }
}

template <class T>
void List<T>::prepend(T item)
{
    Node<T> *pivot = new Node<T>(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node<T> *temp = head->link;
        head->link = pivot;
        pivot->link = temp;
    }
    size++;
}

template <class T>
void List<T>::show() const
{
    Node<T> *tmp = head->link;
    cout << "[";
    while (tmp != NULL) {
        cout << tmp->val << "," << ends;
        tmp = tmp->link;
    }
    cout << "\b\b]" << endl;
}

int main()
{
    List<int> a;
    
    a.append(2);
    a.append(3);
    a.prepend(1);
    a.append(5);
    a.show();
    a.insertAt(-1, 0);
    a.insertAt(4, 4);
    a.insertAt(6, 6);
    a.show();
    cout << "Length Of The List Of Integers: " << a.len() << endl;
    
    List<string> b;
    
    b.append("Cat");
    b.append("Dog");
    b.append("Mouse");
    b.append("Bird");
    b.show();
    cout << "Length Of The List Of Strings: "<< b.len() << endl;
    
    return 0;   
}


[1, 2, 3, 5]
Invalid Position '0' Sprecified.
[1, 2, 3, 4, 5, 6]
Length Of The List Of Integers: 6
[Cat, Dog, Mouse, Bird]
Length Of The List Of Strings: 4

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

Sunday, March 1, 2015

Linked List Implementation In C++ Using Friend Class

Linked List is one of the most common data structures available. In C++ we already have List in STL but in this program we will implement out own link list class using friend class.



#include <iostream>
using namespace std;

class Node
{
    friend class List;
    int val;
    Node *link; 
    public:
        Node() {
            val = 0;
            link = NULL;
        }
        Node(int v) {
            val = v;
            link = NULL;
        }
        Node(int v, Node *p) {
            val = v;
            link = p;
        }
};

class List
{
    int size;
    Node *head;
    public:
        List() {
            head = new Node();
            size = 0;
        }
        void append(int);
        void show() const;
        inline int len() {
            return size;
        }
};

void List::append(int item)
{
    Node *pivot = new Node(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node *temp = head;
        while (temp->link != NULL) {
            temp = temp->link; 
        }
        temp->link = pivot;
    }
    size++;
}

void List::show() const
{
    Node *tmp = head->link;
    cout << "[";
    while (tmp != NULL) {
        cout << tmp->val << "," << ends;
        tmp = tmp->link;
    }
    cout << "\b\b]" << endl;
}

int main()
{
    List a;
    
    a.append(1);
    a.append(2);
    a.append(3);
    a.append(4);
    a.show();
    
    a.append(5);
    a.append(6);
    a.append(7);
    a.show();
    
    cout << "Length Of The List: "<< a.len() << endl;
    
    return 0;   
}
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
Length Of The List: 7

--------------------------------
Process exited after 0.3124 seconds with return value 0
Press any key to continue . . .