-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Pap Lőrinc
committed
Mar 6, 2016
1 parent
787b3ca
commit 9e28fdf
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
21 changes: 21 additions & 0 deletions
21
src/main/groovy/Ch06_MathAndLogicPuzzles/_06_02_Basketball.groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package Ch06_MathAndLogicPuzzles | ||
|
||
import groovy.transform.Memoized | ||
|
||
/** Calculate the probability of making a given number of basketball shots */ | ||
class _06_02_Basketball { | ||
/** Complexity: O(shotCount - successCount) */ | ||
static probability(int shotCount, int successCount) { | ||
def all = 2**shotCount | ||
def successful = (successCount..shotCount).sum(0) { int count -> | ||
factorial(shotCount) / (factorial(count) * factorial(shotCount - count)) | ||
} | ||
successful / all | ||
} | ||
|
||
@Memoized private static factorial(int num) { | ||
if (num < 0) throw new IllegalArgumentException() | ||
else if (num == 0) 1 | ||
else num * factorial(num - 1) | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
src/test/groovy/Ch06_MathAndLogicPuzzles/_06_02_BasketballTest.groovy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package Ch06_MathAndLogicPuzzles | ||
|
||
import spock.lang.Specification | ||
import spock.lang.Unroll | ||
|
||
import static Ch06_MathAndLogicPuzzles._06_02_Basketball.probability | ||
|
||
@Unroll class _06_02_BasketballTest extends Specification { | ||
/*@formatter:off*/ | ||
def 'basketball: successCount / shotCount?'() { | ||
expect: for (shotCount in 1..7) | ||
for (successCount in 0..shotCount) | ||
assert probability(shotCount, successCount) == simulatedProbability(shotCount, successCount) | ||
} | ||
/*@formatter:on*/ | ||
|
||
static simulatedProbability(int shotCount, int successCount) { | ||
def allCombinations = (0..shotCount).collectMany { ([true] * it + [false] * (shotCount - it)).permutations() } | ||
def correctCombinations = allCombinations.findAll { it.count(true) >= successCount } | ||
correctCombinations.size() / allCombinations.size() | ||
} | ||
} |