Skip to content

Commit

Permalink
CTCI 6.02: Basketball.groovy
Browse files Browse the repository at this point in the history
  • Loading branch information
Pap Lőrinc committed Mar 6, 2016
1 parent 787b3ca commit 9e28fdf
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/groovy/Ch06_MathAndLogicPuzzles/_06_02_Basketball.groovy
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)
}
}
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()
}
}

0 comments on commit 9e28fdf

Please sign in to comment.