A java practice problem
Your logic is incorrect. This should do it:
public boolean makeBricks(int small, int big, int goal) {
if (goal < 0 || big < 0 || small < 0) {
throw new IllegalArgumentException();
} else if (goal > big * 5 + small) {
return false;
} else if (goal % 5 <= small) {
return true;
} else {
return false;
}
}
is sufficient. This can be simplified to:
public boolean makeBricks(int small, int big, int goal) {
if (goal < 0 || big < 0 || small < 0) {
throw new IllegalArgumentException();
} else {
return goal <= big * 5 + small && goal % 5 <= small;
}
}
Of course, the sanity check on negative goal, small or big is not strictly required but recommended. Without those checks, the result can simply be obtained by:
public boolean makeBricks(int small, int big, int goal) {
return goal <= big * 5 + small && goal % 5 <= small;
}
I think you can just remove your second test. I would try this:
public boolean makeBricks(int small, int big, int goal) {
if (goal > small + big * 5)
return false;
else
return goal % 5 <= small;
}
The first test just checks how long the row would be if we just put all the bricks in a row. If that's not as long as the goal, then we know that it's impossible.
Next, we calculate the minimum number of small bricks: goal % 5
. For example, if the goal is 8 and we have 1000 large bricks, how many small bricks do we need? 8 % 5
is 3, so we need 3 small bricks at the end of the row.
If we have enough small bricks, and the total length of all the bricks is enough, then we can meet the goal.