Microsoft Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
here is the generic solution works for all buckets
#include <cstdlib>
#include <iostream>
using namespace std;
int ways;
void fill(int b[],int n,int sum,int toFill,int filled[],int index)
{
if(sum==toFill)
{
ways++;
cout<<"\n";
for(int i=0;i<index;i++)
cout<<filled[i]<<" ";
return;
}
if(index<n)
{
for(int i=0;i<=b[index];i++)
{
filled[index]=i;
fill(b,n,sum+i,toFill,filled,index+1);
}
}
}
int main(int argc, char *argv[])
{
int b[]={2,3,2};
int filled[3];
fill(b,3,0,4,filled,0);
cout<<"Total Number Of ways :"<<ways;
system("PAUSE");
return EXIT_SUCCESS;
}
wrong. How your system is considering 2 balls in first bucket? It should be 1. So total 6 steps.
111
120
102
012
021
030
@insigniya: Was the question to be done programmatically or manually? If manually then Cl soln is the else if not then either DP or recursive mtd is to be applied.
FillBuck( int x[], int b1, int b2, int b3, int sum){
if (sum == 0) count ++;
else{
if( x[0] && b1<2) FillBuck(x, b1+1, b2, b3, sum-1);
if( x[1] && b1<3) FillBuck(x, b1, b2+1, b3, sum-1);
if( x[2] && b1<2) FillBuck(x, b1, b2, b3+1, sum-1);
x[0]=0;
if( b1 >0) FillBuck(x, b1-1, b2, b3, sum+1);
x[1]=0;
if( b2 >0) FillBuck(x, b1, b2-1, b3, sum+1);
x[2]=0;
if( b3 >0) FillBuck(x, b1, b2, b3-1, sum+1);
}
}
//FillBuck(x, 0, 0, 0, 3) ; where for i = 1 to 3, x[i]=1;
Ans:8
- Anonymous October 03, 2011