Showing posts with label Adobe. Show all posts
Showing posts with label Adobe. Show all posts

Wednesday, July 30, 2014

Union and Intersection of two sorted arrays

Problem

Find  Union and Intersection of two sorted arrays

Example

For example, if the input arrays are:
arr1[] = {1, 3, 4, 5, 7}
arr2[] = {2, 3, 5, 6}
Then your program should print Union as {1, 2, 3, 4, 5, 6, 7} and Intersection as {3, 5}.


Solution

Algorithm Union(arr1[], arr2[]):
For union of two arrays, follow the following merge procedure.
1) Use two index variables i and j, initial values i = 0, j = 0
2) If arr1[i] is smaller than arr2[j] then print arr1[i] and increment i.
3) If arr1[i] is greater than arr2[j] then print arr2[j] and increment j.
4) If both are same then print any of them and increment both i and j.
5) Print remaining elements of the larger array.
#include<stdio.h>
#include<stdio.h>
int printUnion(int arr1[], int arr2[], int m, int n)
{
  int i = 0, j = 0;
  while(i < m && j < n)
  {
    if(arr1[i] < arr2[j])
      printf(" %d ", arr1[i++]);
    else if(arr2[j] < arr1[i])
      printf(" %d ", arr2[j++]);
    else
    {
      printf(" %d ", arr2[j++]);
      i++;
    }
  }
 
  // Print remaining elements of the larger array
  while(i < m)
   printf(" %d ", arr1[i++]);
  while(j < n)
   printf(" %d ", arr2[j++]);
}

Time Complexity: O(m+n)
Algorithm Intersection(arr1[], arr2[]):
For Intersection of two arrays, print the element only if the element is present in both arrays.
1) Use two index variables i and j, initial values i = 0, j = 0
2) If arr1[i] is smaller than arr2[j] then increment i.
3) If arr1[i] is greater than arr2[j] then increment j.
4) If both are same then print any of them and increment both i and j.
#include<stdio.h>
int printIntersection(int arr1[], int arr2[], int m, int n)
{
  int i = 0, j = 0;
  while(i < m && j < n)
  {
    if(arr1[i] < arr2[j])
      i++;
    else if(arr2[j] < arr1[i])
      j++;
    else // if arr1[i] == arr2[j]
    {
      printf(" %d ", arr2[j++]);
      i++;
    }
  }
}

Time Complexity: O(m+n)

References

Tuesday, May 6, 2014

How many time function gets called?

Problem

Consider the function below:
void foo1()
{
  if(A < B)
    Then { }
  else
   if(C < D)
     then foo2()

}

How many time foo2 () would get called given A < B 25% of the times and C < D 75% of the times and foo1 () is called 5000 times 

Solution
This is the question of basic probability. As foo2() occurs in 2nd branch of if else, the probability of it being called is .75 or 75%. But C < D only 75% chance of this 75% chance.

So total probability = .75 * .75 =  .5625
So number of times = 5000 * 5625 = 2812.5

Friday, April 11, 2014

Create the REV function from Swap

We have a function REV(“string”,m,n).This function is capable of reversing the caharacters in the string from mth location to nth location. e.g. REV(“abcd”,2,3); the output will be acbd We need to swap a string from a position,e.g. SWAP(“abcdefg”,4)  output needs to be efgabcd.
How can the REV function used do this.

Solution
 ANS : L = string length,N= position given in SWAP function.
SWAP(“abcdefg”,4) = REV(REV(REV(“abcdefg”,N+1,L),1,N),1,L).

Is there multiply function in 8085 microprocessor


There is no multiplication instruction in the 8085 - I believe that was added in the 8086 & 8088 version of the series.

This has the entire instruction set for the 8085:

These operations are equivilent to multiplying by 2:

1) Shift left by 1 (shifting left by n is multiplying by 2^n)
2) Add the value to itself once.

Other than that you can write a loop to add the number to itself 'n' times.


Or, if you don't need to generalize you can use the following algorithm:

to multiply an 8 bit value (x) by 3:

.....0 x7 x6 x5 x4 x3 x2 x1 x0 --- (x * 1)
+ x7 x6 x5 x4 x3 x2 x1 x0 0 ---- (x * 2) (x << 1)
--------------------------------------...

to multiply by 5:

.....0...0 x7 x6 x5 x4 x3 x2 x1 x0 ---- (x * 1)
+ x7 x6 x5 x4 x3 x2 x1 x0...0...0 ---- (x * 4) (x << 2)
--------------------------------------...


The "."s are just to get the spacing right

Here is a site with a general bit serial algorithm:



Ooops, I didn't realize there wasn't a shift instruction either.

You can use RAL (rotate left with carry). That will rotate the high order bit to the carry flag and the carry flag to the low order bit. If you need to have the result be greater than 8 bits, you can use the carry flag to shift the bit values into another byte.

If I remember right, the 8085 is a 8 bit processor.
This is how you would shift an 8 bit value, yielding a 16 bit result:

STC
CMC
LDA [a]
RAL
STA [a]
LDA [a+1]
RAL
STA [a+1]

I'm actually more familiar with the 8088/6 and later processors. After looking at the instruction set in more detail, I believe the RAL will not only rotate the high order bit throuh the carry flag, but also rotate the carry flag to the low order bit. That's why you need to clear the carry flag before starting. Since there is no clear carry instruction, the way I did it above was to set the carry flag, then compliment it. Also, it doesn't appear that the RAL instruction allows you to rotate more than one bit at a time.

References
https://in.answers.yahoo.com/question/index?qid=20060917112827AAuPoOe

Friday, April 4, 2014

Find all the words of Length N which are produced by natural order

http://www.careercup.com/question?id=4949947124285440

Friday, March 21, 2014

Set all bits of a number in a range equal to another number

This updated information has been further expanded upon on my new website. You can find the updated details here: https://k5kc.com/cs/algorithms/set-all-bits-of-a-number-in-a-range-equal-to-another-number/.
Problem
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).

Example 
Consider the integer N, where we want to fit in M between bits i and j of N.

Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100

i=2 j = 6 1000 | ----- | 00 

               6       2   
Bits count start from left to right, starting with index 0.

Solution

Method 1
  • Set the bits being modified to 0 via the mask
  • Set the bits being modified to the values of m via the | (m << i)

int fitInteger(int n,int n, int i, int j)
{
    /*     bitwise not of (1s from j to the end) - (1s from i to the end) */
    unsigned int mask = ~ ( ((1 << (j-i)) - 1)   -    ((1 << i) - 1) );
    return (n & mask ) | (m << i);
}

Writing in simpler terms:
Logic is basically to create a mask that consists of 1's in all positions except from position i to position j.
  • Create a mask with 1s but only 0s between positions i and j. AND the mask with N to clear the bits between i and j to 0s.
  • Create another mask with 0s but only 1s between positions i and j. AND the mask with M to clear the bits outside i and j to 0s.
  • OR N and M.

public static int updateBits(int n, int m, int i, int j) {
    int max = ~0; /* All 1's */

    // 1's through position j, then 0's
    int left = max - ((1 << (j+1)) - 1);// here should be j+1 not j.

    // 1's after position i
    int right = ((1 << i) - 1);

    // 1's with 0s between i and j
    int mask = left | right;

    // Clear i through j, then put m in there
    return (n & mask) | (m << i);
}

Dry running the program:
N = 1010 1011 1101 1110
M = 1001 0110
i = 4, j = 11. i.e : should be doing: 1010|---- ----|1110   
                                          11        4   

max      = 1111 1111 1111 1111
left(j)  = 1111 1000 0000 0000
right(i) = 0000 0000 0000 0111
mask     = 1111 1000 0000 0111

//Computing left = max - ((1 << (j+1)) - 1)
------------------------- left -----------------------------
(1<<(j+1)) 0001 0000 0000 0000     //shift 1 - 12 times as j+1 is 12
  1    0000 0000 0000 0001 -       // minus
       -------------------             
(temp) 0000 1111 1111 1111     

(max)   1111 1111 1111 1111
(temp)  0000 1111 1111 1111 -      // minus
       ------------------- 
(left)  1111 0000 0000 0000
------------------------------------------------------------

//Computing right=((1 << i) - 1);
----------- right -----------  -----------------------------
(1<<i)  0000 0000 0001 0000        //left rotate 1 4 times (as i=4)
  1     0000 0000 0000 0001 -      // minus
        -------------------     
(right) 0000 0000 0000 1111    
------------------------------------------------------------
//Compute mask = left | right
(left)  1111 0000 0000 0000
(right) 0000 0000 0000 1111 |
        -------------------
(mask)  1111 0000 0000 1111
------------------------------------------------------------
//Compute result = (n & mask) | (m << i)
-----------------------------   ----------------------------
(n)     1010 1011 1101 1110     
(mask)  1111 0000 0000 1111 &    //and operator
        -------------------            
(tmp1)  1010 0000 0000 1110   
        -------------------
(tmp1) 1010 0000 0000 1110      
(m<<i) 0000 1001 0110 0000 |     //or operator
(result) 1010 1001 0110 1110
-------------------------------------------------------------

Reference - stackoverflow

Tuesday, September 13, 2011

Median of 2 sorted arrays of equal size n

Question 

There are 2 sorted arrays A and B. Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length 2n). The complexity should be O(log(n))

Solution

Before going to solution what is the median.

What is Median?

Median: In probability theory and statistics, a median is described as the number separating the higher half of a sample, a population, or a probability distribution, from the lower half.
The median of a finite list of numbers can be found by arranging all the numbers from lowest value to highest value and picking the middle one.


For getting the median of input array { 12, 11, 15, 10, 20 }, first sort the array. We get { 10, 11, 12, 15, 20 } after sorting. Median is the middle element of the sorted array which is 12.
Input Array - {12,11,15,10,20}
Sorted array - { 10, 11, 12, 15, 20 }
Median - 12

There are different conventions to take median of an array with even number of elements, one can take the mean of the two middle values, or first middle value, or second middle value.

Let us see different methods to get the median of two sorted arrays of size n each. Since size of the set for which we are looking for median is even (2n), we are taking average of two middle two numbers in all below solutions.

Method 1 - Simply count while Merging(Brute force)
Use merge procedure of merge sort. Keep track of count while comparing elements of two arrays. If count becomes n(For 2n elements), we have reached the median. Take the average of the elements at indexes n-1 and n in the merged array. See the below implementation.

int getMedian(int arr1[], int arr2[], int n)
{
 int i = 0;  // Current index of array arr1[] 
 int j = 0;  // Current index of array arr2[] 
 int count;
 int m1 = -1, m2 = -1;

 //Since there are 2n elements, median will be average
 // of elements at index n-1 and n in the array obtained after
 // merging ar1 and ar2 
 for(count = 0; count <= n; count++)
 {
  //Below is to handle case where all elements of arr1[] are
  //  smaller than smallest(or first) element of arr2[]
  if(i == n)
  {
   m1 = m2;
   m2 = arr2[0];
   break;
  }

  //Below is to handle case where all elements of arr2[] are
  //  smaller than smallest(or first) element of arr1[]
  else if(j == n)
  {
   m1 = m2;
   m2 = arr1[0];
   break;
  }

  if(arr1[i] < arr2[j])
  {
   m1 = m2;  //Store the prev median
   m2 = arr1[i];
   i++;
  }
  else
  {
   m1 = m2;  //Store the prev median 
   m2 = arr2[j];
   j++;
  }
 }    

 return (m1 + m2)/2;
}    

// Driver program to test above function 
int main()
{
 int arr1[] = {1, 12, 15, 26, 38};
 int arr2[] = {2, 13, 17, 30, 45};

 printf("%d", getMedian(ar1, ar2, 5)) ;

 getchar();
 return 0;
}

Time Complexity - O(n)

Dry running the algorithm
A1 = { 1,12,15,26,38}
A2 = {2,13,17,30,45}

Initially i=0,j=0,m1=m2=-1

So, we reach arr1[i] < a[j] i.e. arr1[0]<arr2[0] which is true.

Method 2 - By comparing the medians of two arrays(Divide and Conquer)
This method works by first getting medians of the two sorted arrays and then comparing them.

Here is an exemple of how it works. Imagine we have these two sorted lists:
l1 = [1, 4, 5, 7, 7, 8, 9, 9] 
l2 = [0, 1, 3, 6, 6, 6, 7, 8]

We calculate the median of both lists:
l1 median = 7
l2 median = 6

l1 median is greater than l2 median so we can safely remove the numbers on the right side of the median of l1 because the final median is somewhere between the median of both. We also have to remove the same amount of numbers at the left side of l2 to keep the stability of the final list. If one of the list is shorter the amount of removed numbers will the minimum between both median index. So we get:
l1 = [1, 4, 5, 7, 7]
l2 = [6, 6, 6, 7, 8]

We continue the process until have a list with 2 numbers (or less).
l1 median = 5
l2 median = 6

We remove 2 from left side of l1, we remove 2 from right side of l2.
l1 = [5, 7, 7]
l2 = [6, 6, 6]

l1 median = 7
l2 median = 6

We remove 1 from left side of l2, we remove 1 from right side of l1.
l1 = [5, 7]
l2 = [6, 6]

Remember that we have 2 list of the same size. In another case one could be an order of magnitude bigger than the other. Finaly we have to deal with some special case:

  1. The 2 remaining numbers have to be inserted on the left side of the median of the other list.
  2. The 2 remaining numbers have to be inserted on the right side of the median of the other list.
  3. One have to be inserted on the left side of the median and the other on the right side.

For each case we have to check if the number could change the median of the resulting list. If we decide to insert l1 into l2, there will be no implication on the initial median value of l2. But if we decide to insert l2 into l1, the median of l1 will be completly changed. In both case we optain this list [5, 6, 6, 7] and calcuate the median of it : 6.
Inserting the two remaining value into the other list is not the fastest thing possible but it's simple and understandable.

Algorithm (Divide and Conquer):

1) Calculate the medians m1 and m2 of the input arrays ar1[]
   and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
     return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
   of the below two subarrays.
    a)  From first element of ar1 to m1 (ar1[0...|_n/2_|])
    b)  From m2 to last element of ar2  (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one
   of the below two subarrays.
   a)  From m1 to last element of ar1  (ar1[|_n/2_|...n-1])
   b)  From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays
   becomes 2.
6) If size of the two arrays is 2 then use below formula to get
  the median.
    Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2

To sum up, actual median M will lie between m1 and m2. If m1 & gt; m2 => M lies between m2 to m1, so all elements less than m1 but more than m2, hence first half of ar1 and 2nd half of ar2. Likewise for m2>m1.

Time Complexity = O(lg n)

Here is the code:
// This function returns median of ar1[] and ar2[].
// This function returns median of ar1[] and ar2[].
//   Assumptions in this function:
//   Both ar1[] and ar2[] are sorted arrays
 //Both have n elements 
int getMedian(int ar1[], int ar2[], int n)
{
  int m1; // For median of ar1 
  int m2; // For median of ar2 
 
  // return -1  for invalid input 
  if(n <= 0)
    return -1;
 
  if(n == 1)
    return (ar1[0] + ar2[0])/2;
 
  if (n == 2)
    return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2;
 
  m1 = median(ar1, n); // get the median of the first array 
  m2 = median(ar2, n); // get the median of the second array 
 
  // If medians are equal then return either m1 or m2 
  if(m1 == m2)
    return m1;
 
  // if m1 < m2 then median must exist in ar1[m1....] and ar2[....m2] 
  if (m1 < m2)
    return getMedian(ar1 + n/2, ar2, n - n/2);
 
  // if m1 > m2 then median must exist in ar1[....m1] and ar2[m2...] 
  return getMedian(ar2 + n/2, ar1, n - n/2);
}
 
// Driver program to test above function 
int main()
{
  int ar1[] = {1, 12, 15, 26, 38};
  int ar2[] = {2, 13, 17, 30, 45};
  printf("%d", getMedian(ar1, ar2, 5)) ;
 
  getchar();
  return 0;
}
 
// Utility functions 
int max(int x, int y)
{
    return x > y? x : y;
}
 
int min(int x, int y)
{
    return x > y? y : x;
}
 
// Function to get median of a single array 
int median(int arr[], int n)
{
  if(n%2 == 0)
    return (arr[n/2] + arr[n/2-1])/2;
  else
    return arr[n/2];
}

References 

Saturday, December 5, 2009

WAP to check whether string is palindrome

Problem
Write a method which will accept a string and return true if the string is a palindrome and false if it isn't.

Follow up:
a) your method should consider lower case and upper case characters to be the same.
b) your method should ignore special characters and white spaces, for e.g. if your input were the strings were "Madam, I'm Adam!!", then you should consider it a palindrome and hence return true ignoring case and special characters. Same with inputs like "Ma'am", "boB" etc should return true.

Solution
Considering the simple case
Eg, of pallindrome = Malayalam
void isPalindrome(char *string)
{
  char *start, *end;

  if(string)
  {
     start = string;
     end   = string + strlen(string) - 1;

     while((*start == *end) && (start!=end))
     {
       if(start
       if(end>start)end--;
     }

     if(*start!=*end)
     {
        printf("\n[%s] - This is not a palidrome!\n", string);
     }
     else
     {
        printf("\n[%s] - This is a palidrome!\n", string);
     }
  }
  printf("\n\n");
}
Answering the following up questions , to come soon.