-
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
b91727f
commit 77599cd
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
src/main/groovy/Ch06_MathAndLogicPuzzles/_06_07_TheApocalypse.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,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())] | ||
} | ||
} | ||
} |
18 changes: 18 additions & 0 deletions
18
src/test/groovy/Ch06_MathAndLogicPuzzles/_06_07_TheApocalypseTest.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,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*/ | ||
} |