Skip to content

Instantly share code, notes, and snippets.

@stokito
Created November 17, 2014 17:10
Show Gist options
  • Save stokito/8d2f19f007da5a9cc1eb to your computer and use it in GitHub Desktop.
Save stokito/8d2f19f007da5a9cc1eb to your computer and use it in GitHub Desktop.
Test task
import spock.lang.Specification
import spock.lang.Unroll
/**
A programmer drinks exactly goalPints of beer every evening.
One evening, the programmer opens his fridge and sees a number of smallBottles of beer (1 pint each) and a number of bigBottles of beer (3 pints each).
The programmer needs to decide whether he can pick some bottles and start drinking, or has to run to the store to buy some more bottles.
The programmer is "greedy" and never consumes a bottle partially.
Write a Java-method which returns true if it is possible to make the goal by choosing from the given (whole) bottles, or false otherwise.
Note that it is not necessary to "take" all bottles — some may remain unused.
Method stub:
public boolean gotBeer(int goalPints, int smallBottles, int bigBottles) {
// TODO: implement me
}
Examples:
gotBeer(6, 3, 1) must return true
gotBeer(7, 3, 1) must return false
gotBeer(6, 3, 2) must return true
gotBeer(3, 0, 1) must return true
gotBeer(1, 0, 1) must return false
*/
class BeerSpec extends Specification {
private static final int BOTTLES_VOLUME_BIG = 3
private static final int BOTTLES_VOLUME_SMALL = 1
private boolean gotBeer(int goalPints, int smallBottles, int bigBottles) {
int volumeUsedByBigBottles = usedBigBottles(goalPints, bigBottles) * BOTTLES_VOLUME_BIG
def volumeUsedBySmallBottles = smallBottles * BOTTLES_VOLUME_SMALL
int restOfPints = goalPints - volumeUsedByBigBottles
return restOfPints <= volumeUsedBySmallBottles
}
@Unroll
def 'gotBeer() #goalPints #smallBottles #bigBottles #enoght'() {
expect: gotBeer(goalPints, smallBottles, bigBottles) == enoght
where:
goalPints | smallBottles | bigBottles | enoght
8 | 1 | 3 | false
7 | 1 | 3 | true
6 | 3 | 1 | true
7 | 3 | 1 | false
6 | 3 | 2 | true
3 | 0 | 1 | true
1 | 0 | 1 | false
}
int usedBigBottles(int goalPints, int bigBottles) {
int requiredBigBottles = goalPints / BOTTLES_VOLUME_BIG
return Math.min(requiredBigBottles, bigBottles)
}
@Unroll
def 'usedBigBottles() #goalPints #bigBottles #numBigBottles'() {
expect: usedBigBottles(goalPints, bigBottles) == numBigBottles
where:
goalPints | bigBottles | numBigBottles
8 | 3 | 2
7 | 3 | 2
7 | 1 | 1
1 | 1 | 0
6 | 1 | 1
6 | 2 | 2
3 | 1 | 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment