vendredi 19 juin 2020

Assessing whether 2 inputted variable values can sum to a inputted value

I'm working on a small program where a method takes 3 int's bigCount smallCount and goal. These variables are supposed to represent the number of bags of flour in 2 sizes, the bigCount weight value is 5 kilos per bag, smallCount weight value is 1 kilo per bag and goal is the goal weight of the box that would contain the bags.

for example bigCount = 1, bigCount = 1, smallCount = 0, goal = 4

Should return a value of false since bigCount is given the value of 1 and 1 value in bigCount is representative of a 5 kilo bag and thus the bags that you have would never fit into a box with the weight requirement of 4.

At first, I tried to create a bunch of if and else if statements that would return a true value if the values of bigCount and smallCount could be added in a combination to sum to the weight given in the goal variable.

I feel like there is a much smarter way to go about this but I can't figure out an algorithm that could simply wrap all this up without all these if and else if statements. Currently, the logic for some of these if statements is incorrect and not catching all the scenarios to make it work properly.

public static boolean canPack(int bigCount, int smallCount, int goal){

            boolean isPackable = false;
            int bigBKilo = bigCount*5;
            int smallBKilo = smallCount*1;

            int remain5 = goal %5;

            int remainTest = 6 %5;

            int sum = bigBKilo+smallBKilo;

            if( bigCount < 0 || smallCount < 0 || goal <0){
                isPackable = false;
            }else{

                if(remain5 > 0 && remain5 <= smallCount && smallCount >= goal) {
                    isPackable = true;
                }
                else if(remain5 == 0 && bigCount > 0){
                    isPackable = true;
                }
                else if(bigCount == 0 && smallCount >= goal){
                    isPackable = true;
                }
                else if(smallCount ==0 && remain5 == 0){
                    isPackable = true;
                }
                else if(sum == goal){
                    isPackable = true;
                }
                else if(bigBKilo < goal && remain5 <= smallCount){
                    isPackable = true;
                }
                else if(bigCount == 0 && smallCount < goal){
                    isPackable = false;
                }
                else{
                    isPackable = false;
                }
            }

            return isPackable;


        }//end method

Aucun commentaire:

Enregistrer un commentaire