Coding Exercise 24: Flour Park Problem

2021. 4. 1. 08:48Java programming

Write a method named canPack with three parameters of type int named bigCount, smallCount, and goal.

 

The parameter bigCount represents the count of big flour bags (5 kilos each).

 

The parameter smallCount represents the count of small flour bags (1 kilo each).

 

The parameter goal represents the goal amount of kilos of flour needed to assemble a package.

 

Therefore, the sum of the kilos of bigCount and smallCount must be at least equal to the value of goal. The method should return true if it is possible to make a package with goal kilos of flour.

 

If the sum is greater than goal, ensure that only full bags are used towards the goal amount. For example, if goal = 9, boigCount = 2, and smallCount = 0, the method should return false since each big bag is 5 kilos and cannot be divided. However, if goal = 9, bigCount = 1, and smallCount = 5, the method should return true because of 1 full bigCount bag and 4 full smallCount bags equal goal, and it's okay if there are additional bags left over.

 

If any of the parameters are negative, return false.

 

 

public class FlourPacker {
    public static boolean canPack(int bigCount, int smallCount, int goal){
        if (bigCount < 0 || smallCount < 0 || goal < 0)
            return false;

        int j = smallCount;
        while (j >= 0){

            int i = 5 * bigCount;
            while (i >= 0){

                if (i + j == goal){
                    return true;
                }
                i = i - 5;
            }

            j--;

        } return false;

    }
}

The coding answer I've promgrammed seems more of simple but took a while to understand and contemplate the algorithm.

'Java programming' 카테고리의 다른 글

Coding Exercise 26: Diagonal Star  (0) 2021.04.03
Coding Exercise 25: Largest Prime  (0) 2021.04.02
Coding Exercise 23: Number to Words  (0) 2021.03.31
Coding Exercise 22: Perfect Number  (0) 2021.03.30
Coding Exercise 21: All Factors  (0) 2021.03.29