Wednesday, December 30, 2009

for programming interviews part5

hi
today we shall discuss simple problems like


9.Write, efficient code for extracting unique elements from a sorted
list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9 }


#include < iostream >
int main()
{
using namespace std;
int a[20]={1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9};
int i=0,k=0;
for(i=1;i < 20 ; ++i)
{
if(a[k]==a[i])
continue;
else
{
++k;
a[k]=a[i];
}
}
for(i=0;i < k ; ++i )
cout << a[i];
cin.sync();
cin.get();
return 0;
}


10
Give a fast way to multiply a number by 7

#include < iostream >
int main()
{
using namespace std;
long long int a=0;
cin>>a;
long long int k=a;
k=( a << 3 )-k;
cout << k;
cin.sync();
cin.get();
return 0;
}

11
how to remove characters of string2 from string1

#include < iostream >
#include < string >
#include < map >
int main()
{
using namespace std;
char s1[10],s2[10];
int i=0,j=0;
cout<< "nter string 1";
cin >> s1;
cout << "nter string 2";
cin >> s2;
map < char , int > mp;
i=0;
while(s2[i])
{
mp[s2[i]]=1;
++i;
}
int k=0;
while(s1[i])
{
if(!mp[s1[i]])
s1[k]=s1[i];
//cout << s1[k];
++k;
++i;
//cout << s1;
}

for(i=0; i < k; ++i)
cout << s1[i];

//cout << s1 << endl;
cin.sync();
cin.get();
return 0;
}

11.how does a bootstraploader work in a linux

whoa that was shocker.............!!!!!!!!!!.
dont worry
->the BIOS takes the H/W platform specific tasks
->Once the H/W is recognised and started correctly the BIOS loads and executes partition code
->the boot loader presents the user with the various boots options,it then loads the OS after decompressing it from memory and sets H/W and memory management before calling the start_kernel() method
->the start_kernel() performs major operations for initializations and spawing process like init(),schedulers.
->scheduler-it takes care of sys management when kernel goes dormant
->init-it takes care of displaying user scripts for non OS services that are available for user environment.
->the user gets login screen.


whats difference between segmentation and paging
segmentation->it basically has logical units of arbitrary size
it has user protection,its visible to user via programs
paging-its basically physical units of fixed size it remains hidden from user and not visible in his program.

Monday, December 28, 2009

programming interviews part4

today we shall discuss some problems which require some c features

1.how to find the machine is little endian or big endian

#include < iostream >
using namespace std;
int main()
{
int n=1;
if(*(char*)&n==1)
cout<<"small";
else
cout<<"big";
cin.sync();
cin.get();
return 0;
}

2.
wap for finding the sizeof a particular datatype without using sizeof()

#include < iostream >
//#define size(T)(*((char*)&T+1-*(char*)&T));
#define SIZEOF(var) (size_t)(&var+1) - (size_t)(&var)

using namespace std;
int main()
{
int a;
cout << SIZEOF(a);
cin.sync();
cin.get();
return 0;
}

3.wap for finding if stack grows upward or downwards


#include < iostream >
using namespace std;
int main()
{
auto int a; auto int b;
if((&b-&a)>0)
cout<<"down";
else
cout<<"up";
cin.sync();
cin.get();
return 0;
}

4.wap for converting from one endian to other

int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;

byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;

return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}

5.
wap a c program for swapping nibbles in byte
nibble=4bits
byte=8bits
#include < stdio.h >

unsigned char swap_nibbles(unsigned char c)
{
unsigned char temp1, temp2;
temp1 = c & 0x0F;
temp2 = c & 0xF0;
temp1=temp1 << 4;
temp2=temp2 >> 4;

return(temp2|temp1); //adding the bits
}

int main()
{
char ch=0x34;
printf("\nThe exchanged value is %x",swap_nibbles(ch));
return 0;
}

6.wap for adding 2 numbers without +

some guys like(rancho in 3 idiots mite come up with answers like a-(-b)
which is somewhat acceptable if interviewer isn't like imperial college principal)

for others

#include < iostream >
using namespace std;
int main()
{
int a=5,b=4;
int c=0,d=0;
while(b!=0)
{
c=a^b;
d=a&b;
a=c;
d << = 1;
b=d;
}
cout << a;
cin.sync();
cin.get();
return 0;
}


7.wap for swapping two numbers without
temp variable

#include < iostream >
using namespace std;
int main()
{
int a=7,b=8;
a-=b;
b+=a;
a-=b;
a*=-1;
cout << a << endl << b;
cin.sync();
cin.get();
return 0;
}

Thursday, December 24, 2009

for programming interviews-part3

today we shall discuss a simple problems.
5.how do u find out if a no is divisible by 2 in a single line.?
int x;
x&&!(x&(x-1))

6.wap for single line swap of 2 integers without temp variable.

a^=b^=a^=b;

7.wap for finding max & min of 2 nos without branching?

min : (b-(!(a-b) &-(a < b ) ))
max : (a+(!(a-b) &-(a < b ) ))

8.wap for printing the self source code(this was asked to me in HP interview
actually the ans is quine(self printing code )
but the interviewer sed that it wasnt the answer he was expecting.
but i wrote the code for quine .he replied even a 7th grader could write tat code.....
ans:
char *f={"char*f=%c%s%c;main(){ printf(f,34,f,34,10);%c";main(){printf(f,34,f,34,10);}

9.how to print a matrix spiraaly
ans:
for(i=size(a) ,j=0;i > = 0; --i, ++j)
{
for(k=j;k < i; ++k)cout << a[j][k];
for(k=j;k < i; ++k)cout << a[k][i];
for(k=i;k > j; --k)cout << a[i][k];
for(k=j;k > j; --k)cout << a[k][j];
}
if(size(a)%2 == 0)
mid=size/2;
cout << a[mid][mid];

Wednesday, December 23, 2009

for programming interviews part-2

3.wap for sorting ones and 0 in most efficient way while preserving the order.

ans:the solution as many would have guessed has to be in O(n).and the usual 2 pointer approach is correct.but ek problem the order is not preserved hence we have to think of a different approach.we can use 2 ptr approach.a slight change.in the regular approach there is one ptr in front and 2nd ptr at the end of array.
but in my approach we can have 2 ptrs such that both are at front.

#include
using namespace std;
int main()
{
int arry[5]={1,1,1,0,1};
int i=0,j=0,k=0;
for(;k<5;++k)
{
if((i==j)&&(arry[i]!=0))
{
++i;
++j;
}

else if(i==j){
j++;
}
else if(arry[j]==0){
j++;
}
else if((arry[i] == 0) && (arry[j]!=0))
{
int tmp;
tmp = arry[j];
arry[j]=arry[i];
arry[i]=tmp;
i++;
j++;
}

}
for(i=4;i>=0;--i)
cout<cin.sync();
cin.get();
return 0;
}
u can use this approach to sort(separate) the given set of non 0 number and 0 .by putting 0 at end and prserving order.

4.shuffle a deck of cards.


int array[52];
for(i=0;i<52;++i)
{
int rand=rand()%52;
swap(a[i],a[rand]);
}



Tuesday, December 22, 2009

for programming interviews-part 1

hi from now on me writing blogs to answer various programming questions
to start with a simple one
1.Wap to find the largest sum subsequence in array of both +ve and -ve elements
for (int i = 0; i < array.Length; i++)
{
largest = largest > array[i] ? largest : array[i];

curMax = curMax + array[i];
if (curMax > maxSoFar)
{
maxSoFar = curMax;
maxEnd = i;
maxStart = curMaxStart;
allNegatives = false;
}
else if (curMax <= 0)
{
curMax = 0;
curMaxStart = i + 1;
}
}

if (allNegatives)
{
return largest;
}
return maxSoFar;
}
we need to find the sum and also the start and end points.

2.write a program to find out a solution for 8 queen problem?
(this was asked to me in my MS interview)
basically the solution for 8 queen problem consists on the following part.
1.we need to check if i-th and j-th column are empty or not
2.we need to check if the queen is placed in major diagonal t[i]-t[j]==(i-j)
3.or is it in minor diagonal t[j]-t[i]==(i-j)
t[i] is the presence of queen in row i and column t[i] meaning if t[4]=8 means that in 8th row the queen is present in 4 th column
heres the code.

void queen(int i)
{
for(t[i]=1;t[i]<=8;t[i]++)
{
if(i)
{
if(i==8)
print_solution();
else
queen(i+1);
}
}
int empty(int i)
{
int j;
j=1;

while(t[i]!=t[j] && abs(t[i]-t[j])!=(i-j) &&j<8)j++;

return((i==j)?1:0);
}

And here is one of the possible solutions



t[1] = [1] // This means the first square of the first row.
t[2] = [5] // This means the fifth square of the second row.
t[3] = [8] ..
t[4] = [6] ..
t[5] = [3] ..
t[6] = [7] ..
t[7] = [2] ..
t[8] = [4] // This means the fourth square of the last row.

Friday, December 11, 2009

a Simple paint application in python


hi
I'm back .I started my quest with Python from last week.Python is one of the coolest OOP scripting language.("no wonder google bots are programmed via Python").
It has a wide range of libraries Tkinter,wxWindget etc.These support a heck lot of GUI programming.These are lllr to GTK+ in UNIX.Remember the library that supports GUI in UNIX c.or the windows.h in VC++.the power of python is that its used for scientific computing cos the precision is perfect event for 1 millionth decimal in floating point.unlike in c/c++ where the long long int can support up to 16 digits(!!! don't know exactly).Python can support any no. of digits.hence its used by NASA for coding purpose.

Hence i decide to add one of my code for GUI programming its a paint application in python.
hope u would have installed python i n Linux environment.or in case of windows install it from
http://www.python.org/download/.




the code is

from Tkinter import *

class PaintBox( Frame ):
"""Demonstrate drawing on a Canvas"""

def __init__( self ):
"""Create Canvas and bind paint method to mouse dragging"""

Frame.__init__( self )
self.pack( expand = YES, fill = BOTH )
self.master.title( "A simple paint program" )
self.master.geometry( "300x150" )

self.message = Label( self,
text = "Click and Drag the mouse to draw" )
self.message.pack( side = BOTTOM )

# create Canvas component
self.myCanvas = Canvas( self )
self.myCanvas.pack( expand = YES, fill = BOTH )

# bind mouse dragging event to Canvas
self.myCanvas.bind( "", self.paint )

def paint( self, event ):
"""Create an oval of radius 4 around the mouse position"""

x1, y1 = ( event.x - 4 ), ( event.y - 4 )
x2, y2 = ( event.x + 4 ), ( event.y + 4 )
self.myCanvas.create_oval( x1, y1, x2, y2, fill = "black" )

def main():
PaintBox().mainloop()

if __name__ == "__main__":
main()


guys the most important part is check for indentations .python is strict to it and punishes those who don't follow it .just copy paste this code and add on specific functionalities to it.happy python coding


Sunday, December 6, 2009

VOIP for wireless networks

hi this is my first time of writing a blog.
so i would like to start with small intro about me.
I'm pursuing my final year BE CSE in MIT(ANNA UNIVERSITY) its most prestigious college with distinguished set of alumni including former president Dr A.P.J Abdul Kalam.
my area of interest include Wireless communications so i decide to throw light on VOIP STACK.

I hope u would have heard about Skype.Its currently owned by eBay. It is a software application that allows users to make voice calls over the Internet. Calls to other users of the service and, in some countries, to free-of-charge numbers, are free, while calls to other landlines and mobile phones can be made for a fee.As we can see it does require a cost.Hence there must an alternate design which must be made to compensate for extra cost for mobile phones.As India is third largest country in world with max count of cellphones which is to touch approx 20 billion in ther yaer 2015 as according to Qualcomm(an american firm which provides wireless products similar to AT&T BELL LABS) .In long run we have to make sure that even if we make a call from PC the number of landlines is going to be on a decline.As the number of cellphones increases people will automatically shift to GPS and WAP Browsers.We need to ensure how to cut costs on make IPCalls.
before shifting to that we need to get a clear idea of what is VOIP and what are its features etc etc.
VoIP is a revolutionary technology that has the potential to completely rework the world's phone systems. VoIP providers like Vonage have already been around for a while and are growing steadily. Major carriers like AT&T are already setting up VoIP calling plans in several markets around the United States, and the FCC is looking seriously at the potential ramifications of VoIP service

There are three different "flavors" of VoIP service in common use today:
  • ATA -- The simplest and most common way is through the use of a device called an ATA (analog telephone adaptor). The ATA allows you to connect a standard phone to your computer or your Internet connection for use with VoIP. The ATA is an analog-to-digital converter. It takes the analog signal from your traditional phone and converts it into digital data for transmission over the Internet. Providers like Vonage and AT&T CallVantage are bundling ATAs free with their service. You simply crack the ATA out of the box, plug the cable from your phone that would normally go in the wall socket into the ATA, and you're ready to make VoIP calls. Some ATAs may ship with additional software that is loaded onto the host computer to configure it; but in any case, it's a very straightforward setup.

  • IP Phones -- These specialized phones look just like normal phones with a handset, cradle and buttons. But instead of having the standard RJ-11 phone connectors, IP phones have an RJ-45 Ethernet connector. IP phones connect directly to your router and have all the hardware and software necessary right onboard to handle the IP call. Wi-Fi phones allow subscribing callers to make VoIP calls from any Wi-Fi hot spot.

  • Computer-to-computer -- This is certainly the easiest way to use VoIP. You don't even have to pay for long-distance calls. There are several companies offering free or very low-cost software that you can use for this type of VoIP. All you need is the software, a microphone, speakers, a sound card and an Internet connection, preferably a fast one like you would get through a cable or DSL modem. Except for your normal monthly ISP fee, there is usually no charge for computer-to-computer calls, no matter the distance.
I had copy pasted certain terms.But i will surely explain these terms in subsequents blogs...

Using VOIP:
Chances are good you're already making VoIP calls any time you place a (long-distance call(have i heard it somewhere ya.... in Jab We Met Movie)no wonder Shahid names it "Geet"). Phone companies use VoIP to streamline their networks. By routing thousands of phone calls through a circuit switch and into an IP gateway, they can seriously reduce the bandwidth they're using for the long haul. Once the call is received by a gateway on the other side of the call, it's decompressed, reassembled and routed to a local circuit switch.

Although it will take some time, you can be sure that eventually all of the current circuit-switched networks will be replaced with packet-switching technology (more on packet switching and circuit switching later). IP telephony just makes sense, in terms of both economics and infrastructure requirements. More and more businesses are installing VoIP systems, and the technology will continue to grow in popularity as it makes its way into our homes. Perhaps the biggest draws to VoIP for the home users that are making the switch are price and flexibility.

Most VoIP companies are offering minute-rate plans structured like cell phone bills for as little as $30 per month. On the higher end, some offer unlimited plans for $79. With the elimination of unregulated charges and the suite of free features that are included with these plans, it can be quite a savings. (yaar bahut baat karte ho yaar)=>(yaar you talk a lot).

Most VoIP companies provide the features that normal phone companies charge extra for when they are added to your service plan. VoIP includes:

  • Caller ID
  • Call waiting
  • Call transfer
  • Repeat dial
  • Return call
  • Three-way calling
There are also advanced call-filtering options available from some carriers. These features use caller ID information to allow you make a choice about how calls from a particular number are handled. You can:
  • Forward the call to a particular number(hope u would remember what we learnt in MC)(mobile computing course)
  • Send the call directly to voice mail
  • Give the caller a busy signal
  • Play a "not-in-service" message
  • Send the caller to a funny rejection hotline
With many VoIP services, you can also check voice mail via the Web or attach messages to an e-mail that is sent to your computer or handheld. Not all VoIP services offer all of the features above. Prices and services vary, so if you're interested, it's best to do a little shopping. Now that we've looked at VoIP in a general sense, let's look more closely at the components that make the system work. To understand how VoIP really works and why it's an improvement over the traditional phone system, it helps to first understand how a traditional phone system works
apart from this we have SS7(Standard signaling 7).

In my subsequent blogs i shall tell about the strategy how to develop voip stack for mobile phone.