英文:
Returning the different length to maximize profit when cuttting a rod
问题
以下是翻译好的代码部分:
public static void rodCut(int[] lengths, int[] profit, int len){
int lengthInput = lengths.length-1;
int[][] cuttingLength = new int[lengthInput + 1][len + 1];
int[] chosenElement = new int[lengthInput + 1];
int[][] maximum = new int[lengthInput + 1][len + 1];
int numA;
int numB=0;
int a = 1;
while(a <= lengthInput) {
int i=0;
while(i<=len) {
numA = maximum[a - 1][i];
if (i >= lengths[a]) {
numB = profit[a] + maximum[a - 1][i - lengths[a]];
}
maximum[a][i] = Math.max(numA,numB);
if(numA<numB) {
cuttingLength[a][i]=1;
}
else {
cuttingLength[a][i]=0;
}
i++;
numB=0;
}
a++;
}
//we represent the selected element with a 1, else, 0
int z = lengthInput;
int l = len;
while(z>0) {
if (cuttingLength[z][l] > 0){
chosenElement[z] = 1;
l = l - lengths[z];
}
else {
chosenElement[z] = 0;
}
z--;
}
//indicate which length it needs to be cut
int j=1;
String rods = "";
String tmp = "";
while(j<lengthInput+1) {
if (chosenElement[j] == 1) {
tmp+=lengths[j]+", ";
}
j++;
}
rods = tmp.substring(0,tmp.length()-2);
System.out.print("\nLengths to be cut: "+rods+"");
}
请注意,这是您提供的代码的翻译。如果您有任何问题或需要进一步帮助,请随时问我。
英文:
My program have to display in what different lengths to cut a rod in order to maximize profit.
This is my function for the rod cutting:
It takes as parameter an array lengths (1 to 8), an array profit (1,5,8,9,10,17,17,20), and the length of the rod.
public static void rodCut(int[] lengths, int[] profit, int len){
int lengthInput = lengths.length-1;
int[][] cuttingLength = new int[lengthInput + 1][len + 1];
int[] chosenElement = new int[lengthInput + 1];
int[][] maximum = new int[lengthInput + 1][len + 1];
int numA;
int numB=0;
int a = 1;
while(a <=lengthInput) {
int i=0;
while(i<=len) {
numA = maximum[a - 1][i];
if (i >= lengths[a]) {
numB = profit[a] + maximum[a - 1][i - lengths[a]];
}
maximum[a][i] = Math.max(numA,numB);
if(numA<numB) {
cuttingLength[a][i]=1;
}
else {
cuttingLength[a][i]=0;
}
i++;
numB=0;
}
a++;
}
//we represent the selected element with a 1, else, 0
int z = lengthInput;
int l = len;
while(z>0) {
if (cuttingLength[z][l] > 0){
chosenElement[z] = 1;
l = l - lengths[z];
}
else {
chosenElement[z] = 0;
}
z--;
}
//indicate which length it needs to be cut
int j=1;
String rods = "";
String tmp = "";
while(j<lengthInput+1) {
if (chosenElement[j] == 1) {
tmp+=lengths[j]+", ";
}
j++;
}
rods = tmp.substring(0,tmp.length()-2);
System.out.print("\nLengths to be cut: "+rods+"");
}
I am not getting the desired output when the length is large.
Suppose the length is 40.
The output should be : Lengths to be cut: 2,2,2,2,2,6,6,6,6,6
But i am getting: Lengths to be cut: 1,2,3,4,5,6,7,8
专注分享java语言的经验与见解,让所有开发者获益!
评论