Currently writing a program that finds the optimal ratio of 3 given numbers in an array. However the code I have currently only takes 3 numbers and arranges them to find the closest 3 number arrangement to 100. I need the code to be adaptable so that it takes the 3 numbers and gives the n number arrangement closest to 100.
public static int[] mmru(int[] array) {
int result = 1000;
int[] ideal = new int[0];
int closestResult = 100;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
result = 100 - array[i] - array[j] - array[k];
if (result == 0) {
ideal = new int[]{array[i], array[j], array[k]};
return ideal;
} else {
if (result < closestResult && result > 0) {
ideal = new int[]{array[i], array[j], array[k]};
closestResult = result;
}
}
}
}
}
return ideal;
}
the solution I have right now is to manually add more for loops and array elements.
Example - an array of 3 numbers, outputs arrangement of 8 numbers using the 3 numbers to get closest to 100. eg. [8,13,15] gives output of [8,8,13,13,13,15,15,15]
public static int[] mmrh8(int[] array) {
int result = 1000;
int[] ideal = new int[0];
int closestResult = 100;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
for (int o = 0; o < 3; o++) {
for (int p = 0; p < 3; p++) {
result = 100 - array[i] - array[j] - array[k] - array[l] - array[m] - array[n] - array[o] - array[p];
if (result == 0) {
ideal = new int[]{array[i], array[j], array[k], array[l], array[m], array[n], array[o], array[p]};
return ideal;
} else {
if (result < closestResult && result > 0) {
ideal = new int[]{array[i], array[j], array[k], array[l], array[m], array[n], array[o], array[p]};
closestResult = result;
}
}
}
}
}
}
}
}
}
}
return ideal;
}
Is there a way to allow for the number of for loops and array elements to be variable?
Any help appreciated thanks!