Skip to content

Commit

Permalink
CTCI 6.07: TheApocalypse.groovy
Browse files Browse the repository at this point in the history
  • Loading branch information
Pap Lőrinc committed Mar 6, 2016
1 parent b91727f commit 77599cd
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package Ch06_MathAndLogicPuzzles

import static Ch06_MathAndLogicPuzzles._06_07_TheApocalypse.Gender.FEMALE

/** What would be the ratio of men/women, if people would stop having children immediately after having a girl?
* 1/2 would have 1 girl
* 1/4 would have 1 boy and 1 girl
* 1/8 would have 2 boys and 1 girl
* 1/16 would have 3 boys and 1 girl
* ...
* boy/girl ratio = 0/2 + 1/4 + 2/8 + 3/16 + ... (n-1)/2**n == 1 for n→∞
* */
class _06_07_TheApocalypse {
static ratio(int familyCount) {
def (males, females) = [familyCount, familyCount]
(1..familyCount).each {
while (Gender.random != FEMALE)
males++
females++
}
males / females
}

private static enum Gender {
MALE, FEMALE

private static rand = new Random()
static getRandom() {
def genders = values()
genders[rand.nextInt(genders.size())]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package Ch06_MathAndLogicPuzzles

import spock.lang.Specification
import spock.lang.Unroll

import static Ch06_MathAndLogicPuzzles._06_07_TheApocalypse.ratio
import static java.lang.Math.abs

@Unroll class _06_07_TheApocalypseTest extends Specification {
/*@formatter:off*/
def 'theApocalypse?'() {
expect: (500..1000).each { familyCount ->
def result = ratio(familyCount)
assert abs(result - 1) < 2/10
}
}
/*@formatter:on*/
}

0 comments on commit 77599cd

Please sign in to comment.