Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Thursday, January 14, 2010

Bubble sort

The sorting problem
Input: Array of numbers , unsorted. Eg.

Output : Same numbers sorted in some order, say increasing order. Eg.



What is Bubble Sort?

The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items (in other words, all items are in the correct order). This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

Example
Consider the array - {28, 18, 7, 4, 10}
So, in first pass is bubbled at the top, it being the smallest.












Finally 4 is on top.














Now, in second pass, 10 bubbles out , it being second smallest element and so on:

Bubble sort implementation in c

void bubbleSort(int arr[], int n) {
      bool swapped = true;
      int j = 0;
      int tmp;
      while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < n - j; i++) {
                  if (arr[i] > arr[i + 1]) {
                        tmp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = tmp;
                        swapped = true;
                  }
            }
      }
}


Bubble sort in cpp:
 #include <iostream>
 
 class BubbleSort
 {
     public:
         BubbleSort(){}
         ~BubbleSort(){}
         void sort(int arr[], int size);
 };
 
 void BubbleSort::sort(int arr[], int size)
 {
     //With every iteration in outer loop, the next maximum element is moved to it's correct position
     for(int outerLoopIdx = 0; outerLoopIdx < size ; ++outerLoopIdx)
     {
         for(int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx)
         {
             //Comparing two subsequent elements OR bubble comparison
             //Placing the larger element on the right
             if(arr[innerLoopIdx] > arr[innerLoopIdx + 1])
             {
                 int temp = arr[innerLoopIdx];
                 arr[innerLoopIdx] = arr[innerLoopIdx + 1];
                 arr[innerLoopIdx + 1] = temp;
             }
         }
     }
 }
 
 void print(int arr[], int size)
 {
     for(int i = 0; i < size; ++i)
         std::cout << arr[i] << " ";
     std::cout << std::endl;
 }
 
 int main()
 {
     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
     BubbleSort bs;
     bs.sort(arr, 9);
     print(arr, 9);
     return 0;
 }#include <iostream>
 
 class BubbleSort
 {
     public:
         BubbleSort(){}
         ~BubbleSort(){}
         void sort(int arr[], int size);
 };
 
 void BubbleSort::sort(int arr[], int size)
 {
     //With every iteration in outer loop, the next maximum element is moved to it's correct position
     for(int outerLoopIdx = 0; outerLoopIdx < size ; ++outerLoopIdx)
     {
         for(int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx)
         {
             //Comparing two subsequent elements OR bubble comparison
             //Placing the larger element on the right
             if(arr[innerLoopIdx] > arr[innerLoopIdx + 1])
             {
                 int temp = arr[innerLoopIdx];
                 arr[innerLoopIdx] = arr[innerLoopIdx + 1];
                 arr[innerLoopIdx + 1] = temp;
             }
         }
     }
 }
 
 void print(int arr[], int size)
 {
     for(int i = 0; i < size; ++i)
         std::cout << arr[i] << " ";
     std::cout << std::endl;
 }
 
 int main()
 {
     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
     BubbleSort bs;
     bs.sort(arr, 9);
     print(arr, 9);
     return 0;
 }

Bubble sort in java
To come

Bubble sort in java using Generics
import org.junit.Assert;
import org.junit.Test;

class GenericBubbleSorter<T extends Comparable<T>>
{
    public void sort(T[] elems) {
        int size = elems.length;

        for (int outerLoopIdx = 0; outerLoopIdx < size; ++outerLoopIdx) {
            for (int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx) {
                if (elems[innerLoopIdx].compareTo(elems[innerLoopIdx + 1]) > 0) {
                    T temp = elems[innerLoopIdx];
                    elems[innerLoopIdx] = elems[innerLoopIdx + 1];
                    elems[innerLoopIdx + 1] = temp;
                }
            }
        }
    }
}

public class BubbleSortTester
{
    private String[] unsortedNames = new String[] {
            "Pankaj",
            "Paresh",
            "Ankit",
            "Sankalp",
            "Aditya",
            "Prem",
            "Rocket",
            "Singh",
            "Alabama",
            "Alaska",
            "Animal" };

    private String[] sortedNames = new String[] {
            "Aditya",
            "Alabama",
            "Alaska",
            "Animal",
            "Ankit",
            "Pankaj",
            "Paresh",
            "Prem",
            "Rocket",
            "Sankalp",
            "Singh" };

    @Test
    public void testStringSort() {
        GenericBubbleSorter<String> bs = new GenericBubbleSorter<String>();
        bs.sort(unsortedNames);
        Assert.assertArrayEquals(unsortedNames, sortedNames);
    }
}

Thanks.

Thursday, January 7, 2010

Array of 0 and 1, put 0's at even position and 1's at odd position

you are given an array of integers containing only 0s and 1s. you have to place all the 0s in even position and 1s in odd position and if suppose no if 0s exceed no. of 1s or vice verse then keep them untouched. Do that in ONE PASS and WITHOUT taking EXTRA MEMORY.

input array:
{0 1 1 0 1 0 1 0 1 1 1 0 0 1 0 1 1 }
output array:
{0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 }

Thursday, May 15, 2008


This is similar to an implementation of partition method of quick sort.

oddInd==0;
evenInd=1;

while(true)
{
  while(oddInd
  if(oddInd>=strLen) break;
  while(evenInd
  if(evenInd>=strLen) break;
  swap(str[evenInd], str[oddInd]);
}

Well, one more challenging version of this problem is to consider an array containing 0s,1s and 2s and do the same thing. This question was asked in one microsoft internship interview.
jigsaw Send private email
Thursday, May 15, 2008


OOPS!!! There was a big mistake in the above code.
This is similar to an implementation of partition method of quick sort.

oddInd==0;
evenInd=1;

while(true)
{
  while(oddInd  if(oddInd>=strLen) break;
  while(evenInd  if(evenInd>=strLen) break;
  swap(str[evenInd], str[oddInd]);
}

Well, one more challenging version of this problem is to consider an array containing 0s,1s and 2s and do the same thing. This question was asked in one microsoft internship interview.
jigsaw Send private email
Thursday, May 15, 2008


Perish the thought that anyone should use extra memory!

BTW, the indexes into the array are extra memory.

Too many of these questions are isomorphic with:
"Oh, so you can type in your code?  How about if we tie one arm behind your back?  YANK!  Still typing?  How about if we keep hitting you with this baseball bat?  Whack, whack, whack!  Still at it, huh?  Well, at least we got him down to 2 WPM."

Sincerely,

Gene Wirchenko
Gene Wirchenko Send private email
Thursday, May 15, 2008


:) That's funny. BTW when he said extra memory, he meant variable amt of memory i guess.
jigsaw Send private email
Friday, May 16, 2008


That seems to be what they mean when they say no extra memory. Heck making a function call allocates a frame on the stack so does that mean no function calls either?

  I always took it to mean no building a data structure.  Which can be a  valid restriction if data is going to be changing often(high rebuild costs) or you have a truly large dataset. It can be hard to get a std::vector to hit 100mb if you already have a number of other 100mb chunks floating around.
soup
Friday, May 16, 2008


soup,

The usual complexity-theoretic definition of "no extra memory" is that the program can use a constant number of registers just large enough to index the input.
d
Friday, May 16, 2008


I tried JigSaw's solution in to java(http://pastebin.com/f41fe39d1). I might have mis-understood the code but the resulting array is
1 0 1 0 1 0 1 0 1 0  1  0  1  0  1  1
ved Send private email
Monday, May 26, 2008


I think there is a problem in jigsaw's solution.His solution says:
oddInd==0;
evenInd=1;

while(true)
{
  while(oddInd  if(oddInd>=strLen) break;
  while(evenInd  if(evenInd>=strLen) break;
  swap(str[evenInd], str[oddInd]);
}
First of all.it will produce an an arrangement of 10101010 type of string.But that can be solved by using str[oddInd]==0 and str[evenInd]==1. But more serious problem is if the array is such that it has even no. of elements and each even positions are correctly filled with 0s and there are some extra 0s in odd positions because in that case the first inner while loop executes and then the outer while loop terminates by break statement.
sagsriv Send private email
Friday, June 13, 2008


@sagsriv

i guess the depend on understanding of "and if suppose no if 0s exceed no. of 1s or vice versa then keep them untouched"

e.g., input array:
{0 1 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0 }
output array should be:
a)
{0 1 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0 }
since in the question, it states
"if 0s exceed no. of 1s or vice versa then keep them untouched"

or

b)
{0 1 0 1 0 1 0 1 0 1 0 1 0 0 0 0 0 }
to move "0s" to the end.which should can be also done in one pass.

which looks better..lol
ray Send private email
Monday, July 07, 2008


Add all the numbers in the array to get the sum. The sum equals to number of ONEs in the array? Then prepare the sequence of 0,1,0,1 ... based on the no. of ONEs using a simple for loop.

Wednesday, January 6, 2010

Anagram program implentation

#include 
using namespace std;

#include "anaword.h"

static const int ALPH_SIZE = 26;

Anaword::Anaword(const string & word)
    : myWord(word),
      myCounts(ALPH_SIZE,0)
// postcondition: constructed    
{
    normalize();
}

Anaword::Anaword()
    : myWord(""),
      myCounts(ALPH_SIZE,0)
{
    
}

void Anaword::normalize()
// postcondition: myCounts represents the letter signture of myWord
{
    
}

string Anaword::toString() const
// postcondition: return "bagel" or "gable", regular form of string
{
    return myWord;
}

ostream & operator << (ostream & out, const Anaword & a)
// postcondition: a printed t stream out, out returned    
{
    out << a.toString();
    return out;
}

bool Anaword::equal(const Anaword & rhs) const
// postcondition: returns true if and only if *this == rhs
//                canonical/normalized form of word used for comparisons    
{
    return false;
}

bool operator == (const Anaword & lhs, const Anaword & rhs)
// postcondition: returns true if and only if lhs == rhs
{
    return lhs.equal(rhs);
}

bool operator != (const Anaword & lhs, const Anaword & rhs)
// postcondition: returns true if and only if lhs != rhs
{
    return ! lhs.equal(rhs);
}


bool Anaword::less(const Anaword & rhs) const
// postcondition: returns true if and only if *this < rhs
//                canonical/normalized form of word used for comparison    
{
    return false;
}

bool operator <  (const Anaword & lhs,const Anaword & rhs)
// postcondition: returns true if and only if *this < rhs    
{
    return lhs.less(rhs);
}

bool operator <=  (const Anaword & lhs,const Anaword & rhs)
// postcondition: returns true if and only if *this <= rhs
{
    return ! rhs.less(lhs);
}

Tuesday, January 5, 2010

Finding whether 2 arrays are intersecting


Here are 2 arrays:
A1   1 8 7 5 6
A2   0 9 6 4 2

These two are intersecting at 6.
Complexity? 



Solution:
This can be solved using Hash Tables.
Take 1 Hash Table.
Insert elements from A1 in Hast Table as key and put value in front of them
(In case elemente get repeated increment the value count).
Now traverse the second array A2 and check for element as a key.If you find
it decrement the value and put it in array else continue to next element in
A2.

Given an array of n integers from 1 to n with one integer repeated twice

Problem - Given an array of n integers from 1 to n with one integer repeated twice
This can be done via normal array traversal or hash table to find duplicates. But since we are given that the integers are from 1 to n, then there are better methods available.

Approach 1 - Arithmetic sum approach
So, the efficient method to solve it calculate the sum of actual input array, and expected sum of the array.
Input: 1,2,3,2,4 => 12
Expected: 1,2,3,4 => 10
Input - Expected => 2

In general, arithmetic sum of series with numbers - 1,2,...n is n(n+1)/2

Approach 2 - Using the xor approach
 XOR method works when we have an element repeated odd number of times, see here, because xor on number for odd number of times results in that number and xor for number for even number of times returns 0.
i.e.
So, this approach will work uses one additional integer to keep the loop counter, and it accesses each array element three times - twice to read it and write it at the current iteration and once to read it for the next iteration.


for(int i=0;i<array.length;i++){
  array[i] = array[i] ^ array[i-1] ^ i;
}
print(array[n-1]);

However array here is destroyed. Running time is again O(n) and because we use counter, so space complexity is O(1).


Lets dry run. (to come soon) 

But we don't what to destroy the array, then we can use a separate variable to maintain duplicate element.
int dupe;
for(int i=0;i<array.length;i++){
  dupe = dupe ^  i  ^array[i] ;
}
print (dupe);

Approach 3 - Sorting 
Sort the array in O(n log n) time and then check if 2 adjacent elements are equal which takes O(n), so overall O(n log n)

Approach 4 - Hashtable
Of-course this is again very simple approach, where we can add the element to the hashtable, and if the element already exists, while adding this is the element. Again it takes O(n). We can also use array, which pretends like hashtable -

//elements from 1-10
int count [10];

for (int i = 0; i < arraylen; i++) {
    count[array[i]]++;
}

Thanks.

Sunday, January 3, 2010

Given a list of n numbers from 1 to n-1, with one of the numbers repeated. Devise a method to determine which number is repeated

The sum of the numbers 1 to n-1 is (n)(n-1)/2. Add the numbers on the list, and subtract (n)(n-1)/2. The result is the number that has been repeated.

Give a fast way to multiply a number by 7

Multiply by 8 (left shift by 3 bits) and then subtract the number.
(x << 3) - x

Routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all.

Problem

Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all.

Solution

Let

(x ^ 2 + y ^2 = r ^ 2)...................................1 

The basic idea is to draw one quadrant and replicate it to other four quadrants.
Assuming the center is given as (a,b) and radius as r units, then start X from (a+r) down to (a) and start Y from (b) up to (b+r). In the iteration, keep comparing is the equation (1) is satisfied or not within an error of one unit for a and b. If not then re-adjust X and Y.

Also, we should either use Mid point theorem or Bresenham's circle drawing algorithm for this.

Saturday, December 12, 2009

c program without main

http://c4learn.com/c-programs/c-program-without-main-function.html

Saturday, December 5, 2009

How can we sum the digits of a given number in single statement?

int sum=0;

  for(;num>0;sum+=num%10,num/=10);  // This is the "single line".

A program to print numbers from 1 to 100 without using loops

Method1 (Using recursion)


void printUp(int startNumber, int endNumber)
{
  if (startNumber > endNumber)
    return;
 
  printf("[%d]\n", startNumber++);
  printUp(startNumber, endNumber);
}




Method2 (Using goto)


void printUp(int startNumber, int endNumber)
{
start:

    if (startNumber > endNumber)
    {
       goto end;
    }
    else
    {
       printf("[%d]\n", startNumber++);
       goto start;
    }

end:
    return;
}

How to add two numbers without using the plus operator?

Actually,
SUM   = A XOR B
CARRY = A AND B
Recursive:
int add(int a, int b){
            if (!a) return b;
            else
                 return add((a & b) << 1, a ^ b);
      }

Iterative

unsigned long add(unsigned long integer1, unsigned long integer2)
{
    unsigned long xor, and, temp;

    and = integer1 & integer2; /* Obtain the carry bits */
    xor = integer1 ^ integer2; /* resulting bits */

    while(and != 0 ) /* stop when carry bits are gone */
    {
        and <<= 1; /* shifting the carry bits one space */
        temp = xor ^ and; /* hold the new xor result bits*/
        and &= xor; /* clear the previous carry bits and assign the new
carry bits */
        xor = temp; /* resulting bits */
    }
    return xor; /* final result */



} 



On a wicked note, you can add two numbers wihtout using the + operator as follows
a - (- b)

Other way is to use ++ operator:
           int a=10,b=20;
          while(b--) a++;
           printf("Sum is :%d",a);  

Convert the decimal number to any base (binary, hex, oct etc...)

#include 

int main()
{
  decimal_to_anybase(10, 2);
  decimal_to_anybase(255, 16);
  getch();
}

decimal_to_anybase(int n, int base)
{
  int i, m, digits[1000], flag;
  i=0;

  printf("\n\n[%d] converted to base [%d] : ", n, base);

  while(n)
  {
     m=n%base;
     digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];
     n=n/base;
     i++;
   }

   //Eliminate any leading zeroes
   for(i--;i>=0;i--)
   {
     if(!flag && digits[i]!='0')flag=1;
     if(flag)printf("%c",digits[i]);
   } 
}

How to find out if a machine is 32 bit or 64 bit?

n = sizeof(void *);


if n==8, than 64 bit 
if n==4, than 32 bit.

Thursday, December 3, 2009

Given an eight-bit bitmap graphics file, devise an algorithm to convert the file into a two-bit ASCII approximation

Assume that the file format is one byte for every pixel in the file, and that the approximation will produce one ASCII character of output for each pixel. This problem is easier to solve than it sounds. This is one of the tricks used in technical interview questions. Problems may be obscured or made to sound difficult. Don't be fooled! Take the time to think about the core of the problem. In this case, all you want is an algorithm for reading the values in a file and outputting characters based upon those values.
Eight-bit numbers can be in the range from 0 to 255. Two-bit numbers are in the range from 0 to 3. Basically, we want to divide the 256 numbers specified by an eight-bit number into four ranges, which can be indicated by a two-bit number. So, divide the range of 0 to 255 uniformly into four separate ranges: 0 to 63, 64 to 127, 128 to 191, and 192 to 255.
You then have to assign an ASCII character to each of those four ranges of numbers. For example, you could use "_", "~", "+", and "#". Then, the algorithm is as follows:
1. Open the file.
2. For every byte in the file:
a. Read in one byte.
b. If the value is in the range 0..63, we'll print '_'.
c. If the value is in the range 64..127, we'll print '~'.
d. If the value is in the range 128..191, we'll print '+'.
e. If the value is in the range 192..255, we'll print '#'.
3. Close the file.

Given the time, devise an algorithm to calculate the angle between the hour and minute hands of an analog clock

The important realization for this problem is that the hour hand is always moving. In other words, at 1:30, the hour hand is halfway between 1 and 2. Once you remember that, this problem is fairly straightforward. Assuming you don't care whether the function returns the shorter or larger angle.

Efficient code for extracting unique elements from a sorted list of array

int main()
{
int a[10]={1, 2, 4, 4, 7, 8, 9, 14, 14, 20};
int i;
for (i = 0;i<9;i++)
{
if (a[i] != a[i+1])
printf("%d\n",a[i]);
}
return 0;
}

Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal

void putlong(unsigned long x)
{
// we know that 32 bits can have 10 digits. 2^32 = 4294967296
for (unsigned long y = 1000000000; y > 0; y /= 10) {
putchar( (x / y) + '0');
x = x % y;
}
}

Friday, November 27, 2009

Swap two number in place without temporary variables.

Problem

Write a function to swap two number in place without temporary variables.

Solution


Method1 - The XOR or Exclusive trick
In C this should work:
a ^= b ^= a ^= b;


to simplify :
a=a^b;
b=a^b;
a=a^b;

OR
a^=b;
b^=a;
a^=b;

Following are operations in XOR

  • 0^0=0
  • 0^1=1
  • 1^0=1
  • 1^1=0
Hence, we have:
  • a=a^b: 'a' will save all the bits that a differs from b: if the bit that 'a' and 'b' differ, it gets 1, otherwise 0.
  • b=a^b: 'b' will compare to the difference between a and b: for the bit that 'b' and 'a' differ, it means a have 1 at this position and the result of a^b will assign that bit to 1; for the bit that 'b' and 'a' agree, it means a have 0 at this position and the result of a^b will assign that bit to 0.
  • a=a^b:  same logic
Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it wont work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this

Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other.

swap(int *a, int *b)
{
  if(*a!=*b)
  {
    *a ^= *b ^= *a ^= *b;
  }
}

Method 2 - Simple addition and subtraction

This method is also quite popular
 a=a+b;
 b=a-b;
 a=a-b;

OR
a =((a = a + b) - (b = a - b));
But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results.