The solution is pretty simple if you consider that there are 7 possibilities (mutually exclusive) depending on whether you choose one / two / three types of candies.
The solution in C# is listed below.
Note : FindMax2 is a simple function (implementation not listed) that can be used to find the maximum value from the ArrayList.
//there are 7 combinations
ArrayList ar = new ArrayList();
double sm = 0;
//Loop 1
for (int i = 7; i >= 1; i--)
{
sm = i * 0.59;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
//Loop 2
for (int i = 7; i >= 1; i--)
{
sm = i * 0.79;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
//Loop 3
for (int i = 7; i >= 1; i--)
{
sm = i * 0.95;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
//Loop 4
for (int i = 7; i >= 1; i--)
{
for (int j = 7; j >= 1; j--)
{
sm = i * 0.59 + j * 0.79;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
}
//Loop 5
for (int i = 7; i >= 1; i--)
{
for (int j = 7; j >= 1; j--)
{
sm = i * 0.79 + j * 0.95;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
}
//Loop 6
for (int i = 7; i >= 1; i--)
{
for (int j = 7; j >= 1; j--)
{
sm = i * 0.59 + j * 0.95;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
}
//Loop 7
for (int i = 1; i < 7; i++)
{
for (int j = 1; j < 7; j++)
{
for (int k = 1; k < 7; k++)
{
sm = i * 0.59 + j * 0.79 + k * 0.95;
if (sm > 4)
{
continue;
}
else
{
ar.Add(sm);
}
}
}
}
MessageBox.Show(FindMax2(ar).ToString());
The problem statement is to choose the maximum of one or more among three candies A, B and C priced respectively at 0.59, 0.79 and 0.95, such that you can procure the value closest to $4.00.
Comments