我正在研究一个可以用java或伪代码完成的作业问题,我正在尝试java代码的方式。
背景:有一台制作iphone外壳的机器。这台机器可以制造三种可能的情况,每种情况都有不同的油漆成本。给定原始油漆量,返回可以制作的最小箱子数量的整数值。
这是我的代码,
public class ProblemFour
{
//Array entries represent cost for red, green and blue respectively.
int[] classicCost = {4, 1, 1};
int[] coolCost = {3, 2, 1};
int[] modernCost = {1, 3, 2};
String[] names = {"classic", "cool" , "modern"};
int red;
int green;
int blue;
Random generator = new Random();
int pick = generator.nextInt(3);
public int minPhone(int r, int g, int b, String mold)
{
int counter = 0;
if (r > 1 && g > 1 && b > 1 && mold.equals("classic"))
{
counter += 1;
red = r - classicCost[0];
green = g - classicCost[1];
blue = b - classicCost[2];
Random generator = new Random();
int pick = generator.nextInt(3);
counter += minPhone(red, green, blue, names[pick]);
}
else if (r > 1 && g > 1 && b > 1 && mold.equals("cool"))
{
counter += 1;
red = r - coolCost[0];
green = g - coolCost[1];
blue = b - coolCost[2];
Random generator = new Random();
int pick = generator.nextInt(3);
counter += minPhone(red, green, blue, names[pick]);
}
else if (r > 1 && g > 1 && b > 1 && mold.equals("modern"))
{
counter += 1;
red = r - modernCost[0];
green = g - modernCost[1];
blue = b - modernCost[2];
Random generator = new Random();
int pick = generator.nextInt(3);
counter += minPhone(red, green, blue, names[pick]);
}
return counter;
}
}
public static void main(String[] args)
{
ProblemSetThree.ProblemFour example = new ProblemFour();
String[] names = {"classic", "cool" , "modern"};
Random generator = new Random();
int pick = generator.nextInt(3);
//System.out.println(pick);
int testCount = example.minPhone(6, 7, 7, names[pick]);
System.out.println(testCount);
}
}
所以在这个例子中,正确的答案是 2,而不是 3。我的代码有时也会给出。如何确保它只返回最小数量?
在此之后,我需要把它变成一个动态编程程序。我对此代码的优化或软件工程方面不感兴趣,只是它返回正确的答案。
谢谢你。