Thursday, 8 June 2017

pointer arithmetic of an Array and passing a 2D array to a function

Before moving further let's see how a one-dimensional array is stored in a computer memory.
For example, let an array:
                         A = [   3   ][   4   ][   5   ][   6   ][   7   ]      -> value stored in an integer array
                                 200    204     208    212     216         -> these are the address of the memory of the array. As it is an integer array each element has a storage of 4 bytes.

To declare a pointer to a one-dimensional array we simply write:

    int *ptr = A; 
this pointer ptr points to the starting block of the array A. Also, the name of the array i.e A just returns a pointer to the first element of the array.
With the pointer declared we can use pointer arithmetic and dereferencing to access the address and elements of the array.
for example,

print ptr  will give output = 200

print *ptr will give output = 3, i.e the value stored at that memory location (this is called as                                                                                                                                           dereferencing )
print *(ptr +2)  will give us the output 5  as ptr is a pointer to an integer so increasing ptr two times will enhance it to further 8 bytes.

print (ptr +2)  = 208

The language flexibility allows us to use the name of the array as a pointer. Therefore instead of using ptr we can directly use A.
i.e ,

print A = 200
print *A = 3
print *(A+2) = 5
print A+2 = 208

in short,
*(A+i) is same as A[i]
and (A+i) is same as &A[i]

Therefore, ptr = A  but A != ptr .

we can pass a one-dimensional array  in a function as follows:

void myfunction (int *arr)
{
       int n = arr.size();
       cout<<arr[i];
}

int main()
{
   int arr = {1,2,3,4,5,6};
   myfunction(arr);
}

We can do the same thing in a multi-dimensional array. What does it mean when we say multi-dimensional array? A multi-dimensional array is an array of array.
 Let's talk about the two-dimensional array:

Suppose we have a 2-D array:
 B[2][3] = [  [ 2 , 3, 6 ] , [ 4 , 5  ,8  ] ]
                     400             412            -> memory address of the arrays.
Now each element  B[0] and B[1] is an array of integers consisting of three integers each. Hence each block would have a size of 3*4 bytes i.e 12 bytes. Therefore B[0] contains the starting address of the first array  i.e 400  and B[1] contains the starting address of the second array i.e 412.

if we  write,
int *ptr = B ; this will return an error because ptr is a pointer to integer but B is a pointer to a 1-D array of integers.
We can define a pointer to 1-D array of three integers like this:
int (*ptr)[3] = B ;

print B  is same as print (B+0)  and from the above-given statement in 1-D array, (B+i) = &B[i]
 Therefore print B = print  &B[0]  = 400 .

Similarly,
print *B is same as print B[0]  which is equal to a variable name of an array as B[0] is itself a 1-D array, therefore, B[0] will act as a pointer to the address of  first  element of the array B[0] i.e &B[0][0] which is equal to 400.  

Now the output of
print B+1 = &B[1] which is equal to 412 .

print *(B+1) is same as print B[1] which is equal to a variable name of an array as B[1] is itself a   1-D array, therefore, B[1] will act as a pointer to the address of  first  element of the array B[1] i.e &B[1][0] which is equal to 412.

print *(B+1) + 2 = 420. As *(B+1) is a pointer to an integer containing the address of B[1][0] and if we do pointer arithmetic this will occur in terms of bytes. Therefore B[1] + 2 will give the address of B[1][2].

print *(*B + 1) = 3 . As *B returns a pointer to the first integer of the array B[0] and adding 1 to it will take it to the address of B[0][1] which is equal to the value of &B[0][1] again dereferencing it will give the value stored at B[0][1] which is equal to 3.

For 2-D array,
B[i][j] = *(B[i] + j) = *(*(B+i) + j) 

Now passing  a two-dimensional array into a function:

There are several ways of passing a multidimensional array within a function.

1. one of the ways is to use tempelate :

tempelate<int R,int  C>
void myfunc( int (&array)[R][C])
{
     // do stuff
}

2. Another way of doing this is by using simple arithmetic with passing the address of first block :

void myfunc(int n, int m ,int *arr)    // n rows and m columns 
{
    for(i=0;i<n;i++)
     {
           for(j=0;j<m;j++)
           {
               cout<<*((arr+i*n) + j)        // is same as arr[i][j]
           }
     }
}

int main()
{
     // doing stuffs like declaring an array and initializing it
     //calling the function :->
      myfunc(n,m,(int*)arr);
     

}

Update(8/04/2018):
I was using this approach today for a question where I have to manipulate or say modify the contents of the array by using the above-mentioned method of passing the 2d array. Somehow I ended up with segmentation fault every time. Finally, after debugging my code, I realized that the error was in the indexing i.e instead of using "i" I was using "j". So whats the intention of this post? Actually, while I was facing the segmentation fault, I found another method of passing a 2D array to a function after declaring the array dynamically and this is approach is much simpler.




int edit_distance(int **arr,int n,int m,char *source,char *target)
{
   int i=0,j=0,k;
   
    arr[i][j] = 0; // See you can use the arr[i][j] indexing rather than using the pointer arithmetic
   
   for(j=1;j<=m;j++)
   {
      //cout<<"here"<<endl;
        arr[i][j] = j;
       cout<< arr[i][j];
   }
   j = 0;
   for(i=1;i<=n;i++)
   {
        arr[i][j] = i;
   }
   return 3;

}

int main() {
int t;
cin>>t;
while(t--)
{
    int n,m;
    cin>>n>>m;
    char source[n],target[m];
    cin>>source,target;
    int **arr;
    arr = new int*[n+1];
    for(int i =0;i<=n;i++)
    {
    arr[i] = new int[m+1];
    }
    int ans;
    ans = edit_distance(arr,n,m,source,target);
    
    cout<<ans<<endl;
}
return 0;

}










Sunday, 9 April 2017

Divide and Conquer - 1.Karatsuba Algorithm for Multiplication

Hello friends, In this post and following some next posts I would be writing about Divide and Conquer approach of solving problems and famous algorithms which use this approach .
In this post post I am explaining the famous Karatsuba Algorithm for multiplication of number in O(n^1.586) time complexity.

Lets talk about what we actually do when we multiply two numbers. As per I believe, most of us use the basic method of multiplication which has a time complexity of O(n^2).


Something similar to this: 
The above shown multiplication is the simplest basic method for multiplication. But suppose you have to multiply :
3141592653589793238462643383279502884197169399375105820974944592
with 
 2718281828459045235360287471352662497757247093699959574966967627 .

Obviously, If you would go for the basic multiplication method for solving this, it would be a tedious job. That's where the Karatsuba multiplication method comes into play.

In this method we apply the basic principle of divide and conquer i.e divide this multiplication process into smaller sub-process for smaller parts of the number. Suppose we have to multiply 965107 by 102635, both of them are 6-digit numbers i.e a 6 by 6 multiplication.
we can write :
965107 * 102635  = (965000 + 107 ) * (102000 + 635)
                              = (965 * 10^3 + 107  ) * (102 * 10^3 + 635 )
                              = 965 * 102 * 10^6 + 107*635 + 10^3*(965*635 + 102*107) 
 We have reduced one 6 by 6 multilication method into four 3 by 3 multiplication .

The same approach is used in  Karatsuba algorithm :
suppose we have to multiply two n-digit numbers X and Y.
For simplicity assume n is even (where n is the number of digits in X and Y ):

X =  Xl*10^n/2 + Xr    [Xl and Xr contain leftmost and rightmost n/2 bits of X]
Y =  Yl*10^n/2 + Yr    [Yl and Yr contain leftmost and rightmost n/2 bits of Y]

The product of X and Y can be written as :
XY = (Xl*10^n/2 + Xr)(Yl*10^n/2 + Yr)
   = 10^n XlYl + 10^n/2(XlYr + XrYl) + XrYr
Also, XlYr + XrYl = (Xl + Xr)(Yl + Yr) - XlYl- XrYr

So the final result becomes : XY = 10^n XlYl + 10^n/2 * [(Xl + Xr)(Yl + Yr) - XlYl - XrYr] + XrYr
As we need to multiply such large numbers, we store the input in strings and then manipulate them according to our need.
What if the length of two given numbers is not same? In that case we append zeros in front of the numbers which are stored as integers. In case n is odd, we put floor(n/2) bits in left half and ceil(n/2) bits in right half.
The beauty of Karatsuba method is that you can use it for multiplication of numbers of any base ,2,10,16 etc.

The below given code is for multiplication of base 10 numbers. Read it carefully, don't just cram the code :


#include <iostream>
#include <algorithm>
#include <string.h>
#include<stdio.h>


const int MAX_LENGTH = 50000 * 2 + 1;

void add_leading_zeros(char* a, int n) {
  int lena = strlen(a);
  for (int i = lena - 1 + n; i >= n; --i) {
    a[i] = a[i - n];
  }
  a[lena + n] = 0;
  for (int i = 0; i < n; ++i) {
    a[i] = '0';
  }
}

void remove_leading_zeros(char* a) {
  int lena = strlen(a);
  int ind = 0;
  while (ind < lena && a[ind] == '0') {
    ++ind;
  }

  for (int i = ind; i < lena; ++i) {
    a[i - ind] = a[i];
  }
  a[lena - ind] = 0;
}

void sum(char* a, char* b, char* res) {
  int lena = strlen(a);
  int lenb = strlen(b);

  if (lena < lenb) {
    std::swap(a, b);
    std::swap(lena, lenb);
  }

  int toAdd = 0;
  for (int inda = lena - 1, indb = lenb - 1; inda >= 0; --inda, --indb) {
    int x = a[inda] - '0';
    int y = indb >= 0 ? b[indb] - '0' : 0;

    int cur = x + y + toAdd;

    if (cur >= 10) {
      toAdd = 1;
      cur -= 10;
    } else {
      toAdd = 0;
    }

    res[inda] = cur + '0';
  }

  if (toAdd == 1) {
    add_leading_zeros(res, 1);
    res[0] = '1';
  }
}

// assume that a > b
void sub(char* a, char* b, char* res) {
  int lena = strlen(a);
  int lenb = strlen(b);

  //assert(lena >= lenb);

  int toSub = 0;
  for (int inda = lena - 1, indb = lenb - 1; inda >= 0; --inda, --indb) {
    int x = a[inda] - '0';
    int y = indb >= 0 ? b[indb] - '0' : 0;

    if (toSub == 1) {
      x--;
    }
    int cur;
    if (x < y) {
      cur = x + 10 - y;
      toSub = 1;
    } else {
      cur = x - y;
      toSub = 0;
    }

    res[inda] = cur + '0';
  }
}

// returns a * 10^n
void mult10(char* a, int n) {
  int lena = strlen(a);

  if (lena == 1 && a[0] == '0') {
    return;
  }

  for (int i = lena; i < lena + n; ++i) {
    a[i] = '0';
  }
  a[lena + n] = 0;
}

char* CreateArray(int len) {
  char* res = new char[len];
  memset(res, 0, len);
  return res;
}

// add leading zeros if needed
void make_equal_length(char* a, char* b) {
  int lena = strlen(a);
  int lenb = strlen(b);

  int n = std::max(lena, lenb);

  add_leading_zeros(a, n - lena);
  add_leading_zeros(b, n - lenb);
}

void karatsuba(char* x, char* y, char* res) {
  make_equal_length(x, y);

  int len = strlen(x);
  if (len == 1) {
    int val = (x[0] - '0') * (y[0] - '0');
    if (val < 10) {
      res[0] = val + '0';
    } else {
      res[0] = (val / 10) + '0';
      res[1] = (val % 10) + '0';
    }
  } else {
    char* xl = CreateArray(len);
    char* xr = CreateArray(len);
    char* yl = CreateArray(len);
    char* yr = CreateArray(len);

    int rightSize = len / 2;
    int leftSize = len - rightSize;

    strncpy(xl, x, leftSize);
    strcpy(xr, x + leftSize);
    strncpy(yl, y, leftSize);
    strcpy(yr, y + leftSize);

    int maxl = 3 * len;
    char* P1 = CreateArray(maxl);
    char* P2 = CreateArray(maxl);
    char* P3 = CreateArray(maxl);

    karatsuba(xl, yl, P1);
    karatsuba(xr, yr, P2);

    char* tmp1 = CreateArray(maxl);
    char* tmp2 = CreateArray(maxl);

    sum(xl, xr, tmp1);
    sum(yl, yr, tmp2);
    karatsuba(tmp1, tmp2, P3);

    sub(P3, P1, P3);
    sub(P3, P2, P3);
    mult10(P3, rightSize);

    mult10(P1, 2 * rightSize);

    sum(P1, P2, res);
    sum(res, P3, res);

    remove_leading_zeros(res);

    delete[] xl;
    delete[] xr;
    delete[] yl;
    delete[] yr;
    delete[] tmp1;
    delete[] tmp2;
    delete[] P1;
    delete[] P2;
    delete[] P3;
  }
}

int main() {
  char a[MAX_LENGTH], b[MAX_LENGTH];
  scanf("%s\n%s", a, b);

  char* res = CreateArray(MAX_LENGTH);
  karatsuba(a, b, res);

  printf("%s\n", res);

  

  return 0;
}


The answer for multiplication of : 
3141592653589793238462643383279502884197169399375105820974944592
with 
 2718281828459045235360287471352662497757247093699959574966967627
 is :
8539734222673567065463550869546574495034888535765114961879601127067743044893204848617875072216249073013374895871952806582723184

Check the answer using your code. 
Thank you 














Sunday, 5 March 2017

Finding K-th smallest Number In O(n) using Randomized partition methhod

Hello Guys, In this post I will be talking about an efficient way for finding Kth smallest Number in a given list of numbers. There are several methods for finding this number.
One such method is, by first sorting the array an then just access the K-th number. This will cost you O(n log(n)) time complexity.(I won't be talking about the brute force method which is approximately of order O(n*n) )
Another method is using the Divide And conquers paradigm. The key step in this method is using O(n) Partition method as we use in Quick Sort.
What do we basically do in this partitioning method??:->

We  have  a function Randomized_partition(A,start,end);
1. First, choose any random index of the given array to choose it as a pivot element around which partition is to be done.
2. Once the partition function works it places the pivot element in the correct position . i.e the elements greater than the pivot element are towards the right of it and the elements smaller than pivot element is towards the left of the pivot element.
3.We note down the index of the pivot element let it is p.  Now we have three cases left with us :
    a.) p = k-1 (that pivot index is equal to the kth smallest number index )  return this number.
    b.)  p <k-1, the desired answer is in the right partition.
    c.) p> k-1, the desired answer is in the left partition.

We keep on repeating this process until we get the  required  answer


Friday, 17 February 2017

Implementation of Queue of string

#include<stdio.h>
#include<iostream>
#include<string>
#include<string.h>
#include<malloc.h>
using namespace std;  
struct Queue
{
    int front, rear, size;
    int  capacity;
    string * array;
};

// function to create a queue of given capacity. It initializes size of
// queue as 0
struct Queue* createQueue(int capacity)
{
    struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
    queue->capacity = capacity;
    queue->front = queue->size = 0;
    queue->rear = capacity - 1;  // This is important, see the enqueue
    queue->array = (string *) malloc(queue->capacity * sizeof(string));
    return queue;
}

// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{  return (queue->size == queue->capacity);  }

// Queue is empty when size is 0
int isEmpty(struct Queue* queue)
{  return (queue->size == 0); }

// Function to add an item to the queue.  It changes rear and size
void enqueue(struct Queue* queue, string item)
{
    if (isFull(queue))
        return;
    queue->rear = (queue->rear + 1)%queue->capacity;
    queue->array[queue->rear] = item;
    queue->size = queue->size + 1;
    cout<<"enqueued to queue  "<<item<<endl;
}

// Function to remove an item from queue.  It changes front and size
string dequeue(struct Queue* queue)
{
    if (isEmpty(queue))
         {cout<<"no";}
    string item = queue->array[queue->front];
    queue->front = (queue->front + 1)%queue->capacity;
    queue->size = queue->size - 1;
    return item;
}

// Function to get front of queue
string front(struct Queue* queue)
{
    if (isEmpty(queue))
       {cout<<"no";}
    return queue->array[queue->front];
}

// Function to get rear of queue
string rear(struct Queue* queue)
{
    if (isEmpty(queue))
         {cout<<"no";}
    return queue->array[queue->rear];
}


int main()
{
    struct Queue* queue = createQueue(1000);

    enqueue(queue, "abc");
    enqueue(queue, "egf");
    enqueue(queue, "hsaj");
    enqueue(queue, "hua");

    cout<<" dequeued from queue "<<dequeue(queue)<<endl;

   cout<<"Front item is "<<front(queue)<<endl;
    cout<<"Rear item is "<<rear(queue)<<endl;

    return 0;
}