Find the number of ways of placing 3 balls in 3 buckets......
Microsoft Interview Questions and Answers
(Continued from previous question...)
27. Find the number of ways of placing 3 balls in 3 buckets......
Question:
Find the number of ways of placing 3 balls in 3 buckets. buckets are of diff capacity.
bucket1 can hold 2 balls
bucket2 - 3 balls
bucket3 - 2 balls.
ex. 1 1 1 is valid
0 3 0 is valid
maybe an answer1:
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;
}
maybe an answer2:
// simple solution
int main()
{
int i,j,k,count=0;
for(i=0;i<=2;i++)
{
for(j=0;j<=3;j++)
{
for(k=0;k<=2;k++)
{
if((i+j+k)==3)
{
cout<<i<<j<<k<<endl;
count++;
}
}
}
}
cout<<"count is "<<
maybe an answer3:
Ans:8
int main()
{
int i,j,k,count=0;
for(i=0;i<=2;i++)
{
for(j=0;j<=3;j++)
{
for(k=0;k<=2;k++)
{
if((i+j+k)==3)
{
cout<<i<<j<<k<<endl;
count++;
}
}
}
}
cout<<"count is "<<count;
cin.get();
return 0;
}
(Continued on next question...)
Other Interview Questions
|