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.

No comments:

Post a Comment