80 is arbitrary.
I thought 80 was actually an overkill. Originally I tried with 20 but changed it to 80 because I thought maybe I was getting an indexoutofbounds exception.
I went back, tried it with 'types' instead of 80, I removed the catch phrase, and it ran without error, so you must be right (I was still getting indexoutofbounds). Thanks!
My new code is
// author: blu
import java.util.Scanner;
public class Main
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int testcases;
testcases = input.nextInt();
int a = 0;
int empty, full, diffweights;
int types, b;
int[] coinvalue, coinweight;
while (a < testcases){
a++;
int impossible = 0;
empty = input.nextInt();
full = input.nextInt();
if (!(1 <= empty & empty <= full & full <= 10000)){
impossible = 2;
}
types = input.nextInt();
coinvalue = new int[types];
coinweight = new int[types];
b = 0;
while (b < types){
coinvalue[b] = input.nextInt();
coinweight[b] = input.nextInt();
if (coinweight[b] == 0){
impossible = 2;
coinweight[b] = 1;
}//end if
b++;
}
diffweights = full - empty;
int answer[] = new int[types]; //test to make sure answer[x] is not zero before assuming minimum
int counter = 0;
int h2, h3 = 100;
for (int d=0; d < coinweight.length; d++){
int c = diffweights / coinweight[d];
int c2 = diffweights % coinweight[d];
if (c2 == 0){
answer[counter++] = c * coinvalue[d];
}
else{
for (int g = 0; g < coinweight.length; g++){
int i2, i3, j2, j3 = 5;
h2 = c2 / coinweight[g];
h3 = c2 % coinweight[g];
if (h3 == 0)
answer[counter++] = c * coinvalue[d] + h2 * coinvalue[g];
else{
for (int i = 0; i < coinweight.length; i++){
i2 = h3 / coinweight[i];
i3 = h3 % coinweight[i];
if (i3 == 0)
answer[counter++] = c * coinvalue[d] + h2 * coinvalue[g] + i2 * coinvalue[i];
else{
for (int j = 0; j < coinweight.length; j++){
j2 = i3 / coinweight[j];
j3 = i3 % coinweight[j];
if (i3 == 0)
answer[counter++] = c * coinvalue[d] + h2 * coinvalue[g] + i2 * coinvalue[i] + j2 * coinvalue[j];
}
}
}
}
}//end for
}//end else
if (answer[0]==0 & impossible != 1 & impossible != 2){
System.out.println("This is impossible.");
impossible = 1;
}//end if
}//end for
int worstcase = answer[0];
for (int d = 0; d < answer.length - 1; d++){
if (answer[d] != 0 & answer[d+1] != 0)
worstcase = Math.min(answer[d], answer[d+1]);
}
if (impossible != 1 & impossible != 2)
System.out.printf("The minimum amount of money in the piggy-bank is %d.\n", worstcase);
if (impossible == 2)
System.out.println("This is impossible.");
}//end outer while loop (a < testcases)
}//end method main
}//end class PigBank
I added in a few extra for statements to further make sure it is truly impossible before declaring so. I also fixed up some spots that may be giving me 'wrong answer'. However now I get TLE, and yet I don't know how to further improve this code.
Any ideas? Thanks in advance.