fei - 11 months ago 53

Java Question

I came across this problem in javabat(http://www.javabat.com/prob/p183562):

We want to make a row of bricks that

is goal inches long. We have a number

of small bricks (1 inch each) and big

bricks (5 inches each). Return true if

it is possible to make the goal by

choosing from the given bricks. This

is a little harder than it looks and

can be done without any loops.

makeBricks(3, 1, 8) → true

makeBricks(3, 1, 9) → false

makeBricks(3, 2, 10) → true

I came up with this solution:

`public boolean makeBricks(int small, int big, int goal) {`

if (goal > small + big * 5)

return false;

else if (goal % 5 == 0)

return goal / 5 <= big;

else

return goal % 5 <= small;

}

This passed the test. But I found a counter-example myself: makeBricks(10, 0, 10) -> true. My logic will return false. How should I fix my logic? Or is there a better way to do this?

Answer

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;
}
```

Source (Stackoverflow)